@owlmeans/socket 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 OwlMeans Common — Fullstack typescript framework
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,434 @@
1
+ # @owlmeans/socket
2
+
3
+ Common WebSocket communication library for OwlMeans applications. This package provides a unified abstraction for real-time communication across server, web, and mobile environments with support for RPC calls, event handling, authentication, and message queuing.
4
+
5
+ ## Overview
6
+
7
+ The `@owlmeans/socket` package provides:
8
+
9
+ - **Connection Abstraction**: Unified interface for WebSocket connections across platforms
10
+ - **RPC Communication**: Remote procedure call support with timeout and error handling
11
+ - **Event System**: Publish/subscribe event handling for real-time updates
12
+ - **Authentication Integration**: Built-in authentication flow support
13
+ - **Message Queuing**: Queue management for reliable message delivery
14
+ - **Request/Response Pattern**: Structured request/response communication
15
+ - **Error Handling**: Comprehensive error handling with resilient error types
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @owlmeans/socket
21
+ ```
22
+
23
+ ## Core Concepts
24
+
25
+ ### Connection Interface
26
+
27
+ The `Connection` interface provides a unified API for WebSocket communication, supporting various message types and communication patterns.
28
+
29
+ ### Message Types
30
+
31
+ Different message types enable various communication patterns:
32
+ - **Call/Result**: RPC-style method calls with responses
33
+ - **Request/Response**: Structured request/response patterns
34
+ - **Event**: Publish/subscribe event notifications
35
+ - **Auth**: Authentication-specific messages
36
+
37
+ ### Authentication Integration
38
+
39
+ Built-in support for authentication flows with stage-based progression and secure communication.
40
+
41
+ ## API Reference
42
+
43
+ ### Types
44
+
45
+ #### `Connection`
46
+ Core connection interface for WebSocket communication.
47
+
48
+ ```typescript
49
+ interface Connection {
50
+ stage: AuthenticationStage // Current authentication stage
51
+ notify: <T>(event: string, payload: T) => Promise<void> // Send events
52
+ observe: <T>(event: string, handler: (event: EventMessage<T>) => Promise<void>) => () => void // Listen to events
53
+ call: <R, T extends any[]>(method: string, ...payload: T) => Promise<R> // RPC calls
54
+ perform: <R, T extends any[]>(method: string, handler: CallHendler<R, T>) => void // Handle RPC calls
55
+ request: <T, R>(payload: T, observer?: (payload: R) => Promise<boolean>) => Promise<() => void> // Send requests
56
+ reply: <T>(id: string, payload: T) => Promise<void> // Reply to requests
57
+ auth: <T, R>(stage: AuthenticationStage, payload: T) => Promise<R> // Authentication
58
+ close: () => Promise<void> // Close connection
59
+ }
60
+ ```
61
+
62
+ #### `Message<T>`
63
+ Base message structure for all communication.
64
+
65
+ ```typescript
66
+ interface Message<T> {
67
+ type: MessageType // Message type identifier
68
+ id?: string // Unique message ID
69
+ sender?: string // Sender identifier
70
+ recipient?: string // Recipient identifier
71
+ dt?: number // Timestamp
72
+ payload: T // Message payload
73
+ }
74
+ ```
75
+
76
+ #### `MessageType`
77
+ Enumeration of supported message types.
78
+
79
+ ```typescript
80
+ enum MessageType {
81
+ Call = 'call', // RPC method calls
82
+ Result = 'result', // RPC method results
83
+ Error = 'error', // Error responses
84
+ Request = 'request', // Request messages
85
+ Response = 'response', // Response messages
86
+ Event = 'event', // Event notifications
87
+ Message = 'message', // General messages
88
+ Auth = 'auth', // Authentication messages
89
+ System = 'system' // System messages
90
+ }
91
+ ```
92
+
93
+ ## Usage Examples
94
+
95
+ ### Basic Connection Usage
96
+
97
+ ```typescript
98
+ import { Connection, MessageType } from '@owlmeans/socket'
99
+
100
+ // Assuming connection is established
101
+ const connection: Connection = await createConnection()
102
+
103
+ // Send an event
104
+ await connection.notify('user-online', { userId: '123', status: 'active' })
105
+
106
+ // Listen for events
107
+ const unsubscribe = connection.observe('chat-message', async (event) => {
108
+ console.log('New message:', event.payload)
109
+ })
110
+
111
+ // Make RPC call
112
+ const result = await connection.call('getUserProfile', '123')
113
+ console.log('User profile:', result)
114
+
115
+ // Handle RPC calls
116
+ connection.perform('echo', async (message: string) => {
117
+ return `Echo: ${message}`
118
+ })
119
+ ```
120
+
121
+ ### Event System
122
+
123
+ ```typescript
124
+ // Publisher
125
+ await connection.notify('order-status-changed', {
126
+ orderId: 'order-123',
127
+ status: 'shipped',
128
+ timestamp: Date.now()
129
+ })
130
+
131
+ // Subscriber
132
+ const unsubscribe = connection.observe('order-status-changed', async (event) => {
133
+ const { orderId, status } = event.payload
134
+ console.log(`Order ${orderId} is now ${status}`)
135
+
136
+ // Update UI or trigger other actions
137
+ await updateOrderDisplay(orderId, status)
138
+ })
139
+
140
+ // Cleanup
141
+ unsubscribe()
142
+ ```
143
+
144
+ ### RPC Communication
145
+
146
+ ```typescript
147
+ // Client-side: Make calls
148
+ try {
149
+ const users = await connection.call('getUsers', { page: 1, limit: 10 })
150
+ const user = await connection.call('getUserById', '123')
151
+ const updated = await connection.call('updateUser', '123', { name: 'John Doe' })
152
+ } catch (error) {
153
+ console.error('RPC call failed:', error)
154
+ }
155
+
156
+ // Server-side: Handle calls
157
+ connection.perform('getUsers', async (options: { page: number, limit: number }) => {
158
+ const users = await userService.list(options)
159
+ return users
160
+ })
161
+
162
+ connection.perform('getUserById', async (id: string) => {
163
+ const user = await userService.get(id)
164
+ if (!user) {
165
+ throw new Error('User not found')
166
+ }
167
+ return user
168
+ })
169
+
170
+ connection.perform('updateUser', async (id: string, data: Partial<User>) => {
171
+ return await userService.update(id, data)
172
+ })
173
+ ```
174
+
175
+ ### Request/Response Pattern
176
+
177
+ ```typescript
178
+ // Send request and handle responses
179
+ const unsubscribe = await connection.request(
180
+ { action: 'stream-data', filters: { category: 'important' } },
181
+ async (response) => {
182
+ console.log('Received chunk:', response)
183
+ // Return true to continue receiving, false to stop
184
+ return response.hasMore
185
+ }
186
+ )
187
+
188
+ // Handle incoming requests
189
+ const unsubscribeHandler = connection.acknowledge(async (id: string, payload: any) => {
190
+ const { action, filters } = payload
191
+
192
+ if (action === 'stream-data') {
193
+ // Process request and send responses
194
+ const chunks = await getDataChunks(filters)
195
+
196
+ for (const chunk of chunks) {
197
+ await connection.reply(id, {
198
+ data: chunk,
199
+ hasMore: chunk.index < chunks.length - 1
200
+ })
201
+ }
202
+
203
+ return true // Request handled
204
+ }
205
+
206
+ return false // Request not handled
207
+ })
208
+ ```
209
+
210
+ ### Authentication Flow
211
+
212
+ ```typescript
213
+ // Authenticate connection
214
+ try {
215
+ // Start authentication
216
+ let stage = AuthenticationStage.Init
217
+ let result = await connection.auth(stage, { clientId: 'my-app' })
218
+
219
+ // Continue authentication based on challenge
220
+ if (result.challenge) {
221
+ stage = AuthenticationStage.Authenticate
222
+ result = await connection.auth(stage, {
223
+ response: await generateAuthResponse(result.challenge)
224
+ })
225
+ }
226
+
227
+ console.log('Authentication successful:', result)
228
+ } catch (error) {
229
+ console.error('Authentication failed:', error)
230
+ }
231
+
232
+ // Check authentication status
233
+ if (connection.stage === AuthenticationStage.Authenticated) {
234
+ // Perform authenticated operations
235
+ await connection.call('getProtectedData')
236
+ }
237
+ ```
238
+
239
+ ### Message Queuing
240
+
241
+ ```typescript
242
+ // Enqueue messages for delivery
243
+ await connection.enqueue({
244
+ type: 'user-notification',
245
+ userId: '123',
246
+ message: 'Welcome!'
247
+ })
248
+
249
+ await connection.enqueue({
250
+ type: 'system-alert',
251
+ level: 'warning',
252
+ text: 'Maintenance scheduled'
253
+ }, 'maintenance-alert-1')
254
+
255
+ // Check queue status
256
+ const queueSize = connection.enqueued()
257
+ console.log(`${queueSize} messages queued`)
258
+
259
+ // Consume queued messages
260
+ const consumed = connection.consume()
261
+ if (consumed) {
262
+ const [payload, id, remaining] = consumed
263
+ console.log('Consumed message:', payload, 'ID:', id, 'Remaining:', remaining)
264
+ }
265
+
266
+ // Consume with filter
267
+ const alertsOnly = connection.consume((payload: any) => payload.type === 'system-alert')
268
+ ```
269
+
270
+ ### Connection Lifecycle
271
+
272
+ ```typescript
273
+ // Listen to connection events
274
+ const unsubscribeListener = connection.listen(async (message) => {
275
+ console.log('Connection message:', message)
276
+
277
+ // Handle connection-level events
278
+ if (typeof message === 'string') {
279
+ console.log('Raw message:', message)
280
+ } else {
281
+ switch (message.type) {
282
+ case MessageType.System:
283
+ console.log('System message:', message.payload)
284
+ break
285
+ case MessageType.Error:
286
+ console.error('Connection error:', message.payload)
287
+ break
288
+ }
289
+ }
290
+ })
291
+
292
+ // Handle connection cleanup
293
+ const handleConnectionClose = async () => {
294
+ // Unsubscribe from events
295
+ unsubscribeListener()
296
+
297
+ // Clean up resources
298
+ await connection.close()
299
+ }
300
+
301
+ // Handle process termination
302
+ process.on('SIGTERM', handleConnectionClose)
303
+ process.on('SIGINT', handleConnectionClose)
304
+ ```
305
+
306
+ ### Error Handling
307
+
308
+ ```typescript
309
+ import { SocketError } from '@owlmeans/socket'
310
+
311
+ try {
312
+ await connection.call('riskyOperation', data)
313
+ } catch (error) {
314
+ if (error instanceof SocketError) {
315
+ console.error('Socket error:', error.message)
316
+
317
+ // Handle specific socket errors
318
+ switch (error.code) {
319
+ case 'TIMEOUT':
320
+ console.log('Call timed out')
321
+ break
322
+ case 'CONNECTION_LOST':
323
+ console.log('Connection lost, attempting reconnect...')
324
+ await reconnectSocket()
325
+ break
326
+ case 'AUTH_FAILED':
327
+ console.log('Authentication failed')
328
+ await reauthenticate()
329
+ break
330
+ }
331
+ }
332
+ }
333
+ ```
334
+
335
+ ## Advanced Features
336
+
337
+ ### Custom Message Preparation
338
+
339
+ ```typescript
340
+ // Implement custom message preparation
341
+ const customConnection: Connection = {
342
+ ...baseConnection,
343
+
344
+ prepare: <T>(message: Message<T>, isRequest?: boolean) => {
345
+ // Add custom headers or encryption
346
+ return {
347
+ ...message,
348
+ sender: 'my-service',
349
+ dt: Date.now(),
350
+ // Add custom processing
351
+ }
352
+ }
353
+ }
354
+ ```
355
+
356
+ ### Timeout Configuration
357
+
358
+ ```typescript
359
+ // Set default timeout
360
+ connection.defaultCallTimeout = 30000 // 30 seconds
361
+
362
+ // Use custom timeout for specific calls
363
+ try {
364
+ const result = await connection.call('longRunningOperation', data)
365
+ } catch (error) {
366
+ if (error.message.includes('timeout')) {
367
+ console.log('Operation timed out')
368
+ }
369
+ }
370
+ ```
371
+
372
+ ### Connection Multiplexing
373
+
374
+ ```typescript
375
+ // Handle multiple concurrent operations
376
+ const operations = [
377
+ connection.call('operation1', data1),
378
+ connection.call('operation2', data2),
379
+ connection.call('operation3', data3)
380
+ ]
381
+
382
+ const results = await Promise.allSettled(operations)
383
+ results.forEach((result, index) => {
384
+ if (result.status === 'fulfilled') {
385
+ console.log(`Operation ${index + 1} succeeded:`, result.value)
386
+ } else {
387
+ console.error(`Operation ${index + 1} failed:`, result.reason)
388
+ }
389
+ })
390
+ ```
391
+
392
+ ## Integration with OwlMeans Ecosystem
393
+
394
+ The `@owlmeans/socket` package integrates with:
395
+
396
+ - **@owlmeans/auth**: Authentication stages and flows
397
+ - **@owlmeans/error**: Resilient error handling
398
+ - **@owlmeans/client-socket**: Client-side WebSocket implementation
399
+ - **@owlmeans/server-socket**: Server-side WebSocket implementation
400
+ - **@owlmeans/context**: Service registration and lifecycle management
401
+
402
+ ## Constants
403
+
404
+ ```typescript
405
+ const CALL_TIMEOUT = 60000 // Default RPC call timeout (60 seconds)
406
+ ```
407
+
408
+ ## Best Practices
409
+
410
+ ### Connection Management
411
+ - Always handle connection lifecycle events
412
+ - Implement proper reconnection logic
413
+ - Clean up event listeners on disconnect
414
+ - Use appropriate timeouts for different operations
415
+
416
+ ### Error Handling
417
+ - Implement comprehensive error handling for all communication patterns
418
+ - Use appropriate retry strategies for failed operations
419
+ - Log connection events for debugging
420
+ - Handle authentication failures gracefully
421
+
422
+ ### Performance
423
+ - Use appropriate message batching for high-frequency events
424
+ - Implement efficient event filtering
425
+ - Consider message compression for large payloads
426
+ - Monitor connection performance and adjust timeouts
427
+
428
+ ### Security
429
+ - Always authenticate connections before sensitive operations
430
+ - Validate all incoming messages and payloads
431
+ - Use secure WebSocket connections (WSS) in production
432
+ - Implement proper authorization checks for RPC methods
433
+
434
+ Fixes #32.
package/build/.gitkeep ADDED
File without changes
@@ -0,0 +1,13 @@
1
+ export declare enum MessageType {
2
+ Call = "call",
3
+ Result = "result",
4
+ Error = "error",
5
+ Request = "request",
6
+ Response = "response",
7
+ Event = "event",
8
+ Message = "message",
9
+ Auth = "auth",
10
+ System = "system"
11
+ }
12
+ export declare const CALL_TIMEOUT = 60000;
13
+ //# sourceMappingURL=consts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AACA,oBAAY,WAAW;IACrB,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,OAAO,YAAY;IACnB,QAAQ,aAAa;IACrB,KAAK,UAAU;IACf,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,MAAM,WAAW;CAClB;AAED,eAAO,MAAM,YAAY,QAAQ,CAAA"}
@@ -0,0 +1,14 @@
1
+ export var MessageType;
2
+ (function (MessageType) {
3
+ MessageType["Call"] = "call";
4
+ MessageType["Result"] = "result";
5
+ MessageType["Error"] = "error";
6
+ MessageType["Request"] = "request";
7
+ MessageType["Response"] = "response";
8
+ MessageType["Event"] = "event";
9
+ MessageType["Message"] = "message";
10
+ MessageType["Auth"] = "auth";
11
+ MessageType["System"] = "system";
12
+ })(MessageType || (MessageType = {}));
13
+ export const CALL_TIMEOUT = 60000;
14
+ //# sourceMappingURL=consts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consts.js","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AACA,MAAM,CAAN,IAAY,WAUX;AAVD,WAAY,WAAW;IACrB,4BAAa,CAAA;IACb,gCAAiB,CAAA;IACjB,8BAAe,CAAA;IACf,kCAAmB,CAAA;IACnB,oCAAqB,CAAA;IACrB,8BAAe,CAAA;IACf,kCAAmB,CAAA;IACnB,4BAAa,CAAA;IACb,gCAAiB,CAAA;AACnB,CAAC,EAVW,WAAW,KAAX,WAAW,QAUtB;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,CAAA"}
@@ -0,0 +1,34 @@
1
+ import { ResilientError } from '@owlmeans/error';
2
+ export declare class SocketError extends ResilientError {
3
+ static typeName: string;
4
+ constructor(message?: string);
5
+ }
6
+ export declare class SocketInitializationError extends SocketError {
7
+ static typeName: string;
8
+ constructor(message?: string);
9
+ }
10
+ export declare class SocketConnectionError extends SocketError {
11
+ static typeName: string;
12
+ constructor(message?: string);
13
+ }
14
+ export declare class SocketUnauthorized extends SocketConnectionError {
15
+ static typeName: string;
16
+ constructor(message?: string);
17
+ }
18
+ export declare class SocketUnsupported extends SocketConnectionError {
19
+ static typeName: string;
20
+ constructor(message?: string);
21
+ }
22
+ export declare class SocketTimeout extends SocketError {
23
+ static typeName: string;
24
+ constructor(message?: string);
25
+ }
26
+ export declare class SocketMessageError extends SocketError {
27
+ static typeName: string;
28
+ constructor(message?: string);
29
+ }
30
+ export declare class SocketMessageMalformed extends SocketMessageError {
31
+ static typeName: string;
32
+ constructor(message?: string);
33
+ }
34
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAEhD,qBAAa,WAAY,SAAQ,cAAc;IAC7C,OAAuB,QAAQ,EAAE,MAAM,CAAgB;gBAE3C,OAAO,GAAE,MAAgB;CAGtC;AAED,qBAAa,yBAA0B,SAAQ,WAAW;IACxD,OAAuB,QAAQ,EAAE,MAAM,CAA0C;gBAErE,OAAO,GAAE,MAAgB;CAItC;AAED,qBAAa,qBAAsB,SAAQ,WAAW;IACpD,OAAuB,QAAQ,EAAE,MAAM,CAAsC;gBAEjE,OAAO,GAAE,MAAgB;CAItC;AAED,qBAAa,kBAAmB,SAAQ,qBAAqB;IAC3D,OAAuB,QAAQ,EAAE,MAAM,CAAkD;gBAE7E,OAAO,GAAE,MAAgB;CAItC;AAED,qBAAa,iBAAkB,SAAQ,qBAAqB;IAC1D,OAAuB,QAAQ,EAAE,MAAM,CAAiD;gBAE5E,OAAO,GAAE,MAAgB;CAItC;AAED,qBAAa,aAAc,SAAQ,WAAW;IAC5C,OAAuB,QAAQ,EAAE,MAAM,CAAmC;gBAE9D,OAAO,GAAE,MAAgB;CAItC;AAED,qBAAa,kBAAmB,SAAQ,WAAW;IACjD,OAAuB,QAAQ,EAAE,MAAM,CAAmC;gBAE9D,OAAO,GAAE,MAAgB;CAItC;AAED,qBAAa,sBAAuB,SAAQ,kBAAkB;IAC5D,OAAuB,QAAQ,EAAE,MAAM,CAA4C;gBAEvE,OAAO,GAAE,MAAgB;CAItC"}
@@ -0,0 +1,65 @@
1
+ import { ResilientError } from '@owlmeans/error';
2
+ export class SocketError extends ResilientError {
3
+ static typeName = 'SocketError';
4
+ constructor(message = 'error') {
5
+ super(SocketError.typeName, `socket:${message}`);
6
+ }
7
+ }
8
+ export class SocketInitializationError extends SocketError {
9
+ static typeName = `${SocketError.typeName}Initialization`;
10
+ constructor(message = 'error') {
11
+ super(`initialization:${message}`);
12
+ this.type = SocketInitializationError.typeName;
13
+ }
14
+ }
15
+ export class SocketConnectionError extends SocketError {
16
+ static typeName = `${SocketError.typeName}Connection`;
17
+ constructor(message = 'error') {
18
+ super(`connection:${message}`);
19
+ this.type = SocketConnectionError.typeName;
20
+ }
21
+ }
22
+ export class SocketUnauthorized extends SocketConnectionError {
23
+ static typeName = `${SocketConnectionError.typeName}Unauthorized`;
24
+ constructor(message = 'error') {
25
+ super(`unauthorized:${message}`);
26
+ this.type = SocketUnauthorized.typeName;
27
+ }
28
+ }
29
+ export class SocketUnsupported extends SocketConnectionError {
30
+ static typeName = `${SocketConnectionError.typeName}Unsupported`;
31
+ constructor(message = 'error') {
32
+ super(`unsupported:${message}`);
33
+ this.type = SocketUnsupported.typeName;
34
+ }
35
+ }
36
+ export class SocketTimeout extends SocketError {
37
+ static typeName = `${SocketError.typeName}Timeout`;
38
+ constructor(message = 'error') {
39
+ super(`timeout:${message}`);
40
+ this.type = SocketTimeout.typeName;
41
+ }
42
+ }
43
+ export class SocketMessageError extends SocketError {
44
+ static typeName = `${SocketError.typeName}Message`;
45
+ constructor(message = 'error') {
46
+ super(`message:${message}`);
47
+ this.type = SocketMessageError.typeName;
48
+ }
49
+ }
50
+ export class SocketMessageMalformed extends SocketMessageError {
51
+ static typeName = `${SocketMessageError.typeName}Malformed`;
52
+ constructor(message = 'error') {
53
+ super(`malformed:${message}`);
54
+ this.type = SocketMessageMalformed.typeName;
55
+ }
56
+ }
57
+ ResilientError.registerErrorClass(SocketError);
58
+ ResilientError.registerErrorClass(SocketInitializationError);
59
+ ResilientError.registerErrorClass(SocketConnectionError);
60
+ ResilientError.registerErrorClass(SocketUnauthorized);
61
+ ResilientError.registerErrorClass(SocketUnsupported);
62
+ ResilientError.registerErrorClass(SocketTimeout);
63
+ ResilientError.registerErrorClass(SocketMessageError);
64
+ Res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AC,kBAAkB,CAAC,aAAa,CAAC,CAAA;AAChD,cAAc,CAAC,kBAAkB,CAAC,kBAAkB,CAAC,CAAA;AACrD,cAAc,CAAC,kBAAkB,CAAC,sBAAsB,CAAC,CAAA"}
@@ -0,0 +1,6 @@
1
+ import type { CallMessage, EventMessage, Message, AuthMessage } from './types.js';
2
+ export declare const isMessage: <P, T extends Message<P>>(msg: string | T, nonSystem?: boolean) => msg is T;
3
+ export declare const isEventMessage: <P>(msg: string | Message<P>, system?: boolean) => msg is EventMessage<P>;
4
+ export declare const isCallMessage: <P extends any[]>(msg: string | Message<unknown>) => msg is CallMessage<P>;
5
+ export declare const isAuthMessage: <P>(msg: string | Message<P>) => msg is AuthMessage<P>;
6
+ //# sourceMappingURL=helper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helper.d.ts","sourceRoot":"","sources":["../src/helper.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAEjF,eAAO,MAAM,SAAS,GAAI,CAAC,EAAE,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,OAAO,MAAM,GAAG,CAAC,cAAc,OAAO,KAAG,GAAG,IAAI,CAEhB,CAAA;AAEjF,eAAO,MAAM,cAAc,GAAI,CAAC,OAAO,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,WAAW,OAAO,KAAG,GAAG,IAAI,YAAY,CAAC,CAAC,CAEzB,CAAA;AAE3E,eAAO,MAAM,aAAa,GAAI,CAAC,SAAS,GAAG,EAAE,OAAO,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,KAAG,GAAG,IAAI,WAAW,CAAC,CAAC,CACnD,CAAA;AAEjD,eAAO,MAAM,aAAa,GAAI,CAAC,OAAO,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,KAAG,GAAG,IAAI,WAAW,CAAC,CAAC,CAC/B,CAAA"}
@@ -0,0 +1,26 @@
1
+ import { MessageType } from './consts.js';
2
+ export const isMessage = (msg, nonSystem) => typeof msg === 'object' && 'type' in msg && 'payload' in msg
3
+ && (nonSystem === undefined || nonSystem === (msg.type !== MessageType.System));
4
+ export const isEventMessage = (msg, system) => isMessage(msg) && [MessageType.Event, MessageType.System].includes(msg.type)
5
+ && (system === undefined || system === (msg.type === MessageType.System));
6
+ export const isCallMessage = (msg) => isMessage(msg) && msg.type === MessageType.Call;
7
+ export const isAuthMessage = (msg) => isMessage(msg) && msg.type === MessageType.Auth;
8
+ // export const prepareLongCalls = (connection: Connection, longTimeout = CALL_TIMEOUT * 10) => {
9
+ // const _connection = connection as WithLongCalls
10
+ // if (_connection[long_calls] == null) {
11
+ // const prepare = connection.prepare
12
+ // connection.prepare = (message, isRequest) => {
13
+ // if (!isRequest && isCallMessage(message)) {
14
+ // message.timeout = longTimeout
15
+ // }
16
+ // return prepare?.(message, isRequest) ?? message
17
+ // }
18
+ // _connection[long_calls] = true
19
+ // }
20
+ // return connection
21
+ // }
22
+ // const long_calls = Symbol('__prepare_with_long_calls')
23
+ // interface WithLongCalls extends Connection {
24
+ // [long_calls]: boolean
25
+ // }
26
+ //# sourceMappingURL=helper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../src/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAGzC,MAAM,CAAC,MAAM,SAAS,GAAG,CAA0B,GAAe,EAAE,SAAmB,EAAY,EAAE,CACnG,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,IAAI,SAAS,IAAI,GAAG;OACzD,CAAC,SAAS,KAAK,SAAS,IAAI,SAAS,KAAK,CAAC,GAAG,CAAC,IAAI,KAAK,WAAW,CAAC,MAAM,CAAC,CAAC,CAAA;AAEjF,MAAM,CAAC,MAAM,cAAc,GAAG,CAAI,GAAwB,EAAE,MAAgB,EAA0B,EAAE,CACtG,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC;OACzE,CAAC,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,CAAC,GAAG,CAAC,IAAI,KAAK,WAAW,CAAC,MAAM,CAAC,CAAC,CAAA;AAE3E,MAAM,CAAC,MAAM,aAAa,GAAG,CAAkB,GAA8B,EAAyB,EAAE,CACtG,SAAS,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW,CAAC,IAAI,CAAA;AAEjD,MAAM,CAAC,MAAM,aAAa,GAAG,CAAI,GAAwB,EAAyB,EAAE,CAClF,SAAS,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW,CAAC,IAAI,CAAA;AAGjD,iGAAiG;AACjG,oDAAoD;AACpD,2CAA2C;AAC3C,yCAAyC;AACzC,qDAAqD;AACrD,oDAAoD;AACpD,wCAAwC;AACxC,UAAU;AAEV,wDAAwD;AACxD,QAAQ;AACR,qCAAqC;AACrC,MAAM;AAEN,sBAAsB;AACtB,IAAI;AAEJ,yDAAyD;AACzD,+CAA+C;AAC/C,0BAA0B;AAC1B,IAAI"}
@@ -0,0 +1,6 @@
1
+ export type * from './types.js';
2
+ export * from './consts.js';
3
+ export * from './model.js';
4
+ export * from './errors.js';
5
+ export * from './helper.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,mBAAmB,YAAY,CAAA;AAC/B,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,aAAa,CAAA;AAC3B,cAAc,aAAa,CAAA"}
package/build/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './consts.js';
2
+ export * from './model.js';
3
+ export * from './errors.js';
4
+ export * from './helper.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,aAAa,CAAA;AAC3B,cAAc,aAAa,CAAA"}
@@ -0,0 +1,3 @@
1
+ import type { Connection } from './types.js';
2
+ export declare const createBasicConnection: () => Connection;
3
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAC2C,UAAU,EAEhE,MAAM,YAAY,CAAA;AAInB,eAAO,MAAM,qBAAqB,QAAO,UA+VxC,CAAA"}