@bymax-one/nest-realtime 1.2.16 → 1.2.18
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 +63 -3
- package/README.md +31 -22
- package/dist/internal/index.cjs +349 -88
- package/dist/internal/index.d.cts +53 -11
- package/dist/internal/index.d.ts +53 -11
- package/dist/internal/index.mjs +348 -89
- package/dist/react/index.cjs +163 -101
- package/dist/react/index.mjs +164 -102
- package/dist/websocket/index.cjs +18 -3
- package/dist/websocket/index.d.cts +4 -0
- package/dist/websocket/index.d.ts +4 -0
- package/dist/websocket/index.mjs +19 -4
- package/package.json +4 -3
package/dist/internal/index.cjs
CHANGED
|
@@ -43,6 +43,76 @@ var REALTIME_ERROR_CODES = {
|
|
|
43
43
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
|
44
44
|
};
|
|
45
45
|
|
|
46
|
+
// src/server/config/drop-unset.ts
|
|
47
|
+
var SSE_KEYS = {
|
|
48
|
+
endpoint: true,
|
|
49
|
+
heartbeatMs: true,
|
|
50
|
+
replayBufferSize: true,
|
|
51
|
+
replayTtlMs: true,
|
|
52
|
+
replayMaxIdleUsers: true,
|
|
53
|
+
maxConnectionsPerUser: true,
|
|
54
|
+
emitConnectionEvent: true,
|
|
55
|
+
maxQueuedBytes: true,
|
|
56
|
+
maxQueuedEvents: true,
|
|
57
|
+
stallHeartbeats: true
|
|
58
|
+
};
|
|
59
|
+
var WEBSOCKET_KEYS = {
|
|
60
|
+
namespace: true,
|
|
61
|
+
cors: true,
|
|
62
|
+
maxHttpBufferSize: true,
|
|
63
|
+
pingIntervalMs: true,
|
|
64
|
+
pingTimeoutMs: true,
|
|
65
|
+
maxConnectionsPerUser: true,
|
|
66
|
+
emitConnectionEvent: true,
|
|
67
|
+
redisAdapter: true
|
|
68
|
+
};
|
|
69
|
+
var REAUTHENTICATION_KEYS = {
|
|
70
|
+
intervalSeconds: true,
|
|
71
|
+
onFailure: true,
|
|
72
|
+
cacheTtlMs: true,
|
|
73
|
+
revalidateTimeoutMs: true,
|
|
74
|
+
concurrency: true
|
|
75
|
+
};
|
|
76
|
+
var TOP_LEVEL_KEYS = {
|
|
77
|
+
transport: true,
|
|
78
|
+
authenticator: true,
|
|
79
|
+
tenantResolver: true,
|
|
80
|
+
hooks: true,
|
|
81
|
+
hookTimeoutMs: true,
|
|
82
|
+
onConnectFailure: true,
|
|
83
|
+
authenticateTimeoutMs: true,
|
|
84
|
+
maxPendingHandshakes: true,
|
|
85
|
+
maxConnections: true,
|
|
86
|
+
pubsub: true,
|
|
87
|
+
offlineQueue: true,
|
|
88
|
+
presence: true,
|
|
89
|
+
sse: true,
|
|
90
|
+
websocket: true,
|
|
91
|
+
reauthenticationPolicy: true
|
|
92
|
+
};
|
|
93
|
+
var GROUPS = {
|
|
94
|
+
sse: SSE_KEYS,
|
|
95
|
+
websocket: WEBSOCKET_KEYS,
|
|
96
|
+
reauthenticationPolicy: REAUTHENTICATION_KEYS
|
|
97
|
+
};
|
|
98
|
+
function readSet(source, known) {
|
|
99
|
+
const kept = {};
|
|
100
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(source), ...Object.keys(known)])) {
|
|
101
|
+
const value = source[key];
|
|
102
|
+
if (value !== void 0 && value !== null) kept[key] = value;
|
|
103
|
+
}
|
|
104
|
+
return kept;
|
|
105
|
+
}
|
|
106
|
+
function dropUnset(options) {
|
|
107
|
+
const kept = readSet(options, TOP_LEVEL_KEYS);
|
|
108
|
+
for (const [group, keys] of Object.entries(GROUPS)) {
|
|
109
|
+
const value = kept[group];
|
|
110
|
+
if (typeof value === "object" && !Array.isArray(value))
|
|
111
|
+
kept[group] = readSet(value, keys);
|
|
112
|
+
}
|
|
113
|
+
return kept;
|
|
114
|
+
}
|
|
115
|
+
|
|
46
116
|
// src/server/config/default-options.ts
|
|
47
117
|
var DEFAULT_SSE = {
|
|
48
118
|
endpoint: "/realtime/sse",
|
|
@@ -56,7 +126,8 @@ var DEFAULT_SSE = {
|
|
|
56
126
|
maxQueuedEvents: 1e3,
|
|
57
127
|
stallHeartbeats: 3
|
|
58
128
|
};
|
|
59
|
-
function applyDefaults(
|
|
129
|
+
function applyDefaults(raw) {
|
|
130
|
+
const options = dropUnset(raw);
|
|
60
131
|
return Object.freeze({
|
|
61
132
|
...options,
|
|
62
133
|
sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
|
|
@@ -77,6 +148,23 @@ var DEFAULT_HOOK_TIMEOUT_MS = 5e3;
|
|
|
77
148
|
var HEARTBEAT_MIN_MS = 5e3;
|
|
78
149
|
var HEARTBEAT_MAX_MS = 9e4;
|
|
79
150
|
|
|
151
|
+
// src/server/utils/describe-received.ts
|
|
152
|
+
var KIND_OF_TYPE = {
|
|
153
|
+
string: "a string",
|
|
154
|
+
boolean: "a boolean",
|
|
155
|
+
bigint: "a bigint",
|
|
156
|
+
symbol: "a symbol",
|
|
157
|
+
function: "a function",
|
|
158
|
+
undefined: "undefined"
|
|
159
|
+
};
|
|
160
|
+
function describeReceived(value) {
|
|
161
|
+
if (typeof value === "number") {
|
|
162
|
+
return Number.isFinite(value) ? String(value) : "a number that is not finite";
|
|
163
|
+
}
|
|
164
|
+
if (value === null) return "null";
|
|
165
|
+
return Array.isArray(value) ? "an array" : KIND_OF_TYPE[typeof value] ?? "an object";
|
|
166
|
+
}
|
|
167
|
+
|
|
80
168
|
// src/server/utils/realtime-error.ts
|
|
81
169
|
function realtimeError(code, detail, options = {}) {
|
|
82
170
|
const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
|
|
@@ -85,13 +173,81 @@ function realtimeError(code, detail, options = {}) {
|
|
|
85
173
|
return Object.assign(error, { code });
|
|
86
174
|
}
|
|
87
175
|
|
|
176
|
+
// src/server/config/validate-shapes.ts
|
|
177
|
+
var REQUIRED_FUNCTIONS = {
|
|
178
|
+
pubsub: ["publish", "subscribe"],
|
|
179
|
+
offlineQueue: ["append", "retrieveSince", "acknowledge"],
|
|
180
|
+
presence: ["setOnline", "setOffline", "isOnline", "listOnlineByTenant", "countOnline"]
|
|
181
|
+
};
|
|
182
|
+
var HOOK_NAMES = [
|
|
183
|
+
"onConnect",
|
|
184
|
+
"onDisconnect",
|
|
185
|
+
"onError",
|
|
186
|
+
"onReauthenticationFailed",
|
|
187
|
+
"onDeliveryFailure"
|
|
188
|
+
];
|
|
189
|
+
var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
|
|
190
|
+
function refuse(path, expected, received) {
|
|
191
|
+
throw realtimeError(
|
|
192
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
193
|
+
`options.${path} must be ${expected}, received ${describeReceived(received)}`,
|
|
194
|
+
{ who: "BymaxRealtimeModule" }
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
function isObject(value) {
|
|
198
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
199
|
+
}
|
|
200
|
+
function assertObject(path, value) {
|
|
201
|
+
if (value !== void 0 && !isObject(value)) refuse(path, "an object", value);
|
|
202
|
+
}
|
|
203
|
+
function assertFunction(path, value) {
|
|
204
|
+
if (typeof value !== "function") refuse(path, "a function", value);
|
|
205
|
+
}
|
|
206
|
+
function assertOptionalFunction(path, value) {
|
|
207
|
+
if (value !== void 0 && value !== null) assertFunction(path, value);
|
|
208
|
+
}
|
|
209
|
+
function assertBoolean(path, value) {
|
|
210
|
+
if (value !== void 0 && typeof value !== "boolean") refuse(path, "a boolean", value);
|
|
211
|
+
}
|
|
212
|
+
function assertEndpoint(path, value) {
|
|
213
|
+
if (value !== void 0 && !(typeof value === "string" && value.trim().length > 0)) {
|
|
214
|
+
refuse(path, "a non-blank string", value);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function validatePieces(options) {
|
|
218
|
+
for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
|
|
219
|
+
const piece = options[name];
|
|
220
|
+
assertObject(name, piece);
|
|
221
|
+
if (piece === void 0) continue;
|
|
222
|
+
for (const fn of functions)
|
|
223
|
+
assertFunction(`${name}.${fn}`, piece[fn]);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function validateHooks(options) {
|
|
227
|
+
const hooks = options.hooks;
|
|
228
|
+
assertObject("hooks", hooks);
|
|
229
|
+
if (hooks === void 0) return;
|
|
230
|
+
for (const hook of HOOK_NAMES)
|
|
231
|
+
assertOptionalFunction(`hooks.${hook}`, hooks[hook]);
|
|
232
|
+
}
|
|
233
|
+
function validateShapes(options) {
|
|
234
|
+
for (const group of GROUP_NAMES) assertObject(group, options[group]);
|
|
235
|
+
validatePieces(options);
|
|
236
|
+
validateHooks(options);
|
|
237
|
+
assertOptionalFunction("tenantResolver", options.tenantResolver);
|
|
238
|
+
assertBoolean("sse.emitConnectionEvent", options.sse?.emitConnectionEvent);
|
|
239
|
+
assertBoolean("websocket.emitConnectionEvent", options.websocket?.emitConnectionEvent);
|
|
240
|
+
assertEndpoint("sse.endpoint", options.sse?.endpoint);
|
|
241
|
+
}
|
|
242
|
+
|
|
88
243
|
// src/server/config/validate-options.ts
|
|
89
244
|
var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
|
|
90
|
-
function validateOptions(
|
|
245
|
+
function validateOptions(raw) {
|
|
246
|
+
const options = dropUnset(raw);
|
|
91
247
|
if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
|
|
92
248
|
throw realtimeError(
|
|
93
249
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
94
|
-
`options.transport must be one of 'sse' | 'websocket' | 'both'
|
|
250
|
+
`options.transport must be one of 'sse' | 'websocket' | 'both', received ${describeReceived(options.transport)}`,
|
|
95
251
|
{ who: "BymaxRealtimeModule" }
|
|
96
252
|
);
|
|
97
253
|
}
|
|
@@ -109,18 +265,32 @@ function validateOptions(options) {
|
|
|
109
265
|
{ who: "BymaxRealtimeModule" }
|
|
110
266
|
);
|
|
111
267
|
}
|
|
268
|
+
validateShapes(options);
|
|
112
269
|
validateHookTimeout(options);
|
|
270
|
+
validateOnConnectFailure(options);
|
|
113
271
|
validateSseOptions(options);
|
|
114
272
|
validateReauthPolicy(options);
|
|
115
273
|
}
|
|
116
274
|
var MAX_TIMER_MS = 2147483647;
|
|
275
|
+
var MAX_PER_USER_CONNECTIONS = 1e5;
|
|
276
|
+
var MAX_REPLAY_EVENTS = 1e5;
|
|
277
|
+
var MAX_HTTP_BUFFER_BYTES = 100 * 1024 * 1024;
|
|
117
278
|
function assertInteger(path, value, least, most) {
|
|
118
279
|
if (value === void 0) return;
|
|
119
|
-
const valid = typeof value === "number" && Number.
|
|
280
|
+
const valid = typeof value === "number" && Number.isSafeInteger(value) && value >= least && (most === void 0 || value <= most);
|
|
120
281
|
if (valid) return;
|
|
121
282
|
throw realtimeError(
|
|
122
283
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
123
|
-
`options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`},
|
|
284
|
+
`options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, received ${describeReceived(value)}${most === void 0 && Number.isInteger(value) && !Number.isSafeInteger(value) ? ` (the most is ${Number.MAX_SAFE_INTEGER})` : ""}`,
|
|
285
|
+
{ who: "BymaxRealtimeModule" }
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
function validateOnConnectFailure(options) {
|
|
289
|
+
const value = options.onConnectFailure;
|
|
290
|
+
if (value === void 0 || value === "ignore" || value === "close") return;
|
|
291
|
+
throw realtimeError(
|
|
292
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
293
|
+
`options.onConnectFailure must be 'ignore' or 'close', received ${describeReceived(value)}`,
|
|
124
294
|
{ who: "BymaxRealtimeModule" }
|
|
125
295
|
);
|
|
126
296
|
}
|
|
@@ -129,6 +299,18 @@ function validateHookTimeout(options) {
|
|
|
129
299
|
assertInteger("authenticateTimeoutMs", options.authenticateTimeoutMs, 1, MAX_TIMER_MS);
|
|
130
300
|
assertInteger("maxPendingHandshakes", options.maxPendingHandshakes, 1);
|
|
131
301
|
assertInteger("maxConnections", options.maxConnections, 1);
|
|
302
|
+
assertInteger(
|
|
303
|
+
"websocket.maxConnectionsPerUser",
|
|
304
|
+
options.websocket?.maxConnectionsPerUser,
|
|
305
|
+
0,
|
|
306
|
+
MAX_PER_USER_CONNECTIONS
|
|
307
|
+
);
|
|
308
|
+
assertInteger(
|
|
309
|
+
"websocket.maxHttpBufferSize",
|
|
310
|
+
options.websocket?.maxHttpBufferSize,
|
|
311
|
+
1,
|
|
312
|
+
MAX_HTTP_BUFFER_BYTES
|
|
313
|
+
);
|
|
132
314
|
assertInteger("websocket.pingIntervalMs", options.websocket?.pingIntervalMs, 1, MAX_TIMER_MS);
|
|
133
315
|
assertInteger("websocket.pingTimeoutMs", options.websocket?.pingTimeoutMs, 1, MAX_TIMER_MS);
|
|
134
316
|
}
|
|
@@ -147,7 +329,7 @@ function validateReauthPolicy(options) {
|
|
|
147
329
|
if (onFailure !== void 0 && onFailure !== "disconnect" && onFailure !== "event") {
|
|
148
330
|
throw realtimeError(
|
|
149
331
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
150
|
-
`options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event',
|
|
332
|
+
`options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event', received ${describeReceived(onFailure)}`,
|
|
151
333
|
{ who: "BymaxRealtimeModule" }
|
|
152
334
|
);
|
|
153
335
|
}
|
|
@@ -164,36 +346,29 @@ function validateSseOptions(options) {
|
|
|
164
346
|
if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
|
|
165
347
|
throw realtimeError(
|
|
166
348
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
167
|
-
`options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms
|
|
168
|
-
{ who: "BymaxRealtimeModule" }
|
|
169
|
-
);
|
|
170
|
-
}
|
|
171
|
-
if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
|
|
172
|
-
throw realtimeError(
|
|
173
|
-
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
174
|
-
`options.sse.replayBufferSize must be >= 0`,
|
|
349
|
+
`options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(heartbeatMs)}`,
|
|
175
350
|
{ who: "BymaxRealtimeModule" }
|
|
176
351
|
);
|
|
177
352
|
}
|
|
353
|
+
assertInteger("sse.replayBufferSize", sse?.replayBufferSize, 0, MAX_REPLAY_EVENTS);
|
|
178
354
|
assertInteger("sse.replayTtlMs", sse?.replayTtlMs, 1, MAX_TIMER_MS);
|
|
179
355
|
assertInteger("sse.replayMaxIdleUsers", sse?.replayMaxIdleUsers, 1);
|
|
180
356
|
for (const name of ["maxQueuedBytes", "maxQueuedEvents", "stallHeartbeats"]) {
|
|
181
357
|
const value = sse?.[name];
|
|
182
|
-
if (value !== void 0 && !(typeof value === "number" && Number.
|
|
358
|
+
if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
|
|
183
359
|
throw realtimeError(
|
|
184
360
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
185
|
-
`options.sse.${name} must be an integer >= 0 (0 switches the bound off),
|
|
361
|
+
`options.sse.${name} must be an integer >= 0 (0 switches the bound off), received ${describeReceived(value)}`,
|
|
186
362
|
{ who: "BymaxRealtimeModule" }
|
|
187
363
|
);
|
|
188
364
|
}
|
|
189
365
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
366
|
+
assertInteger(
|
|
367
|
+
"sse.maxConnectionsPerUser",
|
|
368
|
+
sse?.maxConnectionsPerUser,
|
|
369
|
+
0,
|
|
370
|
+
MAX_PER_USER_CONNECTIONS
|
|
371
|
+
);
|
|
197
372
|
}
|
|
198
373
|
|
|
199
374
|
// src/server/utils/describe-error.ts
|
|
@@ -375,13 +550,40 @@ var ROOM_PREFIXES = {
|
|
|
375
550
|
RESOURCE: "resource"
|
|
376
551
|
};
|
|
377
552
|
|
|
378
|
-
// src/server/utils/
|
|
553
|
+
// src/server/utils/reserved-room.ts
|
|
379
554
|
var RESERVED_ROOM_PREFIXES = [
|
|
380
555
|
`${ROOM_PREFIXES.USER}:`,
|
|
381
556
|
`${ROOM_PREFIXES.TENANT}:`,
|
|
382
557
|
"connection:"
|
|
383
558
|
];
|
|
384
|
-
function
|
|
559
|
+
function reservedRoomPrefix(room) {
|
|
560
|
+
return RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
|
|
561
|
+
}
|
|
562
|
+
function describeShape(value) {
|
|
563
|
+
if (value === null) return "null";
|
|
564
|
+
return Array.isArray(value) ? "an array" : typeof value;
|
|
565
|
+
}
|
|
566
|
+
function requireRoomName(operation, roomId) {
|
|
567
|
+
if (typeof roomId === "string" && roomId.length > 0) return;
|
|
568
|
+
throw realtimeError(
|
|
569
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
570
|
+
`${operation}: \`roomId\` must be a non-empty string, got ${describeShape(roomId)}`,
|
|
571
|
+
{ who: "RealtimeService" }
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
function refuseReservedRoom(operation, roomId) {
|
|
575
|
+
requireRoomName(operation, roomId);
|
|
576
|
+
const prefix = reservedRoomPrefix(roomId);
|
|
577
|
+
if (prefix === void 0) return;
|
|
578
|
+
throw realtimeError(
|
|
579
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
580
|
+
`${operation}: \`roomId\` starts with the reserved prefix "${prefix}", which the library composes itself`,
|
|
581
|
+
{ who: "RealtimeService" }
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// src/server/utils/admit-rooms.ts
|
|
586
|
+
function refuse2(detail) {
|
|
385
587
|
throw realtimeError(
|
|
386
588
|
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
387
589
|
`the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
|
|
@@ -390,11 +592,11 @@ function refuse(detail) {
|
|
|
390
592
|
function admitRooms(auth) {
|
|
391
593
|
const { rooms } = auth;
|
|
392
594
|
if (rooms === void 0) return auth;
|
|
393
|
-
if (!Array.isArray(rooms))
|
|
595
|
+
if (!Array.isArray(rooms)) refuse2("`rooms` is not an array");
|
|
394
596
|
const admitted = [];
|
|
395
597
|
for (const room of rooms) {
|
|
396
598
|
if (admitted.length === ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
|
|
397
|
-
|
|
599
|
+
refuse2(
|
|
398
600
|
`more than ${ADMISSION_ROOM_LIMITS.MAX_ROOMS} rooms: the limit is ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`
|
|
399
601
|
);
|
|
400
602
|
}
|
|
@@ -402,13 +604,13 @@ function admitRooms(auth) {
|
|
|
402
604
|
}
|
|
403
605
|
for (const room of admitted) {
|
|
404
606
|
if (typeof room !== "string" || room.trim().length === 0) {
|
|
405
|
-
|
|
607
|
+
refuse2("every room must be a non-blank string");
|
|
406
608
|
}
|
|
407
609
|
if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
|
|
408
|
-
|
|
610
|
+
refuse2(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
|
|
409
611
|
}
|
|
410
|
-
const reserved =
|
|
411
|
-
if (reserved !== void 0)
|
|
612
|
+
const reserved = reservedRoomPrefix(room);
|
|
613
|
+
if (reserved !== void 0) refuse2(`a room name starts with the reserved prefix "${reserved}"`);
|
|
412
614
|
}
|
|
413
615
|
return { ...auth, rooms: Object.freeze(admitted) };
|
|
414
616
|
}
|
|
@@ -776,7 +978,12 @@ function composeRoomId(prefix, ...parts) {
|
|
|
776
978
|
}
|
|
777
979
|
function unavailableError(code, who, what, cause) {
|
|
778
980
|
const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
|
|
779
|
-
|
|
981
|
+
const error = Object.assign(new common.ServiceUnavailableException(), { code });
|
|
982
|
+
Object.defineProperties(error, {
|
|
983
|
+
message: { value: message, enumerable: false, writable: true, configurable: true },
|
|
984
|
+
cause: { value: cause, enumerable: false, writable: true, configurable: true }
|
|
985
|
+
});
|
|
986
|
+
return error;
|
|
780
987
|
}
|
|
781
988
|
exports.InMemoryPubSub = class InMemoryPubSub {
|
|
782
989
|
handlers = /* @__PURE__ */ new Set();
|
|
@@ -876,7 +1083,7 @@ exports.HeartbeatService = class HeartbeatService {
|
|
|
876
1083
|
if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
|
|
877
1084
|
throw realtimeError(
|
|
878
1085
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
879
|
-
`heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms
|
|
1086
|
+
`heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(intervalMs)}`
|
|
880
1087
|
);
|
|
881
1088
|
}
|
|
882
1089
|
this.stop(connectionId);
|
|
@@ -1186,6 +1393,7 @@ exports.SseTransport = class SseTransport {
|
|
|
1186
1393
|
await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
|
|
1187
1394
|
}
|
|
1188
1395
|
async emitToRoom(roomId, event, data) {
|
|
1396
|
+
requireRoomName("emitToRoom", roomId);
|
|
1189
1397
|
const id = this.idGen.next();
|
|
1190
1398
|
this.emitToRoomLocal(roomId, event, data, id);
|
|
1191
1399
|
await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
|
|
@@ -1196,10 +1404,12 @@ exports.SseTransport = class SseTransport {
|
|
|
1196
1404
|
await this.publish({ op: "broadcast", args: { event, data, id } });
|
|
1197
1405
|
}
|
|
1198
1406
|
async joinRoom(connectionId, roomId) {
|
|
1407
|
+
refuseReservedRoom("joinRoom", roomId);
|
|
1199
1408
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
1200
1409
|
this.rooms.join(connectionId, roomId);
|
|
1201
1410
|
}
|
|
1202
1411
|
async leaveRoom(connectionId, roomId) {
|
|
1412
|
+
refuseReservedRoom("leaveRoom", roomId);
|
|
1203
1413
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
1204
1414
|
this.rooms.leave(connectionId, roomId);
|
|
1205
1415
|
}
|
|
@@ -1642,7 +1852,10 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1642
1852
|
}
|
|
1643
1853
|
const record = this.transport.getConnection(connectionId);
|
|
1644
1854
|
if (record) {
|
|
1645
|
-
this.fireHook(
|
|
1855
|
+
this.fireHook(
|
|
1856
|
+
() => this.hooks?.onConnect?.(buildMeta(record)),
|
|
1857
|
+
this.options.onConnectFailure === "close" ? () => subscriber.complete() : void 0
|
|
1858
|
+
);
|
|
1646
1859
|
}
|
|
1647
1860
|
const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
1648
1861
|
this.heartbeat.start(
|
|
@@ -1652,9 +1865,11 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1652
1865
|
() => this.transport.checkStall(connectionId)
|
|
1653
1866
|
);
|
|
1654
1867
|
}
|
|
1655
|
-
fireHook(invoke) {
|
|
1868
|
+
fireHook(invoke, onFailure) {
|
|
1656
1869
|
void runHook(invoke).then((failed) => {
|
|
1657
|
-
if (failed)
|
|
1870
|
+
if (!failed) return;
|
|
1871
|
+
this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
|
|
1872
|
+
onFailure?.();
|
|
1658
1873
|
});
|
|
1659
1874
|
}
|
|
1660
1875
|
};
|
|
@@ -1733,16 +1948,19 @@ exports.RealtimeService = class RealtimeService {
|
|
|
1733
1948
|
emitToTenant(tenantId, event, data) {
|
|
1734
1949
|
return this.transport.emitToTenant(tenantId, event, data);
|
|
1735
1950
|
}
|
|
1736
|
-
emitToRoom(roomId, event, data) {
|
|
1951
|
+
async emitToRoom(roomId, event, data) {
|
|
1952
|
+
requireRoomName("emitToRoom", roomId);
|
|
1737
1953
|
return this.transport.emitToRoom(roomId, event, data);
|
|
1738
1954
|
}
|
|
1739
1955
|
broadcast(event, data) {
|
|
1740
1956
|
return this.transport.broadcast(event, data);
|
|
1741
1957
|
}
|
|
1742
|
-
joinRoom(connectionId, roomId) {
|
|
1958
|
+
async joinRoom(connectionId, roomId) {
|
|
1959
|
+
refuseReservedRoom("joinRoom", roomId);
|
|
1743
1960
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1744
1961
|
}
|
|
1745
|
-
leaveRoom(connectionId, roomId) {
|
|
1962
|
+
async leaveRoom(connectionId, roomId) {
|
|
1963
|
+
refuseReservedRoom("leaveRoom", roomId);
|
|
1746
1964
|
return this.transport.leaveRoom(connectionId, roomId);
|
|
1747
1965
|
}
|
|
1748
1966
|
disconnect(connectionId, reason) {
|
|
@@ -1997,7 +2215,8 @@ function buildCommonProviders(resolved, instanceId) {
|
|
|
1997
2215
|
...SHARED_SERVICES
|
|
1998
2216
|
];
|
|
1999
2217
|
}
|
|
2000
|
-
function composeForRoot(moduleClass, wiring, logger,
|
|
2218
|
+
function composeForRoot(moduleClass, wiring, logger, raw) {
|
|
2219
|
+
const options = dropUnset(raw);
|
|
2001
2220
|
validateOptions(options);
|
|
2002
2221
|
assertModeSupported(wiring, options.transport, moduleClass.name);
|
|
2003
2222
|
const resolved = applyDefaults(options);
|
|
@@ -2016,7 +2235,7 @@ function assertSseEndpointApplies(asyncOptions, moduleName) {
|
|
|
2016
2235
|
if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
|
|
2017
2236
|
throw realtimeError(
|
|
2018
2237
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2019
|
-
`sseEndpoint
|
|
2238
|
+
`sseEndpoint was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
|
|
2020
2239
|
{ who: moduleName }
|
|
2021
2240
|
);
|
|
2022
2241
|
}
|
|
@@ -2024,7 +2243,7 @@ function bindSseEndpoint(resolved, declared, bound, moduleName) {
|
|
|
2024
2243
|
if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
|
|
2025
2244
|
throw realtimeError(
|
|
2026
2245
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2027
|
-
`the factory resolved sse.endpoint
|
|
2246
|
+
`the factory resolved an sse.endpoint that differs from the SSE route forRootAsync bound \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
|
|
2028
2247
|
{ who: moduleName }
|
|
2029
2248
|
);
|
|
2030
2249
|
}
|
|
@@ -2034,39 +2253,68 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
|
|
|
2034
2253
|
if (!raw) {
|
|
2035
2254
|
throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
|
|
2036
2255
|
}
|
|
2037
|
-
|
|
2038
|
-
|
|
2256
|
+
const options = dropUnset(raw);
|
|
2257
|
+
validateOptions(options);
|
|
2258
|
+
if (options.transport !== declaredMode) {
|
|
2039
2259
|
throw realtimeError(
|
|
2040
2260
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2041
|
-
`forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${
|
|
2261
|
+
`forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${options.transport}'`,
|
|
2042
2262
|
{ who: moduleName }
|
|
2043
2263
|
);
|
|
2044
2264
|
}
|
|
2045
|
-
const resolved = applyDefaults(
|
|
2265
|
+
const resolved = applyDefaults(options);
|
|
2046
2266
|
logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
|
|
2047
|
-
return resolved;
|
|
2267
|
+
return { resolved, declaredEndpoint: options.sse?.endpoint };
|
|
2048
2268
|
}
|
|
2049
|
-
function
|
|
2050
|
-
const moduleName = moduleClass.name;
|
|
2269
|
+
function assertOneFactoryPattern(asyncOptions, moduleName) {
|
|
2051
2270
|
const patterns = [
|
|
2052
2271
|
asyncOptions.useFactory,
|
|
2053
2272
|
asyncOptions.useClass,
|
|
2054
2273
|
asyncOptions.useExisting
|
|
2055
2274
|
].filter((pattern) => pattern !== void 0);
|
|
2056
|
-
if (patterns.length
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2275
|
+
if (patterns.length === 1) return;
|
|
2276
|
+
throw realtimeError(
|
|
2277
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2278
|
+
`forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
|
|
2279
|
+
{ who: moduleName }
|
|
2280
|
+
);
|
|
2281
|
+
}
|
|
2282
|
+
function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
|
|
2283
|
+
if (asyncOptions.useFactory) {
|
|
2284
|
+
return {
|
|
2285
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
2286
|
+
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
2287
|
+
inject: [...asyncOptions.inject ?? []]
|
|
2288
|
+
};
|
|
2062
2289
|
}
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2290
|
+
return {
|
|
2291
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
2292
|
+
useFactory: async (factory) => resolve(
|
|
2293
|
+
await factory.createRealtimeOptions(),
|
|
2294
|
+
"createRealtimeOptions"
|
|
2295
|
+
),
|
|
2296
|
+
inject: [asyncOptions.useExisting ?? factoryToken]
|
|
2297
|
+
};
|
|
2298
|
+
}
|
|
2299
|
+
function fromOptions(token, read) {
|
|
2300
|
+
return { provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] };
|
|
2301
|
+
}
|
|
2302
|
+
function buildOptionDerivedProviders(logger, instanceId) {
|
|
2303
|
+
return [
|
|
2304
|
+
fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
|
|
2305
|
+
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
2306
|
+
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
2307
|
+
return opts.pubsub ?? new exports.InMemoryPubSub();
|
|
2308
|
+
}),
|
|
2309
|
+
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
2310
|
+
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
2311
|
+
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
2312
|
+
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence)
|
|
2313
|
+
];
|
|
2314
|
+
}
|
|
2315
|
+
function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
|
|
2316
|
+
return (raw, source) => {
|
|
2317
|
+
const { resolved, declaredEndpoint } = resolveAsyncOptions(
|
|
2070
2318
|
raw,
|
|
2071
2319
|
asyncOptions.transport,
|
|
2072
2320
|
instanceId,
|
|
@@ -2075,22 +2323,19 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
2075
2323
|
moduleName
|
|
2076
2324
|
);
|
|
2077
2325
|
if (asyncOptions.transport === "websocket") return resolved;
|
|
2078
|
-
return bindSseEndpoint(resolved,
|
|
2079
|
-
};
|
|
2080
|
-
const resolvedOptionsProvider = asyncOptions.useFactory ? {
|
|
2081
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
2082
|
-
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
2083
|
-
inject: [...asyncOptions.inject ?? []]
|
|
2084
|
-
} : {
|
|
2085
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
2086
|
-
useFactory: async (factory) => resolve(
|
|
2087
|
-
await factory.createRealtimeOptions(),
|
|
2088
|
-
"createRealtimeOptions"
|
|
2089
|
-
),
|
|
2090
|
-
inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
|
|
2326
|
+
return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
|
|
2091
2327
|
};
|
|
2328
|
+
}
|
|
2329
|
+
function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
2330
|
+
const moduleName = moduleClass.name;
|
|
2331
|
+
assertOneFactoryPattern(asyncOptions, moduleName);
|
|
2332
|
+
assertModeSupported(wiring, asyncOptions.transport, moduleName);
|
|
2333
|
+
assertSseEndpointApplies(asyncOptions, moduleName);
|
|
2334
|
+
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
2335
|
+
const instanceId = crypto.randomUUID();
|
|
2336
|
+
const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
|
|
2337
|
+
const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
|
|
2092
2338
|
const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
|
|
2093
|
-
const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
|
|
2094
2339
|
const { providers: transportProviders, controllers } = wiring.buildAsync({
|
|
2095
2340
|
mode: asyncOptions.transport,
|
|
2096
2341
|
sseEndpoint: boundSseEndpoint
|
|
@@ -2101,16 +2346,8 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
2101
2346
|
controllers,
|
|
2102
2347
|
providers: [
|
|
2103
2348
|
...factoryClassProvider,
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
2107
|
-
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
2108
|
-
return opts.pubsub ?? new exports.InMemoryPubSub();
|
|
2109
|
-
}),
|
|
2110
|
-
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
2111
|
-
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
2112
|
-
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
2113
|
-
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
|
|
2349
|
+
buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
|
|
2350
|
+
...buildOptionDerivedProviders(logger, instanceId),
|
|
2114
2351
|
...SHARED_SERVICES,
|
|
2115
2352
|
...transportProviders,
|
|
2116
2353
|
...asyncOptions.extraProviders ?? []
|
|
@@ -2509,6 +2746,18 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2509
2746
|
};
|
|
2510
2747
|
|
|
2511
2748
|
// src/server/offline-queue/redis-offline-queue.ts
|
|
2749
|
+
var MAX_PER_USER_CEILING = 1e5;
|
|
2750
|
+
var TTL_SECONDS_CEILING = 2147483647;
|
|
2751
|
+
function requireInteger(name, value, least, most) {
|
|
2752
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= least && value <= most) {
|
|
2753
|
+
return value;
|
|
2754
|
+
}
|
|
2755
|
+
throw realtimeError(
|
|
2756
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2757
|
+
`options.${name} must be an integer >= ${least} and <= ${most}, received ${describeReceived(value)}`,
|
|
2758
|
+
{ who: "RedisOfflineQueue" }
|
|
2759
|
+
);
|
|
2760
|
+
}
|
|
2512
2761
|
var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
2513
2762
|
#client;
|
|
2514
2763
|
maxPerUser;
|
|
@@ -2517,8 +2766,18 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2517
2766
|
static COUNTER_PAD = 6;
|
|
2518
2767
|
constructor(options) {
|
|
2519
2768
|
this.#client = options.client;
|
|
2520
|
-
this.maxPerUser =
|
|
2521
|
-
|
|
2769
|
+
this.maxPerUser = requireInteger(
|
|
2770
|
+
"maxPerUser",
|
|
2771
|
+
options.maxPerUser ?? 500,
|
|
2772
|
+
1,
|
|
2773
|
+
MAX_PER_USER_CEILING
|
|
2774
|
+
);
|
|
2775
|
+
this.ttlSeconds = requireInteger(
|
|
2776
|
+
"ttlSeconds",
|
|
2777
|
+
options.ttlSeconds ?? 3600,
|
|
2778
|
+
1,
|
|
2779
|
+
TTL_SECONDS_CEILING
|
|
2780
|
+
);
|
|
2522
2781
|
}
|
|
2523
2782
|
key(userId) {
|
|
2524
2783
|
return `bymax:oq:${userId}`;
|
|
@@ -2599,7 +2858,9 @@ exports.describeError = describeError;
|
|
|
2599
2858
|
exports.parseCookieHeader = parseCookieHeader;
|
|
2600
2859
|
exports.quitWithin = quitWithin;
|
|
2601
2860
|
exports.realtimeError = realtimeError;
|
|
2861
|
+
exports.refuseReservedRoom = refuseReservedRoom;
|
|
2602
2862
|
exports.reportDeliveryFailure = reportDeliveryFailure;
|
|
2863
|
+
exports.requireRoomName = requireRoomName;
|
|
2603
2864
|
exports.resolveAuthTenant = resolveAuthTenant;
|
|
2604
2865
|
exports.runHook = runHook;
|
|
2605
2866
|
exports.sseWiring = sseWiring;
|