@xtaskjs/socket-io 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ - Add Socket.IO integration with gateway decorators, DI tokens, and lifecycle-managed server attachment.
package/README.md ADDED
@@ -0,0 +1,84 @@
1
+ # @xtaskjs/socket-io
2
+
3
+ Socket.IO integration package for xtaskjs.
4
+
5
+ This package is part of the xtaskjs project, hosted at [xtaskjs.io](https://xtaskjs.io).
6
+
7
+ ## Installation
8
+ ```bash
9
+ npm install @xtaskjs/socket-io socket.io reflect-metadata
10
+ ```
11
+
12
+ ## What It Provides
13
+ - Gateway decorators for connection, disconnection, and named Socket.IO events.
14
+ - xtaskjs DI integration so gateways remain regular `@Service()` classes.
15
+ - Lifecycle integration that attaches to the live HTTP server during `app.listen()` and closes during `app.close()`.
16
+ - Injectable tokens for the Socket.IO server, namespaces, lifecycle manager, and helper service.
17
+ - A small runtime service for broadcasting events and inspecting discovered gateways.
18
+
19
+ ## Declare A Gateway
20
+ ```typescript
21
+ import { Service } from "@xtaskjs/core";
22
+ import {
23
+ OnSocketConnection,
24
+ OnSocketDisconnect,
25
+ OnSocketEvent,
26
+ SocketGateway,
27
+ } from "@xtaskjs/socket-io";
28
+
29
+ @Service()
30
+ @SocketGateway({ namespace: "/chat", group: ["realtime", "chat"] })
31
+ class ChatGateway {
32
+ @OnSocketConnection()
33
+ onConnect(socket: any) {
34
+ console.log("connected", socket.id);
35
+ }
36
+
37
+ @OnSocketEvent("message")
38
+ onMessage(payload: { text: string }, context: { socket: any }) {
39
+ console.log("message", context.socket.id, payload.text);
40
+ return { ok: true };
41
+ }
42
+
43
+ @OnSocketDisconnect()
44
+ onDisconnect(reason: string) {
45
+ console.log("disconnected", reason);
46
+ }
47
+ }
48
+ ```
49
+
50
+ Event handlers receive the event arguments followed by a context object. If the client sent an acknowledgement callback and the handler returns a value, xtaskjs replies through that acknowledgement automatically.
51
+
52
+ ## Broadcast From Services
53
+ ```typescript
54
+ import { Service } from "@xtaskjs/core";
55
+ import { InjectSocketService, SocketIoService } from "@xtaskjs/socket-io";
56
+
57
+ @Service()
58
+ class NotificationsService {
59
+ constructor(
60
+ @InjectSocketService()
61
+ private readonly sockets: SocketIoService
62
+ ) {}
63
+
64
+ publishSystemNotice(message: string) {
65
+ this.sockets.emit("system.notice", { message }, { namespace: "/chat", room: "admins" });
66
+ }
67
+ }
68
+ ```
69
+
70
+ ## Injection Decorators
71
+ - `@InjectSocketService()` injects `SocketIoService`.
72
+ - `@InjectSocketLifecycleManager()` injects the lifecycle manager.
73
+ - `@InjectSocketServer()` injects the root `Socket.IO` server.
74
+ - `@InjectSocketNamespace("/chat")` injects a namespace instance.
75
+
76
+ ## Lifecycle Behavior
77
+ - During `app.listen()`: xtaskjs resolves the live HTTP server from the selected adapter and attaches a Socket.IO server.
78
+ - After attachment: registered `@SocketGateway()` services are discovered from the DI container and bound to namespaces.
79
+ - During `app.close()`: the Socket.IO server is closed before the HTTP adapter and container are torn down.
80
+
81
+ ## Resources
82
+ - Project site and documentation: [xtaskjs.io](https://xtaskjs.io)
83
+ - npm package: [@xtaskjs/socket-io](https://www.npmjs.com/package/@xtaskjs/socket-io)
84
+ - Source repository: [xtaskjs/xtaskjs](https://github.com/xtaskjs/xtaskjs)
@@ -0,0 +1,4 @@
1
+ import { SocketIoConfiguration } from "./types";
2
+ export declare const configureSocketIo: (configuration?: SocketIoConfiguration) => Required<SocketIoConfiguration>;
3
+ export declare const getSocketIoConfiguration: () => Required<SocketIoConfiguration>;
4
+ export declare const resetSocketIoConfiguration: () => void;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resetSocketIoConfiguration = exports.getSocketIoConfiguration = exports.configureSocketIo = void 0;
4
+ const metadata_1 = require("./metadata");
5
+ const defaultConfiguration = {
6
+ defaultNamespace: "/",
7
+ serverOptions: {},
8
+ };
9
+ let currentConfiguration = {
10
+ ...defaultConfiguration,
11
+ };
12
+ const configureSocketIo = (configuration = {}) => {
13
+ currentConfiguration = {
14
+ defaultNamespace: (0, metadata_1.normalizeNamespace)(configuration.defaultNamespace || currentConfiguration.defaultNamespace),
15
+ serverOptions: {
16
+ ...(currentConfiguration.serverOptions || {}),
17
+ ...(configuration.serverOptions || {}),
18
+ },
19
+ };
20
+ return (0, exports.getSocketIoConfiguration)();
21
+ };
22
+ exports.configureSocketIo = configureSocketIo;
23
+ const getSocketIoConfiguration = () => ({
24
+ defaultNamespace: currentConfiguration.defaultNamespace,
25
+ serverOptions: {
26
+ ...(currentConfiguration.serverOptions || {}),
27
+ },
28
+ });
29
+ exports.getSocketIoConfiguration = getSocketIoConfiguration;
30
+ const resetSocketIoConfiguration = () => {
31
+ currentConfiguration = {
32
+ ...defaultConfiguration,
33
+ };
34
+ };
35
+ exports.resetSocketIoConfiguration = resetSocketIoConfiguration;
@@ -0,0 +1,10 @@
1
+ import { SocketGatewayOptions, SocketHandlerOptions } from "./types";
2
+ export declare const SocketGateway: (options?: SocketGatewayOptions) => ClassDecorator;
3
+ export declare const OnSocketConnection: (options?: SocketHandlerOptions) => MethodDecorator;
4
+ export declare const OnSocketDisconnect: (options?: SocketHandlerOptions) => MethodDecorator;
5
+ export declare const OnSocketEvent: (event: string, options?: SocketHandlerOptions) => MethodDecorator;
6
+ export declare const SubscribeMessage: (event: string, options?: SocketHandlerOptions) => MethodDecorator;
7
+ export declare const InjectSocketService: () => ParameterDecorator & PropertyDecorator;
8
+ export declare const InjectSocketLifecycleManager: () => ParameterDecorator & PropertyDecorator;
9
+ export declare const InjectSocketServer: () => ParameterDecorator & PropertyDecorator;
10
+ export declare const InjectSocketNamespace: (namespace?: string) => ParameterDecorator & PropertyDecorator;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InjectSocketNamespace = exports.InjectSocketServer = exports.InjectSocketLifecycleManager = exports.InjectSocketService = exports.SubscribeMessage = exports.OnSocketEvent = exports.OnSocketDisconnect = exports.OnSocketConnection = exports.SocketGateway = void 0;
4
+ const core_1 = require("@xtaskjs/core");
5
+ const tokens_1 = require("./tokens");
6
+ const metadata_1 = require("./metadata");
7
+ const registerHandler = (target, propertyKey, metadata) => {
8
+ (0, metadata_1.registerSocketHandlerMetadata)(target.constructor, {
9
+ ...metadata,
10
+ method: propertyKey,
11
+ });
12
+ };
13
+ const createInjectionDecorator = (token) => {
14
+ return (target, propertyKey, parameterIndex) => {
15
+ if (typeof parameterIndex === "number") {
16
+ (0, core_1.Qualifier)(token)(target, propertyKey, parameterIndex);
17
+ return;
18
+ }
19
+ if (propertyKey !== undefined) {
20
+ (0, core_1.AutoWired)({ qualifier: token })(target, propertyKey);
21
+ }
22
+ };
23
+ };
24
+ const SocketGateway = (options = {}) => {
25
+ return (target) => {
26
+ (0, metadata_1.registerSocketGatewayMetadata)(target, {
27
+ name: options.name?.trim() || undefined,
28
+ namespace: (0, metadata_1.normalizeNamespace)(options.namespace),
29
+ groups: (0, metadata_1.normalizeGroups)(options.group),
30
+ disabled: options.disabled === true,
31
+ });
32
+ };
33
+ };
34
+ exports.SocketGateway = SocketGateway;
35
+ const OnSocketConnection = (options = {}) => {
36
+ return (target, propertyKey) => {
37
+ registerHandler(target, propertyKey, {
38
+ kind: "connection",
39
+ name: options.name?.trim() || undefined,
40
+ namespace: options.namespace ? (0, metadata_1.normalizeNamespace)(options.namespace) : undefined,
41
+ once: false,
42
+ disabled: options.disabled === true,
43
+ });
44
+ };
45
+ };
46
+ exports.OnSocketConnection = OnSocketConnection;
47
+ const OnSocketDisconnect = (options = {}) => {
48
+ return (target, propertyKey) => {
49
+ registerHandler(target, propertyKey, {
50
+ kind: "disconnect",
51
+ name: options.name?.trim() || undefined,
52
+ namespace: options.namespace ? (0, metadata_1.normalizeNamespace)(options.namespace) : undefined,
53
+ once: false,
54
+ disabled: options.disabled === true,
55
+ });
56
+ };
57
+ };
58
+ exports.OnSocketDisconnect = OnSocketDisconnect;
59
+ const OnSocketEvent = (event, options = {}) => {
60
+ if (!event || !event.trim()) {
61
+ throw new Error("OnSocketEvent requires a non-empty event name");
62
+ }
63
+ return (target, propertyKey) => {
64
+ registerHandler(target, propertyKey, {
65
+ kind: "event",
66
+ event: event.trim(),
67
+ name: options.name?.trim() || undefined,
68
+ namespace: options.namespace ? (0, metadata_1.normalizeNamespace)(options.namespace) : undefined,
69
+ once: options.once === true,
70
+ disabled: options.disabled === true,
71
+ });
72
+ };
73
+ };
74
+ exports.OnSocketEvent = OnSocketEvent;
75
+ exports.SubscribeMessage = exports.OnSocketEvent;
76
+ const InjectSocketService = () => {
77
+ return createInjectionDecorator((0, tokens_1.getSocketIoServiceToken)());
78
+ };
79
+ exports.InjectSocketService = InjectSocketService;
80
+ const InjectSocketLifecycleManager = () => {
81
+ return createInjectionDecorator((0, tokens_1.getSocketIoLifecycleToken)());
82
+ };
83
+ exports.InjectSocketLifecycleManager = InjectSocketLifecycleManager;
84
+ const InjectSocketServer = () => {
85
+ return createInjectionDecorator((0, tokens_1.getSocketIoServerToken)());
86
+ };
87
+ exports.InjectSocketServer = InjectSocketServer;
88
+ const InjectSocketNamespace = (namespace = "/") => {
89
+ return createInjectionDecorator((0, tokens_1.getSocketIoNamespaceToken)(namespace));
90
+ };
91
+ exports.InjectSocketNamespace = InjectSocketNamespace;
@@ -0,0 +1,8 @@
1
+ import "reflect-metadata";
2
+ export * from "./types";
3
+ export * from "./tokens";
4
+ export * from "./metadata";
5
+ export * from "./configuration";
6
+ export * from "./decorators";
7
+ export * from "./socket-io.service";
8
+ export * from "./lifecycle";
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ require("reflect-metadata");
18
+ __exportStar(require("./types"), exports);
19
+ __exportStar(require("./tokens"), exports);
20
+ __exportStar(require("./metadata"), exports);
21
+ __exportStar(require("./configuration"), exports);
22
+ __exportStar(require("./decorators"), exports);
23
+ __exportStar(require("./socket-io.service"), exports);
24
+ __exportStar(require("./lifecycle"), exports);
@@ -0,0 +1,35 @@
1
+ import { ApplicationLifeCycle, Container } from "@xtaskjs/core";
2
+ import type { Namespace, Server } from "socket.io";
3
+ import { SocketEmitOptions, SocketGatewaySummary, SocketIoAttachTarget } from "./types";
4
+ export declare class SocketIoLifecycleManager {
5
+ private readonly gateways;
6
+ private readonly namespaces;
7
+ private container?;
8
+ private lifecycle?;
9
+ private adapter?;
10
+ private server?;
11
+ initialize(container?: Container, lifecycle?: ApplicationLifeCycle, attachTarget?: SocketIoAttachTarget): Promise<void>;
12
+ destroy(): Promise<void>;
13
+ getServer(): Server;
14
+ getNamespace(namespace?: string): Namespace;
15
+ listNamespaces(): string[];
16
+ listGateways(): SocketGatewaySummary[];
17
+ emit(event: string, payload: any, options?: SocketEmitOptions): void;
18
+ private attach;
19
+ private resolveHttpServer;
20
+ private discoverGateways;
21
+ private bindGateways;
22
+ private handleConnection;
23
+ private invokeEventHandler;
24
+ private invokeHandler;
25
+ private reportError;
26
+ private resolveEmitter;
27
+ private ensureNamespace;
28
+ private registerContainerBindings;
29
+ private registerRuntimeBindings;
30
+ private closeServer;
31
+ }
32
+ export declare const initializeSocketIoIntegration: (container?: Container, lifecycle?: ApplicationLifeCycle, attachTarget?: SocketIoAttachTarget) => Promise<void>;
33
+ export declare const shutdownSocketIoIntegration: () => Promise<void>;
34
+ export declare const getSocketIoLifecycleManager: () => SocketIoLifecycleManager;
35
+ export declare const resetSocketIoIntegration: () => Promise<void>;
@@ -0,0 +1,358 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resetSocketIoIntegration = exports.getSocketIoLifecycleManager = exports.shutdownSocketIoIntegration = exports.initializeSocketIoIntegration = exports.SocketIoLifecycleManager = void 0;
4
+ const socket_io_1 = require("socket.io");
5
+ const configuration_1 = require("./configuration");
6
+ const metadata_1 = require("./metadata");
7
+ const socket_io_service_1 = require("./socket-io.service");
8
+ const tokens_1 = require("./tokens");
9
+ const isHttpServerLike = (value) => {
10
+ return Boolean(value) && typeof value.on === "function" && typeof value.listen === "function";
11
+ };
12
+ const normalizeHandlerName = (gateway, targetName, methodName, event) => {
13
+ if (gateway.name && gateway.name.trim()) {
14
+ return `${gateway.name.trim()}.${event || methodName}`;
15
+ }
16
+ return `${targetName}.${methodName}`;
17
+ };
18
+ class SocketIoLifecycleManager {
19
+ constructor() {
20
+ this.gateways = new Map();
21
+ this.namespaces = new Map();
22
+ }
23
+ async initialize(container, lifecycle, attachTarget) {
24
+ await this.destroy();
25
+ this.container = container;
26
+ this.lifecycle = lifecycle;
27
+ this.adapter = attachTarget;
28
+ this.registerContainerBindings(container);
29
+ if (attachTarget) {
30
+ await this.attach(attachTarget);
31
+ }
32
+ this.discoverGateways(container);
33
+ this.bindGateways();
34
+ if (lifecycle && typeof lifecycle.on === "function") {
35
+ lifecycle.on("stopping", async () => {
36
+ await this.closeServer();
37
+ });
38
+ }
39
+ }
40
+ async destroy() {
41
+ await this.closeServer();
42
+ this.gateways.clear();
43
+ this.namespaces.clear();
44
+ this.container = undefined;
45
+ this.lifecycle = undefined;
46
+ this.adapter = undefined;
47
+ }
48
+ getServer() {
49
+ if (!this.server) {
50
+ throw new Error("Socket.IO server is not initialized. Call initializeSocketIoIntegration() after app.listen().");
51
+ }
52
+ return this.server;
53
+ }
54
+ getNamespace(namespace = "/") {
55
+ const normalizedNamespace = (0, metadata_1.normalizeNamespace)(namespace);
56
+ const discoveredNamespace = this.namespaces.get(normalizedNamespace);
57
+ if (discoveredNamespace) {
58
+ return discoveredNamespace;
59
+ }
60
+ if (!this.server) {
61
+ throw new Error("Socket.IO server is not initialized. Call initializeSocketIoIntegration() after app.listen().");
62
+ }
63
+ return this.ensureNamespace(normalizedNamespace);
64
+ }
65
+ listNamespaces() {
66
+ const names = new Set([(0, configuration_1.getSocketIoConfiguration)().defaultNamespace]);
67
+ for (const gateway of this.gateways.values()) {
68
+ names.add(gateway.namespace);
69
+ for (const handler of gateway.handlers) {
70
+ names.add(handler.namespace);
71
+ }
72
+ }
73
+ for (const namespace of this.namespaces.keys()) {
74
+ names.add(namespace);
75
+ }
76
+ return Array.from(names).sort();
77
+ }
78
+ listGateways() {
79
+ return Array.from(this.gateways.values())
80
+ .map((gateway) => ({
81
+ name: gateway.name,
82
+ namespace: gateway.namespace,
83
+ targetName: gateway.targetName,
84
+ groups: [...gateway.groups],
85
+ disabled: gateway.disabled,
86
+ handlers: gateway.handlers.map((handler) => ({
87
+ name: handler.name,
88
+ kind: handler.kind,
89
+ event: handler.event,
90
+ namespace: handler.namespace,
91
+ methodName: handler.methodName,
92
+ once: handler.once,
93
+ disabled: handler.disabled,
94
+ })),
95
+ }))
96
+ .sort((left, right) => left.name.localeCompare(right.name));
97
+ }
98
+ emit(event, payload, options = {}) {
99
+ if (!event || !event.trim()) {
100
+ throw new Error("Socket.IO emit requires a non-empty event name");
101
+ }
102
+ const emitter = this.resolveEmitter(options);
103
+ emitter.emit(event.trim(), payload);
104
+ }
105
+ async attach(target) {
106
+ const httpServer = this.resolveHttpServer(target);
107
+ if (!httpServer) {
108
+ throw new Error("Socket.IO integration requires a Node HTTP server or an HTTP adapter exposing getHttpServer()");
109
+ }
110
+ this.server = new socket_io_1.Server(httpServer, {
111
+ ...((0, configuration_1.getSocketIoConfiguration)().serverOptions || {}),
112
+ });
113
+ this.registerRuntimeBindings();
114
+ }
115
+ resolveHttpServer(target) {
116
+ if (!target) {
117
+ return undefined;
118
+ }
119
+ if (isHttpServerLike(target)) {
120
+ return target;
121
+ }
122
+ if (typeof target.getHttpServer === "function") {
123
+ return target.getHttpServer?.();
124
+ }
125
+ if (typeof target.getHttpServer === "function") {
126
+ return target.getHttpServer();
127
+ }
128
+ return undefined;
129
+ }
130
+ discoverGateways(container) {
131
+ if (!container || typeof container.getRegisteredTypes !== "function") {
132
+ return;
133
+ }
134
+ const registeredTypes = container.getRegisteredTypes();
135
+ for (const type of registeredTypes) {
136
+ const gatewayMetadata = (0, metadata_1.getSocketGatewayMetadata)(type);
137
+ if (!gatewayMetadata) {
138
+ continue;
139
+ }
140
+ const targetName = type.name || "Anonymous";
141
+ const namespace = (0, metadata_1.normalizeNamespace)(gatewayMetadata.namespace);
142
+ if (this.server) {
143
+ this.ensureNamespace(namespace);
144
+ }
145
+ const handlerMetadata = (0, metadata_1.getSocketHandlerMetadata)(type).map((handler) => {
146
+ const methodName = String(handler.method);
147
+ const handlerNamespace = (0, metadata_1.normalizeNamespace)(handler.namespace || namespace);
148
+ if (this.server) {
149
+ this.ensureNamespace(handlerNamespace);
150
+ }
151
+ return {
152
+ name: handler.name?.trim() || normalizeHandlerName(gatewayMetadata, targetName, methodName, handler.event),
153
+ kind: handler.kind,
154
+ event: handler.event,
155
+ namespace: handlerNamespace,
156
+ methodName,
157
+ once: handler.once === true,
158
+ disabled: handler.disabled === true,
159
+ };
160
+ });
161
+ const instance = container.get(type);
162
+ const gatewayName = gatewayMetadata.name?.trim() || targetName;
163
+ this.gateways.set(gatewayName, {
164
+ name: gatewayName,
165
+ namespace,
166
+ targetName,
167
+ groups: [...gatewayMetadata.groups],
168
+ disabled: gatewayMetadata.disabled,
169
+ instance,
170
+ handlers: handlerMetadata,
171
+ });
172
+ }
173
+ }
174
+ bindGateways() {
175
+ if (!this.server) {
176
+ return;
177
+ }
178
+ for (const gateway of this.gateways.values()) {
179
+ if (gateway.disabled) {
180
+ continue;
181
+ }
182
+ const namespace = this.ensureNamespace(gateway.namespace);
183
+ namespace.on("connection", (socket) => {
184
+ void this.handleConnection(gateway, namespace, socket);
185
+ });
186
+ }
187
+ }
188
+ async handleConnection(gateway, namespace, socket) {
189
+ for (const handler of gateway.handlers) {
190
+ if (handler.disabled || handler.namespace !== gateway.namespace) {
191
+ continue;
192
+ }
193
+ if (handler.kind === "connection") {
194
+ await this.invokeHandler(gateway, handler, [socket], namespace, socket);
195
+ }
196
+ }
197
+ for (const handler of gateway.handlers) {
198
+ if (handler.disabled || handler.namespace !== gateway.namespace) {
199
+ continue;
200
+ }
201
+ if (handler.kind === "disconnect") {
202
+ socket.on("disconnect", (reason) => {
203
+ void this.invokeHandler(gateway, handler, [reason, socket], namespace, socket);
204
+ });
205
+ continue;
206
+ }
207
+ if (handler.kind !== "event" || !handler.event) {
208
+ continue;
209
+ }
210
+ const subscribe = handler.once ? socket.once.bind(socket) : socket.on.bind(socket);
211
+ subscribe(handler.event, (...args) => {
212
+ void this.invokeEventHandler(gateway, handler, args, namespace, socket);
213
+ });
214
+ }
215
+ }
216
+ async invokeEventHandler(gateway, handler, args, namespace, socket) {
217
+ const maybeAck = args.length > 0 && typeof args[args.length - 1] === "function" ? args[args.length - 1] : undefined;
218
+ const payloadArgs = maybeAck ? args.slice(0, -1) : args;
219
+ try {
220
+ const result = await this.invokeHandler(gateway, handler, payloadArgs, namespace, socket, maybeAck);
221
+ if (maybeAck && result !== undefined) {
222
+ maybeAck(result);
223
+ }
224
+ }
225
+ catch (error) {
226
+ await this.reportError(error);
227
+ }
228
+ }
229
+ async invokeHandler(gateway, handler, args, namespace, socket, ack) {
230
+ try {
231
+ const context = {
232
+ socket,
233
+ server: this.getServer(),
234
+ namespace,
235
+ container: this.container,
236
+ lifecycle: this.lifecycle,
237
+ gateway: gateway.name,
238
+ event: handler.event,
239
+ ack,
240
+ adapter: this.adapter,
241
+ };
242
+ if (handler.kind === "connection") {
243
+ return await Promise.resolve(gateway.instance[handler.methodName].call(gateway.instance, socket, context));
244
+ }
245
+ if (handler.kind === "disconnect") {
246
+ const [reason] = args;
247
+ return await Promise.resolve(gateway.instance[handler.methodName].call(gateway.instance, reason, socket, context));
248
+ }
249
+ return await Promise.resolve(gateway.instance[handler.methodName].call(gateway.instance, ...args, context));
250
+ }
251
+ catch (error) {
252
+ await this.reportError(error);
253
+ throw error;
254
+ }
255
+ }
256
+ async reportError(error) {
257
+ if (this.lifecycle && typeof this.lifecycle.emit === "function") {
258
+ await this.lifecycle.emit("error", error);
259
+ }
260
+ }
261
+ resolveEmitter(options) {
262
+ let emitter = this.getNamespace(options.namespace || (0, configuration_1.getSocketIoConfiguration)().defaultNamespace);
263
+ const rooms = Array.isArray(options.room) ? options.room : options.room ? [options.room] : [];
264
+ for (const room of rooms) {
265
+ emitter = emitter.to(room);
266
+ }
267
+ const excludedRooms = Array.isArray(options.except)
268
+ ? options.except
269
+ : options.except
270
+ ? [options.except]
271
+ : [];
272
+ for (const room of excludedRooms) {
273
+ if (typeof emitter.except === "function") {
274
+ emitter = emitter.except(room);
275
+ }
276
+ }
277
+ if (options.volatile && emitter.volatile) {
278
+ emitter = emitter.volatile;
279
+ }
280
+ if (options.local && emitter.local) {
281
+ emitter = emitter.local;
282
+ }
283
+ if (options.compress === false && typeof emitter.compress === "function") {
284
+ emitter = emitter.compress(false);
285
+ }
286
+ if (typeof options.timeoutMs === "number" && typeof emitter.timeout === "function") {
287
+ emitter = emitter.timeout(options.timeoutMs);
288
+ }
289
+ return emitter;
290
+ }
291
+ ensureNamespace(namespaceName) {
292
+ const normalizedNamespace = (0, metadata_1.normalizeNamespace)(namespaceName);
293
+ const existingNamespace = this.namespaces.get(normalizedNamespace);
294
+ if (existingNamespace) {
295
+ return existingNamespace;
296
+ }
297
+ const namespace = this.getServer().of(normalizedNamespace);
298
+ this.namespaces.set(normalizedNamespace, namespace);
299
+ if (this.container && typeof this.container.registerNamedInstance === "function") {
300
+ this.container.registerNamedInstance((0, tokens_1.getSocketIoNamespaceToken)(normalizedNamespace), namespace);
301
+ }
302
+ return namespace;
303
+ }
304
+ registerContainerBindings(container) {
305
+ if (!container) {
306
+ return;
307
+ }
308
+ const anyContainer = container;
309
+ if (typeof anyContainer.registerNamedInstance === "function") {
310
+ anyContainer.registerNamedInstance((0, tokens_1.getSocketIoLifecycleToken)(), this);
311
+ }
312
+ if (typeof anyContainer.registerWithName === "function") {
313
+ anyContainer.registerWithName(socket_io_service_1.SocketIoService, { scope: "singleton" }, (0, tokens_1.getSocketIoServiceToken)());
314
+ }
315
+ }
316
+ registerRuntimeBindings() {
317
+ if (!this.container || !this.server || typeof this.container.registerNamedInstance !== "function") {
318
+ return;
319
+ }
320
+ const anyContainer = this.container;
321
+ anyContainer.registerNamedInstance((0, tokens_1.getSocketIoServerToken)(), this.server);
322
+ this.ensureNamespace((0, configuration_1.getSocketIoConfiguration)().defaultNamespace);
323
+ }
324
+ async closeServer() {
325
+ if (!this.server) {
326
+ return;
327
+ }
328
+ const server = this.server;
329
+ this.server = undefined;
330
+ this.namespaces.clear();
331
+ await new Promise((resolve, reject) => {
332
+ server.close((error) => {
333
+ if (error) {
334
+ reject(error);
335
+ return;
336
+ }
337
+ resolve();
338
+ });
339
+ });
340
+ }
341
+ }
342
+ exports.SocketIoLifecycleManager = SocketIoLifecycleManager;
343
+ const lifecycleManager = new SocketIoLifecycleManager();
344
+ const initializeSocketIoIntegration = async (container, lifecycle, attachTarget) => {
345
+ await lifecycleManager.initialize(container, lifecycle, attachTarget);
346
+ };
347
+ exports.initializeSocketIoIntegration = initializeSocketIoIntegration;
348
+ const shutdownSocketIoIntegration = async () => {
349
+ await lifecycleManager.destroy();
350
+ };
351
+ exports.shutdownSocketIoIntegration = shutdownSocketIoIntegration;
352
+ const getSocketIoLifecycleManager = () => lifecycleManager;
353
+ exports.getSocketIoLifecycleManager = getSocketIoLifecycleManager;
354
+ const resetSocketIoIntegration = async () => {
355
+ await (0, exports.shutdownSocketIoIntegration)();
356
+ (0, configuration_1.resetSocketIoConfiguration)();
357
+ };
358
+ exports.resetSocketIoIntegration = resetSocketIoIntegration;
@@ -0,0 +1,7 @@
1
+ import { SocketGatewayMetadata, SocketHandlerMetadata } from "./types";
2
+ export declare const normalizeNamespace: (value?: string) => string;
3
+ export declare const normalizeGroups: (value?: string | string[]) => string[];
4
+ export declare const registerSocketGatewayMetadata: (target: any, metadata: SocketGatewayMetadata) => void;
5
+ export declare const getSocketGatewayMetadata: (target: any) => SocketGatewayMetadata | undefined;
6
+ export declare const registerSocketHandlerMetadata: (target: any, metadata: SocketHandlerMetadata) => void;
7
+ export declare const getSocketHandlerMetadata: (target: any) => SocketHandlerMetadata[];
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSocketHandlerMetadata = exports.registerSocketHandlerMetadata = exports.getSocketGatewayMetadata = exports.registerSocketGatewayMetadata = exports.normalizeGroups = exports.normalizeNamespace = void 0;
4
+ const SOCKET_GATEWAY_METADATA_KEY = "xtask:socket-io:gateway";
5
+ const SOCKET_HANDLER_METADATA_KEY = "xtask:socket-io:handlers";
6
+ const normalizeNamespace = (value) => {
7
+ const normalizedValue = String(value || "/").trim();
8
+ if (!normalizedValue || normalizedValue === "/") {
9
+ return "/";
10
+ }
11
+ const withLeadingSlash = normalizedValue.startsWith("/") ? normalizedValue : `/${normalizedValue}`;
12
+ return withLeadingSlash.endsWith("/") ? withLeadingSlash.slice(0, -1) : withLeadingSlash;
13
+ };
14
+ exports.normalizeNamespace = normalizeNamespace;
15
+ const normalizeGroups = (value) => {
16
+ if (!value) {
17
+ return [];
18
+ }
19
+ const groups = Array.isArray(value) ? value : [value];
20
+ return Array.from(new Set(groups
21
+ .map((group) => group.trim())
22
+ .filter((group) => group.length > 0)));
23
+ };
24
+ exports.normalizeGroups = normalizeGroups;
25
+ const registerSocketGatewayMetadata = (target, metadata) => {
26
+ Reflect.defineMetadata(SOCKET_GATEWAY_METADATA_KEY, metadata, target);
27
+ };
28
+ exports.registerSocketGatewayMetadata = registerSocketGatewayMetadata;
29
+ const getSocketGatewayMetadata = (target) => {
30
+ return Reflect.getMetadata(SOCKET_GATEWAY_METADATA_KEY, target);
31
+ };
32
+ exports.getSocketGatewayMetadata = getSocketGatewayMetadata;
33
+ const registerSocketHandlerMetadata = (target, metadata) => {
34
+ const existingMetadata = (0, exports.getSocketHandlerMetadata)(target);
35
+ existingMetadata.push(metadata);
36
+ Reflect.defineMetadata(SOCKET_HANDLER_METADATA_KEY, existingMetadata, target);
37
+ };
38
+ exports.registerSocketHandlerMetadata = registerSocketHandlerMetadata;
39
+ const getSocketHandlerMetadata = (target) => {
40
+ return Reflect.getMetadata(SOCKET_HANDLER_METADATA_KEY, target) || [];
41
+ };
42
+ exports.getSocketHandlerMetadata = getSocketHandlerMetadata;
@@ -0,0 +1,9 @@
1
+ import type { Namespace, Server } from "socket.io";
2
+ import { SocketEmitOptions, SocketGatewaySummary } from "./types";
3
+ export declare class SocketIoService {
4
+ getServer(): Server;
5
+ getNamespace(namespace?: string): Namespace;
6
+ listNamespaces(): string[];
7
+ listGateways(): SocketGatewaySummary[];
8
+ emit(event: string, payload: any, options?: SocketEmitOptions): void;
9
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SocketIoService = void 0;
4
+ const lifecycle_1 = require("./lifecycle");
5
+ class SocketIoService {
6
+ getServer() {
7
+ return (0, lifecycle_1.getSocketIoLifecycleManager)().getServer();
8
+ }
9
+ getNamespace(namespace = "/") {
10
+ return (0, lifecycle_1.getSocketIoLifecycleManager)().getNamespace(namespace);
11
+ }
12
+ listNamespaces() {
13
+ return (0, lifecycle_1.getSocketIoLifecycleManager)().listNamespaces();
14
+ }
15
+ listGateways() {
16
+ return (0, lifecycle_1.getSocketIoLifecycleManager)().listGateways();
17
+ }
18
+ emit(event, payload, options = {}) {
19
+ (0, lifecycle_1.getSocketIoLifecycleManager)().emit(event, payload, options);
20
+ }
21
+ }
22
+ exports.SocketIoService = SocketIoService;
@@ -0,0 +1,4 @@
1
+ export declare const getSocketIoLifecycleToken: () => string;
2
+ export declare const getSocketIoServiceToken: () => string;
3
+ export declare const getSocketIoServerToken: () => string;
4
+ export declare const getSocketIoNamespaceToken: (namespace?: string) => string;
package/dist/tokens.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSocketIoNamespaceToken = exports.getSocketIoServerToken = exports.getSocketIoServiceToken = exports.getSocketIoLifecycleToken = void 0;
4
+ const metadata_1 = require("./metadata");
5
+ const SOCKET_IO_LIFECYCLE_TOKEN = "xtask:socket-io:lifecycle";
6
+ const SOCKET_IO_SERVICE_TOKEN = "xtask:socket-io:service";
7
+ const SOCKET_IO_SERVER_TOKEN = "xtask:socket-io:server";
8
+ const getSocketIoLifecycleToken = () => SOCKET_IO_LIFECYCLE_TOKEN;
9
+ exports.getSocketIoLifecycleToken = getSocketIoLifecycleToken;
10
+ const getSocketIoServiceToken = () => SOCKET_IO_SERVICE_TOKEN;
11
+ exports.getSocketIoServiceToken = getSocketIoServiceToken;
12
+ const getSocketIoServerToken = () => SOCKET_IO_SERVER_TOKEN;
13
+ exports.getSocketIoServerToken = getSocketIoServerToken;
14
+ const getSocketIoNamespaceToken = (namespace = "/") => {
15
+ return `xtask:socket-io:namespace:${(0, metadata_1.normalizeNamespace)(namespace)}`;
16
+ };
17
+ exports.getSocketIoNamespaceToken = getSocketIoNamespaceToken;
@@ -0,0 +1,77 @@
1
+ import type { Server as HttpServer } from "http";
2
+ import type { ApplicationLifeCycle, Container, HttpAdapter } from "@xtaskjs/core";
3
+ import type { Namespace, Server, ServerOptions, Socket } from "socket.io";
4
+ export type SocketIoAttachTarget = HttpAdapter | HttpServer | {
5
+ getHttpServer?: () => HttpServer | undefined;
6
+ getNativeApp?: () => any;
7
+ type?: string;
8
+ };
9
+ export interface SocketIoConfiguration {
10
+ defaultNamespace?: string;
11
+ serverOptions?: Partial<ServerOptions>;
12
+ }
13
+ export interface SocketGatewayOptions {
14
+ name?: string;
15
+ namespace?: string;
16
+ group?: string | string[];
17
+ disabled?: boolean;
18
+ }
19
+ export interface SocketGatewayMetadata {
20
+ name?: string;
21
+ namespace: string;
22
+ groups: string[];
23
+ disabled: boolean;
24
+ }
25
+ export type SocketHandlerKind = "connection" | "disconnect" | "event";
26
+ export interface SocketHandlerOptions {
27
+ name?: string;
28
+ namespace?: string;
29
+ once?: boolean;
30
+ disabled?: boolean;
31
+ }
32
+ export interface SocketHandlerMetadata {
33
+ kind: SocketHandlerKind;
34
+ method: string | symbol;
35
+ event?: string;
36
+ name?: string;
37
+ namespace?: string;
38
+ once?: boolean;
39
+ disabled?: boolean;
40
+ }
41
+ export interface SocketHandlerContext {
42
+ socket: Socket;
43
+ server: Server;
44
+ namespace: Namespace;
45
+ container?: Container;
46
+ lifecycle?: ApplicationLifeCycle;
47
+ gateway: string;
48
+ event?: string;
49
+ ack?: (...args: any[]) => void;
50
+ adapter?: SocketIoAttachTarget;
51
+ }
52
+ export interface SocketHandlerSummary {
53
+ name: string;
54
+ kind: SocketHandlerKind;
55
+ event?: string;
56
+ namespace: string;
57
+ methodName: string;
58
+ once: boolean;
59
+ disabled: boolean;
60
+ }
61
+ export interface SocketGatewaySummary {
62
+ name: string;
63
+ namespace: string;
64
+ targetName: string;
65
+ groups: string[];
66
+ disabled: boolean;
67
+ handlers: SocketHandlerSummary[];
68
+ }
69
+ export interface SocketEmitOptions {
70
+ namespace?: string;
71
+ room?: string | string[];
72
+ except?: string | string[];
73
+ volatile?: boolean;
74
+ local?: boolean;
75
+ compress?: boolean;
76
+ timeoutMs?: number;
77
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@xtaskjs/socket-io",
3
+ "version": "1.0.1",
4
+ "description": "Socket.IO integration for xtaskjs.",
5
+ "author": "Javier Rodriguez Soler",
6
+ "homepage": "https://xtaskjs.io",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "require": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "scripts": {
22
+ "build": "npm run build --prefix ../core && rm -rf dist && tsc",
23
+ "prepack": "npm run build",
24
+ "test": "jest --passWithNoTests",
25
+ "test:coverage": "jest --coverage --runInBand",
26
+ "coverage:open": "xdg-open coverage/lcov-report/index.html"
27
+ },
28
+ "funding": {
29
+ "type": "opencollective",
30
+ "url": "https://opencollective.com/xtaskjs"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/xtaskjs/xtask.git",
35
+ "directory": "packages/socket-io"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/xtaskjs/xtask/issues"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "license": "MIT",
44
+ "dependencies": {
45
+ "@xtaskjs/core": "^1.0.26",
46
+ "socket.io": "^4.8.1"
47
+ },
48
+ "peerDependencies": {
49
+ "reflect-metadata": "^0.1.12 || ^0.2.0"
50
+ },
51
+ "devDependencies": {
52
+ "@jest/globals": "^30.1.2",
53
+ "@types/jest": "^30.0.0",
54
+ "jest": "^30.1.3",
55
+ "nodemon": "^3.1.10",
56
+ "ts-jest": "^29.4.4",
57
+ "ts-node": "^10.9.2",
58
+ "tsconfig-paths": "^4.2.0",
59
+ "typescript": "^5.9.2"
60
+ }
61
+ }