New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@nestjs/websockets

Package Overview
Dependencies
Maintainers
1
Versions
351
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nestjs/websockets - npm Package Compare versions

Comparing version 7.6.11 to 8.0.0-alpha.1

factories/server-and-event-streams-factory.d.ts

3

adapters/ws-adapter.d.ts

@@ -13,5 +13,6 @@ import { INestApplicationContext, WebSocketAdapter } from '@nestjs/common';

bindClientDisconnect(client: TClient, callback: Function): void;
close(server: TServer): void;
close(server: TServer): Promise<void>;
dispose(): Promise<void>;
abstract create(port: number, options?: TOptions): TServer;
abstract bindMessageHandlers(client: TClient, handlers: WsMessageHandler[], transform: (data: any) => Observable<any>): any;
}

@@ -22,7 +22,9 @@ "use strict";

}
close(server) {
async close(server) {
const isCallable = server && shared_utils_1.isFunction(server.close);
isCallable && server.close();
isCallable && (await new Promise(resolve => server.close(resolve)));
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
async dispose() { }
}
exports.AbstractWsAdapter = AbstractWsAdapter;

@@ -96,3 +96,3 @@ "use strict";

const numericType = Number(type);
const extractValue = (...args) => paramsFactory.exchangeKeyForValue(numericType, args);
const extractValue = (...args) => paramsFactory.exchangeKeyForValue(numericType, data, args);
return { index, extractValue, type: numericType, data, pipes };

@@ -99,0 +99,0 @@ });

import { PipeTransform, Type } from '@nestjs/common';
/**
* WebSockets message body parameter decorator.
*
* @publicApi
*/
export declare function MessageBody(): ParameterDecorator;
/**
* WebSockets message body parameter decorator.
*
* Example:
* ```typescript
* create(@MessageBody(new ValidationPipe()) createDto: CreateCatDto)
* ```
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound parameter.
*
* @publicApi
*/
export declare function MessageBody(...pipes: (Type<PipeTransform> | PipeTransform)[]): ParameterDecorator;
/**
* WebSockets message body parameter decorator. Extracts a property from the
* message payload object. May also apply pipes to the bound parameter.
*
* For example, extracting all params:
* ```typescript
* findMany(@MessageBody() ids: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* create(@MessageBody('data') createDto: { data: string })
* ```
*
* For example, extracting a single param with pipe:
* ```typescript
* create(@MessageBody('data', new ValidationPipe()) createDto: { data: string })
* ```
* @param propertyKey name of single property to extract from the message payload
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound parameter.
*
* @publicApi
*/
export declare function MessageBody(propertyKey: string, ...pipes: (Type<PipeTransform> | PipeTransform)[]): ParameterDecorator;

@@ -6,5 +6,5 @@ "use strict";

const param_utils_1 = require("../utils/param.utils");
function MessageBody(...pipes) {
return param_utils_1.createPipesWsParamDecorator(ws_paramtype_enum_1.WsParamtype.PAYLOAD)(...pipes);
function MessageBody(propertyOrPipe, ...pipes) {
return param_utils_1.createPipesWsParamDecorator(ws_paramtype_enum_1.WsParamtype.PAYLOAD)(propertyOrPipe, ...pipes);
}
exports.MessageBody = MessageBody;
export declare class WsParamsFactory {
exchangeKeyForValue(type: number, args: unknown[]): unknown;
exchangeKeyForValue(type: number, data: string | undefined, args: unknown[]): any;
}

@@ -6,3 +6,4 @@ "use strict";

class WsParamsFactory {
exchangeKeyForValue(type, args) {
exchangeKeyForValue(type, data, args) {
var _a;
if (!args) {

@@ -15,3 +16,3 @@ return null;

case ws_paramtype_enum_1.WsParamtype.PAYLOAD:
return args[1];
return data ? (_a = args[1]) === null || _a === void 0 ? void 0 : _a[data] : args[1];
default:

@@ -18,0 +19,0 @@ return null;

/**
* @external https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/socket.io/index.d.ts
* @external https://github.com/socketio/socket.io/blob/master/lib/index.ts
*/
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
export interface GatewayMetadata {

@@ -10,8 +11,8 @@ /**

/**
* The path to ws
* @default '/socket.io'
* Name of the path to capture
* @default "/socket.io"
*/
path?: string;
/**
* Should we serve the client file?
* Whether to serve the client files
* @default true

@@ -21,20 +22,23 @@ */

/**
* The adapter to use for handling rooms. NOTE: this should be a class,
* not an object
* @default typeof Adapter
* The adapter to use
* @default the in-memory adapter (https://github.com/socketio/socket.io-adapter)
*/
adapter?: any;
/**
* Accepted origins
* @default '*:*'
* The parser to use
* @default the default parser (https://github.com/socketio/socket.io-parser)
*/
origins?: string | string[];
parser?: any;
/**
* How many milliseconds without a pong packed to consider the connection closed (engine.io)
* @default 60000
* How many ms before a client without namespace is closed
* @default 45000
*/
connectTimeout?: number;
/**
* How many ms without a pong packet to consider the connection closed
* @default 5000
*/
pingTimeout?: number;
/**
* How many milliseconds before sending a new ping packet (keep-alive) (engine.io)
* How many ms before sending a new ping packet
* @default 25000

@@ -44,14 +48,25 @@ */

/**
* How many bytes or characters a message can be when polling, before closing the session
* (to avoid Dos) (engine.io)
* @default 10E7
* How many ms before an uncompleted transport upgrade is cancelled
* @default 10000
*/
upgradeTimeout?: number;
/**
* How many bytes or characters a message can be, before closing the session (to avoid DoS).
* @default 1e5 (100 KB)
*/
maxHttpBufferSize?: number;
/**
* Transports to allow connections to (engine.io)
* @default ['polling','websocket']
* A function that receives a given handshake or upgrade request as its first parameter,
* and can decide whether to continue or not. The second argument is a function that needs
* to be called with the decided information: fn(err, success), where success is a boolean
* value where false means that the request is rejected, and err is an error code.
*/
transports?: string[];
allowRequest?: (req: any, fn: (err: string | null | undefined, success: boolean) => void) => void;
/**
* Whether to allow transport upgrades (engine.io)
* The low-level transports that are enabled
* @default ["polling", "websocket"]
*/
transports?: Transport[];
/**
* Whether to allow transport upgrades
* @default true

@@ -61,26 +76,46 @@ */

/**
* parameters of the WebSocket permessage-deflate extension (see ws module).
* Set to false to disable (engine.io)
* Parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable.
* @default false
*/
perMessageDeflate?: boolean | object;
/**
* Parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable.
* @default true
*/
perMessageDeflate?: Record<string, any> | boolean;
httpCompression?: boolean | object;
/**
* Parameters of the http compression for the polling transports (see zlib).
* Set to false to disable, or set an object with parameter "threshold:number"
* to only compress data if the byte size is above this value (1024) (engine.io)
* @default true|1024
* What WebSocket server implementation to use. Specified module must
* conform to the ws interface (see ws module api docs). Default value is ws.
* An alternative c++ addon is also available by installing uws module.
*/
httpCompression?: Record<string, any> | boolean;
wsEngine?: string;
/**
* Name of the HTTP cookie that contains the client sid to send as part of
* handshake response headers. Set to false to not send one (engine.io)
* @default "io"
* An optional packet which will be concatenated to the handshake packet emitted by Engine.IO.
*/
cookie?: string | boolean;
initialPacket?: any;
/**
* Whether to let engine.io handle the OPTIONS requests.
* You can also pass a custom function to handle the requests
* Configuration of the cookie that contains the client sid to send as part of handshake response headers. This cookie
* might be used for sticky-session. Defaults to not sending any cookie.
* @default false
*/
cookie?: any | boolean;
/**
* The options that will be forwarded to the cors module
*/
cors?: CorsOptions;
/**
* Whether to enable compatibility with Socket.IO v2 clients
* @default false
*/
allowEIO3?: boolean;
/**
* Destroy unhandled upgrade requests
* @default true
*/
handlePreflightRequest?: ((req: any, res: any) => void) | boolean;
destroyUpgrade?: boolean;
/**
* Milliseconds after which unhandled requests are ended
* @default 1000
*/
destroyUpgradeTimeout?: number;
}
"use strict";
/**
* @external https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/socket.io/index.d.ts
* @external https://github.com/socketio/socket.io/blob/master/lib/index.ts
*/
Object.defineProperty(exports, "__esModule", { value: true });
export * from './gateway-metadata.interface';
export * from './hooks';
export * from './socket-events-host.interface';
export * from './server-and-event-streams-host.interface';
export * from './web-socket-server.interface';
export * from './ws-response.interface';

@@ -6,4 +6,4 @@ "use strict";

tslib_1.__exportStar(require("./hooks"), exports);
tslib_1.__exportStar(require("./socket-events-host.interface"), exports);
tslib_1.__exportStar(require("./server-and-event-streams-host.interface"), exports);
tslib_1.__exportStar(require("./web-socket-server.interface"), exports);
tslib_1.__exportStar(require("./ws-response.interface"), exports);
{
"name": "@nestjs/websockets",
"version": "7.6.11",
"version": "8.0.0-alpha.1",
"description": "Nest - modern, fast, powerful node.js web framework (@websockets)",

@@ -16,7 +16,8 @@ "author": "Kamil Mysliwiec",

"iterare": "1.2.1",
"object-hash": "2.1.1",
"tslib": "2.1.0"
},
"devDependencies": {
"@nestjs/common": "7.6.11",
"@nestjs/core": "7.6.11"
"@nestjs/common": "^8.0.0-alpha.1",
"@nestjs/core": "^8.0.0-alpha.1"
},

@@ -26,5 +27,11 @@ "peerDependencies": {

"@nestjs/core": "^7.0.0",
"@nestjs/platform-socket.io": "^7.0.0",
"reflect-metadata": "^0.1.12",
"rxjs": "^6.0.0"
},
"peerDependenciesMeta": {
"@nestjs/platform-socket.io": {
"optional": true
}
}
}

@@ -5,2 +5,3 @@ import { Injectable } from '@nestjs/common/interfaces/injectable.interface';

import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper';
import { InstanceToken } from '@nestjs/core/injector/module';
export declare class SocketModule<HttpServer = any> {

@@ -13,4 +14,4 @@ private readonly socketsContainer;

register(container: NestContainer, config: ApplicationConfig, httpServer?: HttpServer): void;
combineAllGateways(providers: Map<string, InstanceWrapper<Injectable>>, moduleName: string): void;
combineGatewayAndServer(wrapper: InstanceWrapper<Injectable>, moduleName: string): void;
connectAllGateways(providers: Map<InstanceToken, InstanceWrapper<Injectable>>, moduleName: string): void;
connectGatewayToServer(wrapper: InstanceWrapper<Injectable>, moduleName: string): void;
close(): Promise<any>;

@@ -17,0 +18,0 @@ private initializeAdapter;

@@ -30,10 +30,10 @@ "use strict";

const modules = container.getModules();
modules.forEach(({ providers }, moduleName) => this.combineAllGateways(providers, moduleName));
modules.forEach(({ providers }, moduleName) => this.connectAllGateways(providers, moduleName));
}
combineAllGateways(providers, moduleName) {
connectAllGateways(providers, moduleName) {
iterare_1.iterate(providers.values())
.filter(wrapper => wrapper && !wrapper.isNotMetatype)
.forEach(wrapper => this.combineGatewayAndServer(wrapper, moduleName));
.forEach(wrapper => this.connectGatewayToServer(wrapper, moduleName));
}
combineGatewayAndServer(wrapper, moduleName) {
connectGatewayToServer(wrapper, moduleName) {
const { instance, metatype } = wrapper;

@@ -47,5 +47,6 @@ const metadataKeys = Reflect.getMetadataKeys(metatype);

}
this.webSocketsController.mergeGatewayAndServer(instance, metatype, moduleName);
this.webSocketsController.connectGatewayToServer(instance, metatype, moduleName);
}
async close() {
var _a;
if (!this.applicationConfig) {

@@ -58,6 +59,7 @@ return;

}
const servers = this.socketsContainer.getAllSocketEventHosts();
const servers = this.socketsContainer.getAll();
await Promise.all(iterare_1.iterate(servers.values())
.filter(({ server }) => server)
.map(async ({ server }) => adapter.close(server)));
await ((_a = adapter) === null || _a === void 0 ? void 0 : _a.dispose());
this.socketsContainer.clear();

@@ -71,3 +73,3 @@ }

}
const { IoAdapter } = load_adapter_1.loadAdapter('@nestjs/platform-socket.io', 'WebSockets');
const { IoAdapter } = load_adapter_1.loadAdapter('@nestjs/platform-socket.io', 'WebSockets', () => require('@nestjs/platform-socket.io'));
const ioAdapter = new IoAdapter(this.httpServer);

@@ -74,0 +76,0 @@ this.applicationConfig.setIoAdapter(ioAdapter);

import { ApplicationConfig } from '@nestjs/core/application-config';
import { GatewayMetadata } from './interfaces/gateway-metadata.interface';
import { SocketEventsHost } from './interfaces/socket-events-host.interface';
import { ServerAndEventStreamsHost } from './interfaces/server-and-event-streams-host.interface';
import { SocketsContainer } from './sockets-container';

@@ -9,7 +9,7 @@ export declare class SocketServerProvider {

constructor(socketsContainer: SocketsContainer, applicationConfig: ApplicationConfig);
scanForSocketServer<T extends GatewayMetadata>(options: T, port: number): SocketEventsHost;
scanForSocketServer<T extends GatewayMetadata = any>(options: T, port: number): ServerAndEventStreamsHost;
private createSocketServer;
private createWithNamespace;
private decorateWithNamespace;
private getServerOfNamespace;
private validateNamespace;
}

@@ -6,4 +6,3 @@ "use strict";

const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const util_1 = require("util");
const socket_events_host_factory_1 = require("./socket-events-host-factory");
const server_and_event_streams_factory_1 = require("./factories/server-and-event-streams-factory");
class SocketServerProvider {

@@ -15,26 +14,30 @@ constructor(socketsContainer, applicationConfig) {

scanForSocketServer(options, port) {
const socketEventsHost = this.socketsContainer.getSocketEventsHostByPort(port);
return socketEventsHost
? this.createWithNamespace(options, port, socketEventsHost)
const serverAndStreamsHost = this.socketsContainer.getOneByConfig({
port,
path: options.path,
});
if (serverAndStreamsHost && options.namespace) {
return this.decorateWithNamespace(options, port, serverAndStreamsHost.server);
}
return serverAndStreamsHost
? serverAndStreamsHost
: this.createSocketServer(options, port);
}
createSocketServer(options, port) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const adapter = this.applicationConfig.getIoAdapter();
const _a = options, { namespace, server } = _a, partialOptions = tslib_1.__rest(_a, ["namespace", "server"]);
const adapter = this.applicationConfig.getIoAdapter();
const ioServer = adapter.create(port, partialOptions);
const observableSocket = socket_events_host_factory_1.SocketEventsHostFactory.create(ioServer);
this.socketsContainer.addSocketEventsHost(null, port, observableSocket);
return this.createWithNamespace(options, port, observableSocket);
}
createWithNamespace(options, port, socketEventsHost) {
const { namespace } = options;
const serverAndEventStreamsHost = server_and_event_streams_factory_1.ServerAndEventStreamsFactory.create(ioServer);
this.socketsContainer.addOne({ port, path: options.path }, serverAndEventStreamsHost);
if (!namespace) {
return socketEventsHost;
return serverAndEventStreamsHost;
}
const namespaceServer = this.getServerOfNamespace(options, port, socketEventsHost.server);
const eventsHost = socket_events_host_factory_1.SocketEventsHostFactory.create(namespaceServer);
this.socketsContainer.addSocketEventsHost(namespace, port, eventsHost);
return eventsHost;
return this.decorateWithNamespace(options, port, ioServer);
}
decorateWithNamespace(options, port, targetServer) {
const namespaceServer = this.getServerOfNamespace(options, port, targetServer);
const serverAndEventStreamsHost = server_and_event_streams_factory_1.ServerAndEventStreamsFactory.create(namespaceServer);
this.socketsContainer.addOne({ port, path: options.path, namespace: options.namespace }, serverAndEventStreamsHost);
return serverAndEventStreamsHost;
}
getServerOfNamespace(options, port, server) {

@@ -45,3 +48,3 @@ const adapter = this.applicationConfig.getIoAdapter();

validateNamespace(namespace) {
if (!util_1.isString(namespace)) {
if (!shared_utils_1.isString(namespace)) {
return namespace;

@@ -48,0 +51,0 @@ }

@@ -1,8 +0,9 @@

import { SocketEventsHost } from './interfaces';
import { GatewayMetadata, ServerAndEventStreamsHost } from './interfaces';
export declare class SocketsContainer {
private readonly socketEventHosts;
getAllSocketEventHosts(): Map<string | RegExp, SocketEventsHost>;
getSocketEventsHostByPort(port: number): SocketEventsHost;
addSocketEventsHost(namespace: string | RegExp, port: number, host: SocketEventsHost): void;
private readonly serverAndEventStreamsHosts;
getAll(): Map<string | RegExp, ServerAndEventStreamsHost>;
getOneByConfig<T extends GatewayMetadata = any>(options: T): ServerAndEventStreamsHost;
addOne<T extends GatewayMetadata = any>(options: T, host: ServerAndEventStreamsHost): void;
clear(): void;
private generateHashByOptions;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SocketsContainer = void 0;
const hash = require("object-hash");
class SocketsContainer {
constructor() {
this.socketEventHosts = new Map();
this.serverAndEventStreamsHosts = new Map();
}
getAllSocketEventHosts() {
return this.socketEventHosts;
getAll() {
return this.serverAndEventStreamsHosts;
}
getSocketEventsHostByPort(port) {
return this.socketEventHosts.get(`${port}`);
getOneByConfig(options) {
const uniqueToken = this.generateHashByOptions(options);
return this.serverAndEventStreamsHosts.get(uniqueToken);
}
addSocketEventsHost(namespace, port, host) {
this.socketEventHosts.set(namespace ? `${namespace}:${port}` : `${port}`, host);
addOne(options, host) {
const uniqueToken = this.generateHashByOptions(options);
this.serverAndEventStreamsHosts.set(uniqueToken, host);
}
clear() {
this.socketEventHosts.clear();
this.serverAndEventStreamsHosts.clear();
}
generateHashByOptions(options) {
return hash(options, { ignoreUnknown: true });
}
}
exports.SocketsContainer = SocketsContainer;

@@ -5,2 +5,2 @@ import { PipeTransform, Type } from '@nestjs/common';

export declare function createWsParamDecorator(paramtype: WsParamtype): (...pipes: (Type<PipeTransform> | PipeTransform)[]) => ParameterDecorator;
export declare const createPipesWsParamDecorator: (paramtype: WsParamtype) => (...pipes: (Type<PipeTransform> | PipeTransform)[]) => ParameterDecorator;
export declare const createPipesWsParamDecorator: (paramtype: WsParamtype) => (data?: any, ...pipes: (Type<PipeTransform> | PipeTransform)[]) => ParameterDecorator;

@@ -5,2 +5,3 @@ "use strict";

const route_params_decorator_1 = require("@nestjs/common/decorators/http/route-params.decorator");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
require("reflect-metadata");

@@ -15,6 +16,9 @@ const constants_1 = require("../constants");

exports.createWsParamDecorator = createWsParamDecorator;
const createPipesWsParamDecorator = (paramtype) => (...pipes) => (target, key, index) => {
const createPipesWsParamDecorator = (paramtype) => (data, ...pipes) => (target, key, index) => {
const args = Reflect.getMetadata(constants_1.PARAM_ARGS_METADATA, target.constructor, key) || {};
Reflect.defineMetadata(constants_1.PARAM_ARGS_METADATA, route_params_decorator_1.assignMetadata(args, paramtype, index, undefined, ...pipes), target.constructor, key);
const hasParamData = shared_utils_1.isNil(data) || shared_utils_1.isString(data);
const paramData = hasParamData ? data : undefined;
const paramPipes = hasParamData ? pipes : [data, ...pipes];
Reflect.defineMetadata(constants_1.PARAM_ARGS_METADATA, route_params_decorator_1.assignMetadata(args, paramtype, index, paramData, ...paramPipes), target.constructor, key);
};
exports.createPipesWsParamDecorator = createPipesWsParamDecorator;

@@ -8,3 +8,3 @@ import { Type } from '@nestjs/common/interfaces/type.interface';

import { NestGateway } from './interfaces/nest-gateway.interface';
import { SocketEventsHost } from './interfaces/socket-events-host.interface';
import { ServerAndEventStreamsHost } from './interfaces/server-and-event-streams-host.interface';
import { SocketServerProvider } from './socket-server-provider';

@@ -17,5 +17,5 @@ export declare class WebSocketsController {

constructor(socketServerProvider: SocketServerProvider, config: ApplicationConfig, contextCreator: WsContextCreator);
mergeGatewayAndServer(instance: NestGateway, metatype: Type<unknown> | Function, moduleKey: string): void;
connectGatewayToServer(instance: NestGateway, metatype: Type<unknown> | Function, moduleKey: string): void;
subscribeToServerEvents<T extends GatewayMetadata>(instance: NestGateway, options: T, port: number, moduleKey: string): void;
subscribeEvents(instance: NestGateway, subscribersMap: MessageMappingProperties[], observableServer: SocketEventsHost): void;
subscribeEvents(instance: NestGateway, subscribersMap: MessageMappingProperties[], observableServer: ServerAndEventStreamsHost): void;
getConnectionHandler(context: WebSocketsController, instance: NestGateway, subscribersMap: MessageMappingProperties[], disconnect: Subject<any>, connection: Subject<any>): (...args: unknown[]) => void;

@@ -22,0 +22,0 @@ subscribeInitEvent(instance: NestGateway, event: Subject<any>): void;

@@ -19,3 +19,3 @@ "use strict";

}
mergeGatewayAndServer(instance, metatype, moduleKey) {
connectGatewayToServer(instance, metatype, moduleKey) {
const options = Reflect.getMetadata(constants_1.GATEWAY_OPTIONS, metatype) || {};

@@ -22,0 +22,0 @@ const port = Reflect.getMetadata(constants_1.PORT_METADATA, metatype) || 0;

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc