@nmtjs/ws-transport 0.1.8 → 0.2.1

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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
+ export * from "./lib/injectables.js";
1
2
  export * from "./lib/server.js";
2
3
  export * from "./lib/transport.js";
3
4
  export * from "./lib/types.js";
4
5
  export * from "./lib/utils.js";
5
- export * from "./lib/injectables.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../index.ts"],"sourcesContent":["export * from './lib/server.ts'\nexport * from './lib/transport.ts'\nexport * from './lib/types.ts'\nexport * from './lib/utils.ts'\nexport * from './lib/injectables.ts'\n"],"names":[],"mappings":"AAAA,cAAc,kBAAiB;AAC/B,cAAc,qBAAoB;AAClC,cAAc,iBAAgB;AAC9B,cAAc,iBAAgB;AAC9B,cAAc,uBAAsB"}
1
+ {"version":3,"sources":["../../index.ts"],"sourcesContent":["export * from './lib/injectables.ts'\nexport * from './lib/server.ts'\nexport * from './lib/transport.ts'\nexport * from './lib/types.ts'\nexport * from './lib/utils.ts'\n"],"names":[],"mappings":"AAAA,cAAc,uBAAsB;AACpC,cAAc,kBAAiB;AAC/B,cAAc,qBAAoB;AAClC,cAAc,iBAAgB;AAC9B,cAAc,iBAAgB"}
@@ -1,2 +1,5 @@
1
- import { injectables } from '@nmtjs/application';
2
- export const connectionData = injectables.connectionData;
1
+ import { ProtocolInjectables } from '@nmtjs/protocol/server';
2
+ const connectionData = ProtocolInjectables.connectionData;
3
+ export const WsTransportInjectables = {
4
+ connectionData
5
+ };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../lib/injectables.ts"],"sourcesContent":["import {\n type LazyInjectable,\n type Scope,\n injectables,\n} from '@nmtjs/application'\nimport type { WsConnectionData } from './types.ts'\n\nexport const connectionData = injectables.connectionData as LazyInjectable<\n WsConnectionData,\n Scope.Connection\n>\n"],"names":["injectables","connectionData"],"mappings":"AAAA,SAGEA,WAAW,QACN,qBAAoB;AAG3B,OAAO,MAAMC,iBAAiBD,YAAYC,cAAc,CAGvD"}
1
+ {"version":3,"sources":["../../../lib/injectables.ts"],"sourcesContent":["import type { LazyInjectable, Scope } from '@nmtjs/core'\nimport { ProtocolInjectables } from '@nmtjs/protocol/server'\nimport type { WsUserData } from './types.ts'\n\nconst connectionData = ProtocolInjectables.connectionData as LazyInjectable<\n WsUserData['request'],\n Scope.Connection\n>\n\nexport const WsTransportInjectables = {\n connectionData,\n} as const\n"],"names":["ProtocolInjectables","connectionData","WsTransportInjectables"],"mappings":"AACA,SAASA,mBAAmB,QAAQ,yBAAwB;AAG5D,MAAMC,iBAAiBD,oBAAoBC,cAAc;AAKzD,OAAO,MAAMC,yBAAyB;IACpCD;AACF,EAAU"}
@@ -1,18 +1,20 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { ApiError, Scope, ServerDownStream, ServerUpStream, SubscriptionResponse, builtin, onAbort } from '@nmtjs/application';
3
- import { MessageType, TransportType, decodeNumber, encodeNumber } from '@nmtjs/common';
4
1
  import { App, SSLApp } from 'uWebSockets.js';
5
- import { connectionData } from "./injectables.js";
6
- import { InternalError, getFormat, getRequestData, send, sendMessage, sendRpcMessage } from "./utils.js";
2
+ import assert from 'node:assert';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createPromise } from '@nmtjs/common';
5
+ import { ClientMessageType, decodeNumber } from '@nmtjs/protocol/common';
6
+ import { ProtocolInjectables } from '@nmtjs/protocol/server';
7
+ import { WsTransportInjectables } from "./injectables.js";
8
+ import { getRequestData, send } from "./utils.js";
7
9
  export class WsTransportServer {
8
- application;
10
+ context;
9
11
  options;
10
12
  server;
11
- transportType;
12
- constructor(application, options){
13
- this.application = application;
13
+ clients;
14
+ constructor(context, options){
15
+ this.context = context;
14
16
  this.options = options;
15
- this.transportType = TransportType.WS;
17
+ this.clients = new Map();
16
18
  this.server = this.options.tls ? SSLApp(options.tls) : App();
17
19
  this.server.options('/*', (res, req)=>{
18
20
  this.applyCors(res, req);
@@ -27,62 +29,52 @@ export class WsTransportServer {
27
29
  maxPayloadLength: this.options.maxPayloadLength,
28
30
  upgrade: (res, req, context)=>{
29
31
  const requestData = getRequestData(req);
30
- const container = this.application.container.createScope(Scope.Connection);
31
- const services = requestData.query.getAll('services');
32
- for (const serviceName of services){
33
- const service = this.application.registry.services.get(serviceName);
34
- if (!service) return void res.writeStatus('400 Bad Request').end(`Service ${service} not found`);
35
- if (this.transportType in service.contract.transports === false) return void res.writeStatus('400 Bad Request').end(`Service ${service} not supported`);
36
- }
32
+ const contentType = requestData.headers.get('content-type') || requestData.query.get('content-type');
33
+ const acceptType = requestData.headers.get('accept') || requestData.query.get('accept');
37
34
  const data = {
38
35
  id: randomUUID(),
39
- format: getFormat(requestData, this.application.format),
40
- container,
41
- streams: {
42
- up: new Map(),
43
- down: new Map(),
44
- streamId: 0
45
- },
46
- abortControllers: new Map(),
47
- subscriptions: new Map(),
48
- services,
49
- data: {
36
+ request: {
50
37
  query: requestData.query,
51
38
  headers: requestData.headers,
52
39
  proxiedRemoteAddress: Buffer.from(res.getProxiedRemoteAddressAsText()).toString(),
53
- remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString()
40
+ remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString(),
41
+ contentType,
42
+ acceptType
54
43
  },
44
+ opening: createPromise(),
55
45
  backpressure: null,
56
46
  context: {}
57
47
  };
58
48
  res.upgrade(data, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context);
59
49
  },
60
- open: (ws)=>{
61
- const data = ws.getUserData();
62
- this.logger.debug('Connection %s opened', data.id);
63
- data.context.decode = this.createDecodeRpcContext(ws);
64
- data.context.encode = this.createEncodeRpcContext(ws);
65
- data.container.provide(connectionData, data.data);
66
- const connection = this.application.connections.add({
67
- id: data.id,
68
- services: data.services,
69
- type: this.transportType,
70
- subscriptions: data.subscriptions,
71
- sendEvent: (service, event, payload)=>sendMessage(ws, MessageType.Event, [
72
- service,
73
- event,
74
- payload
75
- ])
76
- });
77
- data.container.provide(builtin.connection, connection);
50
+ open: async (ws)=>{
51
+ const { id, context, request, opening } = ws.getUserData();
52
+ this.clients.set(id, ws);
53
+ this.logger.debug('Connection %s opened', id);
54
+ try {
55
+ const { context: _context, connection } = await this.context.protocol.connections.add(this, {
56
+ id,
57
+ data: {}
58
+ }, {
59
+ acceptType: request.acceptType,
60
+ contentType: request.contentType
61
+ });
62
+ Object.assign(context, _context);
63
+ context.container.provide(ProtocolInjectables.connection, connection);
64
+ context.container.provide(WsTransportInjectables.connectionData, request);
65
+ opening.resolve();
66
+ } catch (error) {
67
+ opening.reject(error);
68
+ }
78
69
  },
79
- message: async (ws, event)=>{
80
- const buffer = event;
70
+ message: async (ws, buffer)=>{
71
+ const { opening } = ws.getUserData();
81
72
  const messageType = decodeNumber(buffer, 'Uint8');
82
73
  if (messageType in this === false) {
83
74
  ws.end(1011, 'Unknown message type');
84
75
  } else {
85
76
  try {
77
+ await opening.promise;
86
78
  await this[messageType](ws, buffer.slice(Uint8Array.BYTES_PER_ELEMENT));
87
79
  } catch (error) {
88
80
  this.logError(error, 'Error while processing message');
@@ -94,31 +86,19 @@ export class WsTransportServer {
94
86
  data.backpressure?.resolve();
95
87
  data.backpressure = null;
96
88
  },
97
- close: (ws, code, message)=>{
98
- const data = ws.getUserData();
99
- this.logger.debug('Connection %s closed with code %s: %s', data.id, code, Buffer.from(message).toString());
100
- this.application.connections.remove(data.id);
101
- const error = new Error('Connection closed');
102
- for (const ac of data.abortControllers.values()){
103
- ac.abort(error);
104
- }
105
- data.abortControllers.clear();
106
- for (const stream of data.streams.down.values()){
107
- stream.destroy(error);
108
- }
109
- data.streams.down.clear();
110
- for (const stream of data.streams.up.values()){
111
- stream.destroy(error);
112
- }
113
- data.streams.up.clear();
114
- for (const subscription of data.subscriptions.values()){
115
- subscription.destroy();
116
- }
117
- data.subscriptions.clear();
118
- this.handleContainerDisposal(data.container);
89
+ close: async (ws, code, message)=>{
90
+ const { id } = ws.getUserData();
91
+ this.logger.debug('Connection %s closed with code %s: %s', id, code, Buffer.from(message).toString());
92
+ this.clients.delete(id);
93
+ await this.protocol.connections.remove(id);
119
94
  }
120
95
  });
121
96
  }
97
+ send(connection, messageType, buffer) {
98
+ const ws = this.clients.get(connection.id);
99
+ assert(ws, 'Websocket not found');
100
+ send(ws, messageType, buffer);
101
+ }
122
102
  async start() {
123
103
  return new Promise((resolve, reject)=>{
124
104
  const hostname = this.options.hostname ?? '127.0.0.1';
@@ -135,11 +115,11 @@ export class WsTransportServer {
135
115
  async stop() {
136
116
  this.server.close();
137
117
  }
138
- get api() {
139
- return this.application.api;
118
+ get protocol() {
119
+ return this.context.protocol;
140
120
  }
141
121
  get logger() {
142
- return this.application.logger;
122
+ return this.context.logger;
143
123
  }
144
124
  async logError(cause, message = 'Unknown error while processing request') {
145
125
  this.logger.error(new Error(message, {
@@ -154,203 +134,41 @@ export class WsTransportServer {
154
134
  res.writeHeader('Access-Control-Allow-Methods', 'GET, POST');
155
135
  res.writeHeader('Access-Control-Allow-Credentials', 'true');
156
136
  }
157
- async handleContainerDisposal(container) {
158
- await container.dispose();
159
- }
160
- async handleRPC(options) {
161
- return await this.api.call({
162
- ...options,
163
- transport: this.transportType
164
- });
165
- }
166
- createEncodeRpcContext(ws) {
167
- const data = ws.getUserData();
168
- return {
169
- addStream: (blob)=>{
170
- const id = ++data.streams.streamId;
171
- const downstream = new ServerDownStream(id, blob);
172
- downstream.pause();
173
- downstream.on('error', console.dir);
174
- downstream.once('error', (err)=>{
175
- console.log({
176
- err
177
- });
178
- if (downstream.errored?.message !== 'Aborted by client') send(ws, MessageType.DownStreamAbort, encodeNumber(id, 'Uint32'));
179
- });
180
- downstream.on('data', (chunk)=>{
181
- downstream.pause();
182
- send(ws, MessageType.DownStreamPush, encodeNumber(id, 'Uint32'), Buffer.from(chunk).buffer);
183
- });
184
- data.streams.down.set(id, downstream);
185
- return {
186
- id,
187
- metadata: blob.metadata
188
- };
189
- },
190
- getStream: (id)=>{
191
- return data.streams.down.get(id);
192
- }
193
- };
194
- }
195
- createDecodeRpcContext(ws) {
196
- const data = ws.getUserData();
197
- return {
198
- addStream (signal, id, metadata) {
199
- const upstream = new ServerUpStream(metadata, {
200
- read: (size)=>{
201
- send(ws, MessageType.UpStreamPull, encodeNumber(id, 'Uint32'), encodeNumber(size, 'Uint32'));
202
- }
203
- });
204
- data.streams.up.set(id, upstream);
205
- onAbort(signal, ()=>{
206
- upstream.destroy(new Error('Call aborted by client'));
207
- });
208
- upstream.once('error', (error)=>{
209
- if (error.message !== 'Aborted by server') send(ws, MessageType.UpStreamAbort, encodeNumber(id, 'Uint32'));
210
- });
211
- upstream.once('close', ()=>{
212
- if (upstream.errored?.message !== 'Aborted by server') send(ws, MessageType.UpStreamEnd, encodeNumber(id, 'Uint32'));
213
- });
214
- return upstream;
215
- },
216
- getStream (id) {
217
- return data.streams.down.get(id);
218
- }
219
- };
220
- }
221
- async [MessageType.Rpc](ws, buffer) {
222
- const data = ws.getUserData();
223
- const connection = this.application.connections.get(data.id);
224
- if (!connection) return void ws.end(1011, 'Unknown connection');
225
- const ac = new AbortController();
226
- const rpc = data.format.decoder.decodeRpc(buffer, {
227
- ...data.context.decode,
228
- addStream: data.context.decode.addStream.bind(null, ac.signal)
229
- });
230
- data.abortControllers.set(rpc.callId, ac);
231
- const container = data.container.createScope(Scope.Call);
232
- try {
233
- const { service, procedure } = this.api.find(rpc.service, rpc.procedure, this.transportType);
234
- const response = await this.handleRPC({
235
- connection,
236
- service,
237
- procedure,
238
- container,
239
- signal: ac.signal,
240
- payload: rpc.payload
241
- });
242
- if (response instanceof SubscriptionResponse) {
243
- sendRpcMessage(ws, MessageType.RpcSubscription, {
244
- callId: rpc.callId,
245
- error: null,
246
- payload: [
247
- response.subscription.key,
248
- response.payload
249
- ]
250
- });
251
- response.subscription.on('event', (event, payload)=>{
252
- sendMessage(ws, MessageType.ServerSubscriptionEvent, [
253
- response.subscription.key,
254
- event,
255
- payload
256
- ]);
257
- });
258
- response.subscription.once('end', ()=>{
259
- sendMessage(ws, MessageType.ServerUnsubscribe, [
260
- response.subscription.key
261
- ]);
262
- });
263
- } else {
264
- sendRpcMessage(ws, MessageType.Rpc, {
265
- callId: rpc.callId,
266
- error: null,
267
- payload: response
268
- });
269
- }
270
- } catch (error) {
271
- if (error instanceof ApiError) {
272
- this.logger.debug(new Error('Api error', {
273
- cause: error
274
- }));
275
- sendRpcMessage(ws, MessageType.Rpc, {
276
- callId: rpc.callId,
277
- error,
278
- payload: null
279
- });
280
- } else {
281
- this.logger.error(new Error('Unexpected error', {
282
- cause: error
283
- }));
284
- sendRpcMessage(ws, MessageType.Rpc, {
285
- callId: rpc.callId,
286
- error: InternalError(),
287
- payload: null
288
- });
289
- }
290
- } finally{
291
- data.abortControllers.delete(rpc.callId);
292
- this.handleContainerDisposal(container);
293
- }
294
- }
295
- async [MessageType.UpStreamPush](ws, buffer) {
296
- const data = ws.getUserData();
297
- const id = decodeNumber(buffer, 'Uint32');
298
- const stream = data.streams.up.get(id);
299
- if (!stream) return ws.end(1011, 'Unknown stream');
300
- stream.push(Buffer.from(buffer.slice(Uint32Array.BYTES_PER_ELEMENT)));
301
- }
302
- async [MessageType.UpStreamEnd](ws, buffer) {
303
- const data = ws.getUserData();
304
- const id = decodeNumber(buffer, 'Uint32');
305
- const stream = data.streams.up.get(id);
306
- if (!stream) return ws.end(1011, 'Unknown stream');
307
- stream.push(null);
308
- data.streams.up.delete(id);
309
- }
310
- async [MessageType.UpStreamAbort](ws, buffer) {
311
- const data = ws.getUserData();
312
- const id = decodeNumber(buffer, 'Uint32');
313
- const stream = data.streams.up.get(id);
314
- if (!stream) return ws.end(1011, 'Unknown stream');
315
- stream.destroy(new Error('Aborted by client'));
316
- data.streams.up.delete(id);
317
- }
318
- async [MessageType.DownStreamPull](ws, buffer) {
319
- const data = ws.getUserData();
320
- const id = decodeNumber(buffer, 'Uint32');
321
- const stream = data.streams.down.get(id);
322
- if (!stream) return ws.end(1011, 'Unknown stream');
323
- await data.backpressure?.promise;
324
- if (stream.readableEnded) send(ws, MessageType.DownStreamEnd, encodeNumber(id, 'Uint32'));
325
- else stream.resume();
326
- }
327
- async [MessageType.DownStreamEnd](ws, buffer) {
328
- const data = ws.getUserData();
329
- const id = decodeNumber(buffer, 'Uint32');
330
- const stream = data.streams.down.get(id);
331
- if (!stream) return ws.end(1011, 'Unknown stream');
332
- data.streams.down.delete(id);
333
- }
334
- async [MessageType.DownStreamAbort](ws, buffer) {
335
- const data = ws.getUserData();
336
- const id = decodeNumber(buffer, 'Uint32');
337
- const stream = data.streams.down.get(id);
338
- if (!stream) return ws.end(1011, 'Unknown stream');
339
- stream.destroy(new Error('Aborted by client'));
340
- data.streams.down.delete(id);
341
- }
342
- async [MessageType.ClientUnsubscribe](ws, buffer) {
343
- const data = ws.getUserData();
344
- const [key] = data.format.decoder.decode(buffer);
345
- const subscription = data.subscriptions.get(key);
346
- if (!subscription) return void ws.end();
347
- subscription.destroy();
348
- data.subscriptions.delete(key);
349
- }
350
- async [MessageType.RpcAbort](ws, buffer) {
351
- const data = ws.getUserData();
352
- const callId = decodeNumber(buffer, 'Uint32');
353
- const ac = data.abortControllers.get(callId);
354
- if (ac) ac.abort(new Error('Aborted by client'));
137
+ [ClientMessageType.Rpc](ws, buffer) {
138
+ const { id } = ws.getUserData();
139
+ this.protocol.rpcRaw(id, buffer);
140
+ }
141
+ [ClientMessageType.RpcAbort](ws, buffer) {
142
+ const { id } = ws.getUserData();
143
+ this.protocol.rpcAbortRaw(id, buffer);
144
+ }
145
+ [ClientMessageType.RpcStreamAbort](ws, buffer) {
146
+ const { id } = ws.getUserData();
147
+ this.protocol.rpcStreamAbortRaw(id, buffer);
148
+ }
149
+ [ClientMessageType.ClientStreamPush](ws, buffer) {
150
+ const { id } = ws.getUserData();
151
+ const streamId = decodeNumber(buffer, 'Uint32');
152
+ this.protocol.clientStreams.push(id, streamId, buffer.slice(Uint32Array.BYTES_PER_ELEMENT));
153
+ }
154
+ [ClientMessageType.ClientStreamEnd](ws, buffer) {
155
+ const { id } = ws.getUserData();
156
+ const streamId = decodeNumber(buffer, 'Uint32');
157
+ this.protocol.clientStreams.end(id, streamId);
158
+ }
159
+ [ClientMessageType.ClientStreamAbort](ws, buffer) {
160
+ const { id } = ws.getUserData();
161
+ const streamId = decodeNumber(buffer, 'Uint32');
162
+ this.protocol.clientStreams.abort(id, streamId);
163
+ }
164
+ [ClientMessageType.ServerStreamPull](ws, buffer) {
165
+ const { id } = ws.getUserData();
166
+ const streamId = decodeNumber(buffer, 'Uint32');
167
+ this.protocol.serverStreams.pull(id, streamId);
168
+ }
169
+ [ClientMessageType.ServerStreamAbort](ws, buffer) {
170
+ const { id } = ws.getUserData();
171
+ const streamId = decodeNumber(buffer, 'Uint32');
172
+ this.protocol.serverStreams.abort(id, streamId);
355
173
  }
356
174
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../lib/server.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport {\n type AnyBaseProcedure,\n ApiError,\n type ApplicationContext,\n type Connection,\n type Container,\n Scope,\n ServerDownStream,\n ServerUpStream,\n type Service,\n SubscriptionResponse,\n builtin,\n onAbort,\n} from '@nmtjs/application'\nimport {\n type ApiBlobMetadata,\n type EncodeRpcContext,\n MessageType,\n TransportType,\n decodeNumber,\n encodeNumber,\n} from '@nmtjs/common'\nimport {\n App,\n type HttpRequest,\n type HttpResponse,\n SSLApp,\n type TemplatedApp,\n} from 'uWebSockets.js'\n\nimport { connectionData } from './injectables.ts'\nimport type {\n WsTransportOptions,\n WsTransportSocket,\n WsUserData,\n} from './types.ts'\nimport {\n InternalError,\n getFormat,\n getRequestData,\n send,\n sendMessage,\n sendRpcMessage,\n} from './utils.ts'\n\nexport class WsTransportServer {\n protected server!: TemplatedApp\n protected readonly transportType = TransportType.WS\n\n constructor(\n protected readonly application: ApplicationContext,\n protected readonly options: WsTransportOptions,\n ) {\n this.server = this.options.tls ? SSLApp(options.tls!) : App()\n\n this.server\n .options('/*', (res, req) => {\n this.applyCors(res, req)\n res.writeStatus('200 OK')\n res.endWithoutBody()\n })\n .get('/healthy', (res, req) => {\n this.applyCors(res, req)\n res.writeHeader('Content-Type', 'text/plain')\n res.end('OK')\n })\n .ws<WsUserData>('/api', {\n sendPingsAutomatically: true,\n maxPayloadLength: this.options.maxPayloadLength,\n upgrade: (res, req, context) => {\n const requestData = getRequestData(req)\n const container = this.application.container.createScope(\n Scope.Connection,\n )\n const services = requestData.query.getAll('services')\n\n for (const serviceName of services) {\n const service = this.application.registry.services.get(serviceName)\n if (!service)\n return void res\n .writeStatus('400 Bad Request')\n .end(`Service ${service} not found`)\n if (this.transportType in service.contract.transports === false)\n return void res\n .writeStatus('400 Bad Request')\n .end(`Service ${service} not supported`)\n }\n\n const data: WsUserData = {\n id: randomUUID(),\n format: getFormat(requestData, this.application.format),\n container,\n streams: {\n up: new Map(),\n down: new Map(),\n streamId: 0,\n },\n abortControllers: new Map(),\n subscriptions: new Map(),\n services,\n data: {\n query: requestData.query,\n headers: requestData.headers,\n proxiedRemoteAddress: Buffer.from(\n res.getProxiedRemoteAddressAsText(),\n ).toString(),\n remoteAddress: Buffer.from(\n res.getRemoteAddressAsText(),\n ).toString(),\n },\n backpressure: null,\n context: {} as any,\n }\n\n res.upgrade(\n data,\n req.getHeader('sec-websocket-key'),\n req.getHeader('sec-websocket-protocol'),\n req.getHeader('sec-websocket-extensions'),\n context,\n )\n },\n open: (ws: WsTransportSocket) => {\n const data = ws.getUserData()\n this.logger.debug('Connection %s opened', data.id)\n data.context.decode = this.createDecodeRpcContext(ws)\n data.context.encode = this.createEncodeRpcContext(ws)\n data.container.provide(connectionData, data.data)\n\n const connection = this.application.connections.add({\n id: data.id,\n services: data.services,\n type: this.transportType,\n subscriptions: data.subscriptions,\n sendEvent: (service, event, payload) =>\n sendMessage(ws, MessageType.Event, [service, event, payload]),\n })\n\n data.container.provide(builtin.connection, connection)\n },\n message: async (ws: WsTransportSocket, event) => {\n const buffer = event as unknown as ArrayBuffer\n const messageType = decodeNumber(buffer, 'Uint8')\n if (messageType in this === false) {\n ws.end(1011, 'Unknown message type')\n } else {\n try {\n await this[messageType](\n ws,\n buffer.slice(Uint8Array.BYTES_PER_ELEMENT),\n )\n } catch (error: any) {\n this.logError(error, 'Error while processing message')\n }\n }\n },\n drain: (ws: WsTransportSocket) => {\n const data = ws.getUserData()\n data.backpressure?.resolve()\n data.backpressure = null\n },\n close: (ws: WsTransportSocket, code, message) => {\n const data = ws.getUserData()\n\n this.logger.debug(\n 'Connection %s closed with code %s: %s',\n data.id,\n code,\n Buffer.from(message).toString(),\n )\n\n this.application.connections.remove(data.id)\n const error = new Error('Connection closed')\n\n for (const ac of data.abortControllers.values()) {\n ac.abort(error)\n }\n data.abortControllers.clear()\n\n for (const stream of data.streams.down.values()) {\n stream.destroy(error)\n }\n data.streams.down.clear()\n\n for (const stream of data.streams.up.values()) {\n stream.destroy(error)\n }\n data.streams.up.clear()\n\n for (const subscription of data.subscriptions.values()) {\n subscription.destroy()\n }\n data.subscriptions.clear()\n\n this.handleContainerDisposal(data.container)\n },\n })\n }\n\n async start() {\n return new Promise<void>((resolve, reject) => {\n const hostname = this.options.hostname ?? '127.0.0.1'\n this.server.listen(hostname, this.options.port!, (socket) => {\n if (socket) {\n this.logger.info(\n 'Server started on %s:%s',\n hostname,\n this.options.port!,\n )\n resolve()\n } else {\n reject(new Error('Failed to start server'))\n }\n })\n })\n }\n\n async stop() {\n this.server.close()\n }\n\n protected get api() {\n return this.application.api\n }\n\n protected get logger() {\n return this.application.logger\n }\n\n protected async logError(\n cause: Error,\n message = 'Unknown error while processing request',\n ) {\n this.logger.error(new Error(message, { cause }))\n }\n\n protected applyCors(res: HttpResponse, req: HttpRequest) {\n // TODO: this should be configurable\n const origin = req.getHeader('origin')\n if (!origin) return\n res.writeHeader('Access-Control-Allow-Origin', origin)\n res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.writeHeader('Access-Control-Allow-Methods', 'GET, POST')\n res.writeHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n protected async handleContainerDisposal(container: Container) {\n await container.dispose()\n }\n\n protected async handleRPC(options: {\n connection: Connection\n service: Service\n procedure: AnyBaseProcedure\n container: Container\n signal: AbortSignal\n payload: any\n }) {\n return await this.api.call({\n ...options,\n transport: this.transportType,\n })\n }\n\n protected createEncodeRpcContext(ws: WsTransportSocket): EncodeRpcContext {\n const data = ws.getUserData()\n return {\n addStream: (blob) => {\n const id = ++data.streams.streamId\n const downstream = new ServerDownStream(id, blob)\n downstream.pause()\n downstream.on('error', console.dir)\n downstream.once('error', (err) => {\n console.log({ err })\n if (downstream.errored?.message !== 'Aborted by client')\n send(ws, MessageType.DownStreamAbort, encodeNumber(id, 'Uint32'))\n })\n downstream.on('data', (chunk) => {\n downstream.pause()\n send(\n ws,\n MessageType.DownStreamPush,\n encodeNumber(id, 'Uint32'),\n Buffer.from(chunk).buffer as ArrayBuffer,\n )\n })\n data.streams.down.set(id, downstream)\n return { id, metadata: blob.metadata }\n },\n getStream: (id) => {\n return data.streams.down.get(id)!\n },\n }\n }\n\n protected createDecodeRpcContext(ws: WsTransportSocket) {\n const data = ws.getUserData()\n return {\n addStream(signal: AbortSignal, id: number, metadata: ApiBlobMetadata) {\n const upstream = new ServerUpStream(metadata, {\n read: (size) => {\n send(\n ws,\n MessageType.UpStreamPull,\n encodeNumber(id, 'Uint32'),\n encodeNumber(size, 'Uint32'),\n )\n },\n })\n\n data.streams.up.set(id, upstream)\n onAbort(signal, () => {\n upstream.destroy(new Error('Call aborted by client'))\n })\n upstream.once('error', (error) => {\n if (error.message !== 'Aborted by server')\n send(ws, MessageType.UpStreamAbort, encodeNumber(id, 'Uint32'))\n })\n upstream.once('close', () => {\n if (upstream.errored?.message !== 'Aborted by server')\n send(ws, MessageType.UpStreamEnd, encodeNumber(id, 'Uint32'))\n })\n\n return upstream\n },\n getStream(id) {\n return data.streams.down.get(id)\n },\n }\n }\n\n protected async [MessageType.Rpc](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n\n const connection = this.application.connections.get(data.id)\n if (!connection) return void ws.end(1011, 'Unknown connection')\n\n const ac = new AbortController()\n const rpc = data.format.decoder.decodeRpc(buffer, {\n ...data.context.decode,\n addStream: data.context.decode.addStream.bind(null, ac.signal),\n })\n\n data.abortControllers.set(rpc.callId, ac)\n\n const container = data.container.createScope(Scope.Call)\n\n try {\n const { service, procedure } = this.api.find(\n rpc.service,\n rpc.procedure,\n this.transportType,\n )\n\n const response = await this.handleRPC({\n connection,\n service,\n procedure,\n container,\n signal: ac.signal,\n payload: rpc.payload,\n })\n\n if (response instanceof SubscriptionResponse) {\n sendRpcMessage(ws, MessageType.RpcSubscription, {\n callId: rpc.callId,\n error: null,\n payload: [response.subscription.key, response.payload],\n })\n\n response.subscription.on('event', (event, payload) => {\n sendMessage(ws, MessageType.ServerSubscriptionEvent, [\n response.subscription.key,\n event,\n payload,\n ])\n })\n response.subscription.once('end', () => {\n sendMessage(ws, MessageType.ServerUnsubscribe, [\n response.subscription.key,\n ])\n })\n } else {\n sendRpcMessage(ws, MessageType.Rpc, {\n callId: rpc.callId,\n error: null,\n payload: response,\n })\n }\n } catch (error) {\n if (error instanceof ApiError) {\n this.logger.debug(new Error('Api error', { cause: error }))\n sendRpcMessage(ws, MessageType.Rpc, {\n callId: rpc.callId,\n error,\n payload: null,\n })\n } else {\n this.logger.error(new Error('Unexpected error', { cause: error }))\n sendRpcMessage(ws, MessageType.Rpc, {\n callId: rpc.callId,\n error: InternalError(),\n payload: null,\n })\n }\n } finally {\n data.abortControllers.delete(rpc.callId)\n this.handleContainerDisposal(container)\n }\n }\n\n async [MessageType.UpStreamPush](ws: WsTransportSocket, buffer: ArrayBuffer) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.up.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.push(Buffer.from(buffer.slice(Uint32Array.BYTES_PER_ELEMENT)))\n }\n\n async [MessageType.UpStreamEnd](ws: WsTransportSocket, buffer: ArrayBuffer) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.up.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.push(null)\n data.streams.up.delete(id)\n }\n\n async [MessageType.UpStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.up.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.destroy(new Error('Aborted by client'))\n data.streams.up.delete(id)\n }\n\n async [MessageType.DownStreamPull](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.down.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n await data.backpressure?.promise\n if (stream.readableEnded)\n send(ws, MessageType.DownStreamEnd, encodeNumber(id, 'Uint32'))\n else stream.resume()\n }\n\n async [MessageType.DownStreamEnd](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.down.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n data.streams.down.delete(id)\n }\n\n async [MessageType.DownStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.down.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.destroy(new Error('Aborted by client'))\n data.streams.down.delete(id)\n }\n\n async [MessageType.ClientUnsubscribe](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const [key] = data.format.decoder.decode(buffer)\n const subscription = data.subscriptions.get(key)\n if (!subscription) return void ws.end()\n subscription.destroy()\n data.subscriptions.delete(key)\n }\n\n async [MessageType.RpcAbort](ws: WsTransportSocket, buffer: ArrayBuffer) {\n const data = ws.getUserData()\n const callId = decodeNumber(buffer, 'Uint32')\n const ac = data.abortControllers.get(callId)\n if (ac) ac.abort(new Error('Aborted by client'))\n }\n}\n"],"names":["randomUUID","ApiError","Scope","ServerDownStream","ServerUpStream","SubscriptionResponse","builtin","onAbort","MessageType","TransportType","decodeNumber","encodeNumber","App","SSLApp","connectionData","InternalError","getFormat","getRequestData","send","sendMessage","sendRpcMessage","WsTransportServer","server","transportType","constructor","application","options","WS","tls","res","req","applyCors","writeStatus","endWithoutBody","get","writeHeader","end","ws","sendPingsAutomatically","maxPayloadLength","upgrade","context","requestData","container","createScope","Connection","services","query","getAll","serviceName","service","registry","contract","transports","data","id","format","streams","up","Map","down","streamId","abortControllers","subscriptions","headers","proxiedRemoteAddress","Buffer","from","getProxiedRemoteAddressAsText","toString","remoteAddress","getRemoteAddressAsText","backpressure","getHeader","open","getUserData","logger","debug","decode","createDecodeRpcContext","encode","createEncodeRpcContext","provide","connection","connections","add","type","sendEvent","event","payload","Event","message","buffer","messageType","slice","Uint8Array","BYTES_PER_ELEMENT","error","logError","drain","resolve","close","code","remove","Error","ac","values","abort","clear","stream","destroy","subscription","handleContainerDisposal","start","Promise","reject","hostname","listen","port","socket","info","stop","api","cause","origin","dispose","handleRPC","call","transport","addStream","blob","downstream","pause","on","console","dir","once","err","log","errored","DownStreamAbort","chunk","DownStreamPush","set","metadata","getStream","signal","upstream","read","size","UpStreamPull","UpStreamAbort","UpStreamEnd","Rpc","AbortController","rpc","decoder","decodeRpc","bind","callId","Call","procedure","find","response","RpcSubscription","key","ServerSubscriptionEvent","ServerUnsubscribe","delete","UpStreamPush","push","Uint32Array","DownStreamPull","promise","readableEnded","DownStreamEnd","resume","ClientUnsubscribe","RpcAbort"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAa;AACxC,SAEEC,QAAQ,E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AAC7J,YAAY0K,QAAQ,CAAC,CAAC7I,EAAqB,EAAEuD,MAAmB,EAAE;QACvE,MAAMtC,OAAOjB,GAAGsC,WAAW;QAC3B,MAAMoF,SAASrJ,aAAakF,QAAQ;QACpC,MAAMa,KAAKnD,KAAKQ,gBAAgB,CAAC5B,GAAG,CAAC6H;QACrC,IAAItD,IAAIA,GAAGE,KAAK,CAAC,IAAIH,MAAM;IAC7B;AACF"}
1
+ {"version":3,"sources":["../../../lib/server.ts"],"sourcesContent":["import {\n App,\n type HttpRequest,\n type HttpResponse,\n SSLApp,\n type TemplatedApp,\n} from 'uWebSockets.js'\nimport assert from 'node:assert'\nimport { randomUUID } from 'node:crypto'\nimport { createPromise } from '@nmtjs/common'\nimport {\n ClientMessageType,\n decodeNumber,\n type ServerMessageType,\n} from '@nmtjs/protocol/common'\nimport {\n type Connection,\n ProtocolInjectables,\n type Transport,\n type TransportPluginContext,\n} from '@nmtjs/protocol/server'\nimport { WsTransportInjectables } from './injectables.ts'\nimport type {\n WsTransportOptions,\n WsTransportSocket,\n WsUserData,\n} from './types.ts'\nimport { getRequestData, send } from './utils.ts'\n\nexport type WsConnectionData = {}\n\nexport class WsTransportServer implements Transport<WsConnectionData> {\n protected server!: TemplatedApp\n protected clients: Map<string, WsTransportSocket> = new Map()\n\n constructor(\n protected readonly context: TransportPluginContext,\n protected readonly options: WsTransportOptions,\n ) {\n this.server = this.options.tls ? SSLApp(options.tls!) : App()\n\n this.server\n .options('/*', (res, req) => {\n this.applyCors(res, req)\n res.writeStatus('200 OK')\n res.endWithoutBody()\n })\n .get('/healthy', (res, req) => {\n this.applyCors(res, req)\n res.writeHeader('Content-Type', 'text/plain')\n res.end('OK')\n })\n .ws<WsUserData>('/api', {\n sendPingsAutomatically: true,\n maxPayloadLength: this.options.maxPayloadLength,\n upgrade: (res, req, context) => {\n const requestData = getRequestData(req)\n\n const contentType =\n requestData.headers.get('content-type') ||\n requestData.query.get('content-type')\n\n const acceptType =\n requestData.headers.get('accept') || requestData.query.get('accept')\n\n const data: WsUserData = {\n id: randomUUID(),\n request: {\n query: requestData.query,\n headers: requestData.headers,\n proxiedRemoteAddress: Buffer.from(\n res.getProxiedRemoteAddressAsText(),\n ).toString(),\n remoteAddress: Buffer.from(\n res.getRemoteAddressAsText(),\n ).toString(),\n contentType,\n acceptType,\n },\n opening: createPromise(),\n backpressure: null,\n context: {} as any,\n }\n\n res.upgrade(\n data,\n req.getHeader('sec-websocket-key'),\n req.getHeader('sec-websocket-protocol'),\n req.getHeader('sec-websocket-extensions'),\n context,\n )\n },\n open: async (ws: WsTransportSocket) => {\n const { id, context, request, opening } = ws.getUserData()\n this.clients.set(id, ws)\n this.logger.debug('Connection %s opened', id)\n try {\n const { context: _context, connection } =\n await this.context.protocol.connections.add(\n this,\n { id, data: {} },\n {\n acceptType: request.acceptType,\n contentType: request.contentType,\n },\n )\n Object.assign(context, _context)\n context.container.provide(\n ProtocolInjectables.connection,\n connection,\n )\n context.container.provide(\n WsTransportInjectables.connectionData,\n request,\n )\n opening.resolve()\n } catch (error) {\n opening.reject(error)\n }\n },\n message: async (ws: WsTransportSocket, buffer) => {\n const { opening } = ws.getUserData()\n const messageType = decodeNumber(buffer, 'Uint8')\n if (messageType in this === false) {\n ws.end(1011, 'Unknown message type')\n } else {\n try {\n await opening.promise\n await this[messageType](\n ws,\n buffer.slice(Uint8Array.BYTES_PER_ELEMENT),\n )\n } catch (error: any) {\n this.logError(error, 'Error while processing message')\n }\n }\n },\n drain: (ws: WsTransportSocket) => {\n const data = ws.getUserData()\n data.backpressure?.resolve()\n data.backpressure = null\n },\n close: async (ws: WsTransportSocket, code, message) => {\n const { id } = ws.getUserData()\n\n this.logger.debug(\n 'Connection %s closed with code %s: %s',\n id,\n code,\n Buffer.from(message).toString(),\n )\n this.clients.delete(id)\n await this.protocol.connections.remove(id)\n },\n })\n }\n\n send(\n connection: Connection<WsConnectionData>,\n messageType: ServerMessageType,\n buffer: ArrayBuffer,\n ) {\n const ws = this.clients.get(connection.id)\n assert(ws, 'Websocket not found')\n send(ws, messageType, buffer)\n }\n\n async start() {\n return new Promise<void>((resolve, reject) => {\n const hostname = this.options.hostname ?? '127.0.0.1'\n this.server.listen(hostname, this.options.port!, (socket) => {\n if (socket) {\n this.logger.info(\n 'Server started on %s:%s',\n hostname,\n this.options.port!,\n )\n resolve()\n } else {\n reject(new Error('Failed to start server'))\n }\n })\n })\n }\n\n async stop() {\n this.server.close()\n }\n\n protected get protocol() {\n return this.context.protocol\n }\n\n protected get logger() {\n return this.context.logger\n }\n\n protected async logError(\n cause: Error,\n message = 'Unknown error while processing request',\n ) {\n this.logger.error(new Error(message, { cause }))\n }\n\n protected applyCors(res: HttpResponse, req: HttpRequest) {\n // TODO: this should be configurable\n const origin = req.getHeader('origin')\n if (!origin) return\n res.writeHeader('Access-Control-Allow-Origin', origin)\n res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.writeHeader('Access-Control-Allow-Methods', 'GET, POST')\n res.writeHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n protected [ClientMessageType.Rpc](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n this.protocol.rpcRaw(id, buffer)\n }\n\n protected [ClientMessageType.RpcAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n this.protocol.rpcAbortRaw(id, buffer)\n }\n\n protected [ClientMessageType.RpcStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n this.protocol.rpcStreamAbortRaw(id, buffer)\n }\n\n protected [ClientMessageType.ClientStreamPush](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.clientStreams.push(\n id,\n streamId,\n buffer.slice(Uint32Array.BYTES_PER_ELEMENT),\n )\n }\n\n protected [ClientMessageType.ClientStreamEnd](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.clientStreams.end(id, streamId)\n }\n\n protected [ClientMessageType.ClientStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.clientStreams.abort(id, streamId)\n }\n\n protected [ClientMessageType.ServerStreamPull](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.serverStreams.pull(id, streamId)\n }\n\n protected [ClientMessageType.ServerStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.serverStreams.abort(id, streamId)\n }\n}\n"],"names":["App","SSLApp","assert","randomUUID","createPromise","ClientMessageType","decodeNumber","ProtocolInjectables","WsTransportInjectables","getRequestData","send","WsTransportServer","server","clients","constructor","context","options","Map","tls","res","req","applyCors","writeStatus","endWithoutBody","get","writeHeader","end","ws","sendPingsAutomatically","maxPayloadLength","upgrade","requestData","contentType","headers","query","acceptType","data","id","request","proxiedRemoteAddress","Buffer","from","getProxiedRemoteAddressAsText","toString","remoteAddress","getRemoteAddressAsText","opening","backpressure","getHeader","open","getUserData","set","logger","debug","_context","connection","protocol","connections","add","Object","assign","container","provide","connectionData","resolve","error","reject","message","buffer","messageType","promise","slice","Uint8Array","BYTES_PER_ELEMENT","logError","drain","close","code","delete","remove","start","Promise","hostname","listen","port","socket","info","Error","stop","cause","origin","Rpc","rpcRaw","RpcAbort","rpcAbortRaw","RpcStreamAbort","rpcStreamAbortRaw","ClientStreamPush","streamId","clientStreams","push","Uint32Array","ClientStreamEnd","ClientStreamAbort","abort","ServerStreamPull","serverStreams","pull","ServerStreamAbort"],"mappings":"AAAA,SACEA,GAAG,EAGHC,MAAM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uB,WAAW;QAC7B,MAAMgD,WAAW5F,aAAa8D,QAAQ;QACtC,IAAI,CAACZ,QAAQ,CAACkD,aAAa,CAACF,KAAK,CAACnE,IAAI6D;IACxC;AACF"}
@@ -1,5 +1,5 @@
1
- import { createTransport } from '@nmtjs/application';
1
+ import { createTransport } from '@nmtjs/protocol/server';
2
2
  import { WsTransportServer } from "./server.js";
3
- export const WsTransport = createTransport('WsTransport', (app, options)=>{
4
- return new WsTransportServer(app, options);
3
+ export const WsTransport = createTransport('WsTransport', (context, options)=>{
4
+ return new WsTransportServer(context, options);
5
5
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../lib/transport.ts"],"sourcesContent":["import { Hook, createPlugin, createTransport } from '@nmtjs/application'\nimport { WsTransportServer } from './server.ts'\nimport type { WsTransportOptions } from './types.ts'\n\nexport const WsTransport = createTransport<WsTransportOptions>(\n 'WsTransport',\n (app, options) => {\n return new WsTransportServer(app, options)\n },\n)\n"],"names":["createTransport","WsTransportServer","WsTransport","app","options"],"mappings":"AAAA,SAA6BA,eAAe,QAAQ,qBAAoB;AACxE,SAASC,iBAAiB,QAAQ,cAAa;AAG/C,OAAO,MAAMC,cAAcF,gBACzB,eACA,CAACG,KAAKC;IACJ,OAAO,IAAIH,kBAAkBE,KAAKC;AACpC,GACD"}
1
+ {"version":3,"sources":["../../../lib/transport.ts"],"sourcesContent":["import { createTransport } from '@nmtjs/protocol/server'\nimport { type WsConnectionData, WsTransportServer } from './server.ts'\nimport type { WsTransportOptions } from './types.ts'\n\nexport const WsTransport = createTransport<\n WsConnectionData,\n WsTransportOptions\n>('WsTransport', (context, options) => {\n return new WsTransportServer(context, options)\n})\n"],"names":["createTransport","WsTransportServer","WsTransport","context","options"],"mappings":"AAAA,SAASA,eAAe,QAAQ,yBAAwB;AACxD,SAAgCC,iBAAiB,QAAQ,cAAa;AAGtE,OAAO,MAAMC,cAAcF,gBAGzB,eAAe,CAACG,SAASC;IACzB,OAAO,IAAIH,kBAAkBE,SAASC;AACxC,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../lib/types.ts"],"sourcesContent":["import type {\n Callback,\n Connection,\n Container,\n ServerDownStream,\n ServerUpStream,\n Subscription,\n} from '@nmtjs/application'\nimport type {\n BaseServerDecoder,\n BaseServerEncoder,\n DecodeRpcContext,\n EncodeRpcContext,\n} from '@nmtjs/common'\nimport type { AppOptions, WebSocket } from 'uWebSockets.js'\n\nexport type WsUserData = {\n id: Connection['id']\n services: string[]\n backpressure: null | {\n promise: Promise<void>\n resolve: Callback\n }\n abortControllers: Map<number, AbortController>\n streams: {\n /**\n * Client to server streams\n */\n up: Map<number, ServerUpStream>\n /**\n * Server to client streams\n */\n down: Map<number, ServerDownStream>\n streamId: number\n }\n subscriptions: Map<string, Subscription>\n container: Container\n data: WsConnectionData\n format: {\n encoder: BaseServerEncoder\n decoder: BaseServerDecoder\n }\n context: {\n decode: Omit<DecodeRpcContext, 'addStream'> & {\n addStream: (\n signal: AbortSignal,\n ...args: Parameters<DecodeRpcContext['addStream']>\n ) => any\n }\n encode: EncodeRpcContext\n }\n}\n\nexport type WsTransportSocket = WebSocket<WsUserData>\n\nexport type WsTransportOptions = {\n port?: number\n hostname?: string\n unix?: string\n tls?: AppOptions\n maxPayloadLength?: number\n maxStreamChunkLength?: number\n // cors?: ServerOptions['cors']\n}\n\nexport type WsConnectionData = {\n headers: Map<string, string>\n query: URLSearchParams\n remoteAddress: string\n proxiedRemoteAddress: string\n}\n"],"names":[],"mappings":"AAiEA,WAKC"}
1
+ {"version":3,"sources":["../../../lib/types.ts"],"sourcesContent":["import type { AppOptions, WebSocket } from 'uWebSockets.js'\nimport type { InteractivePromise } from '@nmtjs/common'\nimport type { Connection, ConnectionContext } from '@nmtjs/protocol/server'\n\nexport type WsUserData = {\n id: Connection['id']\n opening: InteractivePromise<void>\n backpressure: InteractivePromise<void> | null\n request: {\n headers: Map<string, string>\n query: URLSearchParams\n remoteAddress: string\n proxiedRemoteAddress: string\n acceptType: string | null\n contentType: string | null\n }\n context: ConnectionContext\n}\n\nexport type WsTransportSocket = WebSocket<WsUserData>\n\nexport type WsTransportOptions = {\n port?: number\n hostname?: string\n unix?: string\n tls?: AppOptions\n maxPayloadLength?: number\n maxStreamChunkLength?: number\n}\n"],"names":[],"mappings":"AAqBA,WAOC"}