@colyseus/core 0.16.24 → 0.17.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.
Files changed (258) hide show
  1. package/build/Debug.js +16 -4
  2. package/build/Debug.js.map +2 -2
  3. package/build/Debug.mjs +11 -1
  4. package/build/Debug.mjs.map +2 -2
  5. package/build/IPC.js +5 -3
  6. package/build/IPC.js.map +2 -2
  7. package/build/IPC.mjs +1 -0
  8. package/build/IPC.mjs.map +2 -2
  9. package/build/Logger.js +1 -0
  10. package/build/Logger.js.map +1 -1
  11. package/build/MatchMaker.js +148 -84
  12. package/build/MatchMaker.js.map +3 -3
  13. package/build/MatchMaker.mjs +130 -70
  14. package/build/MatchMaker.mjs.map +3 -3
  15. package/build/Protocol.js +54 -41
  16. package/build/Protocol.js.map +3 -3
  17. package/build/Protocol.mjs +52 -41
  18. package/build/Protocol.mjs.map +3 -3
  19. package/build/Room.js +430 -195
  20. package/build/Room.js.map +3 -3
  21. package/build/Room.mjs +417 -175
  22. package/build/Room.mjs.map +3 -3
  23. package/build/Server.js +49 -108
  24. package/build/Server.js.map +3 -3
  25. package/build/Server.mjs +40 -102
  26. package/build/Server.mjs.map +3 -3
  27. package/build/Stats.js +2 -1
  28. package/build/Stats.js.map +2 -2
  29. package/build/Stats.mjs.map +1 -1
  30. package/build/Transport.js +29 -11
  31. package/build/Transport.js.map +3 -3
  32. package/build/Transport.mjs +15 -9
  33. package/build/Transport.mjs.map +3 -3
  34. package/build/errors/RoomExceptions.js +9 -5
  35. package/build/errors/RoomExceptions.js.map +2 -2
  36. package/build/errors/RoomExceptions.mjs +8 -5
  37. package/build/errors/RoomExceptions.mjs.map +2 -2
  38. package/build/errors/SeatReservationError.js +1 -0
  39. package/build/errors/SeatReservationError.js.map +1 -1
  40. package/build/errors/ServerError.js +2 -1
  41. package/build/errors/ServerError.js.map +2 -2
  42. package/build/errors/ServerError.mjs.map +1 -1
  43. package/build/index.js +60 -26
  44. package/build/index.js.map +2 -2
  45. package/build/index.mjs +33 -7
  46. package/build/index.mjs.map +2 -2
  47. package/build/matchmaker/Lobby.js +13 -3
  48. package/build/matchmaker/Lobby.js.map +2 -2
  49. package/build/matchmaker/Lobby.mjs +11 -2
  50. package/build/matchmaker/Lobby.mjs.map +2 -2
  51. package/build/matchmaker/LocalDriver/LocalDriver.js +94 -0
  52. package/build/matchmaker/LocalDriver/LocalDriver.js.map +7 -0
  53. package/build/matchmaker/LocalDriver/LocalDriver.mjs +71 -0
  54. package/build/matchmaker/LocalDriver/LocalDriver.mjs.map +7 -0
  55. package/build/matchmaker/LocalDriver/Query.js +111 -0
  56. package/build/matchmaker/LocalDriver/Query.js.map +7 -0
  57. package/build/matchmaker/LocalDriver/Query.mjs +88 -0
  58. package/build/matchmaker/LocalDriver/Query.mjs.map +7 -0
  59. package/build/matchmaker/RegisteredHandler.js +57 -7
  60. package/build/matchmaker/RegisteredHandler.js.map +2 -2
  61. package/build/matchmaker/RegisteredHandler.mjs +54 -5
  62. package/build/matchmaker/RegisteredHandler.mjs.map +2 -2
  63. package/build/matchmaker/controller.js +8 -8
  64. package/build/matchmaker/controller.js.map +2 -2
  65. package/build/matchmaker/controller.mjs +4 -5
  66. package/build/matchmaker/controller.mjs.map +2 -2
  67. package/build/matchmaker/driver/api.js +21 -2
  68. package/build/matchmaker/driver/api.js.map +2 -2
  69. package/build/matchmaker/driver/api.mjs +18 -1
  70. package/build/matchmaker/driver/api.mjs.map +2 -2
  71. package/build/matchmaker/driver/local/LocalDriver.js +36 -7
  72. package/build/matchmaker/driver/local/LocalDriver.js.map +2 -2
  73. package/build/matchmaker/driver/local/LocalDriver.mjs +33 -5
  74. package/build/matchmaker/driver/local/LocalDriver.mjs.map +2 -2
  75. package/build/matchmaker/driver/local/Query.js +51 -18
  76. package/build/matchmaker/driver/local/Query.js.map +2 -2
  77. package/build/matchmaker/driver/local/Query.mjs +50 -18
  78. package/build/matchmaker/driver/local/Query.mjs.map +2 -2
  79. package/build/matchmaker/driver.js +44 -0
  80. package/build/matchmaker/driver.js.map +7 -0
  81. package/build/matchmaker/driver.mjs +20 -0
  82. package/build/matchmaker/driver.mjs.map +7 -0
  83. package/build/matchmaker/routes.js +79 -0
  84. package/build/matchmaker/routes.js.map +7 -0
  85. package/build/matchmaker/routes.mjs +45 -0
  86. package/build/matchmaker/routes.mjs.map +7 -0
  87. package/build/presence/LocalPresence.js +13 -27
  88. package/build/presence/LocalPresence.js.map +3 -3
  89. package/build/presence/LocalPresence.mjs +11 -16
  90. package/build/presence/LocalPresence.mjs.map +2 -2
  91. package/build/presence/Presence.js +37 -0
  92. package/build/presence/Presence.js.map +2 -2
  93. package/build/presence/Presence.mjs +29 -0
  94. package/build/presence/Presence.mjs.map +3 -3
  95. package/build/rooms/LobbyRoom.js +5 -5
  96. package/build/rooms/LobbyRoom.js.map +2 -2
  97. package/build/rooms/LobbyRoom.mjs +1 -2
  98. package/build/rooms/LobbyRoom.mjs.map +2 -2
  99. package/build/rooms/RankedQueueRoom.js +224 -0
  100. package/build/rooms/RankedQueueRoom.js.map +7 -0
  101. package/build/rooms/RankedQueueRoom.mjs +201 -0
  102. package/build/rooms/RankedQueueRoom.mjs.map +7 -0
  103. package/build/rooms/RelayRoom.js +6 -6
  104. package/build/rooms/RelayRoom.js.map +2 -2
  105. package/build/rooms/RelayRoom.mjs +4 -5
  106. package/build/rooms/RelayRoom.mjs.map +2 -2
  107. package/build/rooms/createRoom.js +51 -0
  108. package/build/rooms/createRoom.js.map +7 -0
  109. package/build/rooms/createRoom.mjs +28 -0
  110. package/build/rooms/createRoom.mjs.map +7 -0
  111. package/build/router/default_routes.js +79 -0
  112. package/build/router/default_routes.js.map +7 -0
  113. package/build/router/default_routes.mjs +45 -0
  114. package/build/router/default_routes.mjs.map +7 -0
  115. package/build/router/index.js +55 -0
  116. package/build/router/index.js.map +7 -0
  117. package/build/router/index.mjs +30 -0
  118. package/build/router/index.mjs.map +7 -0
  119. package/build/serializer/NoneSerializer.js +1 -0
  120. package/build/serializer/NoneSerializer.js.map +2 -2
  121. package/build/serializer/NoneSerializer.mjs.map +2 -2
  122. package/build/serializer/SchemaSerializer.js +6 -7
  123. package/build/serializer/SchemaSerializer.js.map +2 -2
  124. package/build/serializer/SchemaSerializer.mjs +3 -5
  125. package/build/serializer/SchemaSerializer.mjs.map +2 -2
  126. package/build/serializer/SchemaSerializerDebug.js +29 -0
  127. package/build/serializer/SchemaSerializerDebug.js.map +3 -3
  128. package/build/serializer/SchemaSerializerDebug.mjs +7 -0
  129. package/build/serializer/SchemaSerializerDebug.mjs.map +3 -3
  130. package/build/serializer/Serializer.js +1 -0
  131. package/build/serializer/Serializer.js.map +2 -2
  132. package/build/{Debug.d.ts → src/Debug.d.ts} +2 -1
  133. package/build/{IPC.d.ts → src/IPC.d.ts} +2 -2
  134. package/build/{MatchMaker.d.ts → src/MatchMaker.d.ts} +58 -33
  135. package/build/src/Protocol.d.ts +53 -0
  136. package/build/src/Room.d.ts +497 -0
  137. package/build/{Server.d.ts → src/Server.d.ts} +23 -25
  138. package/build/{Transport.d.ts → src/Transport.d.ts} +65 -22
  139. package/build/{errors → src/errors}/RoomExceptions.d.ts +8 -7
  140. package/build/src/index.d.ts +27 -0
  141. package/build/src/matchmaker/Lobby.d.ts +4 -0
  142. package/build/src/matchmaker/LocalDriver/LocalDriver.d.ts +17 -0
  143. package/build/src/matchmaker/LocalDriver/Query.d.ts +12 -0
  144. package/build/src/matchmaker/RegisteredHandler.d.ts +81 -0
  145. package/build/{matchmaker → src/matchmaker}/controller.d.ts +5 -6
  146. package/build/src/matchmaker/driver/api.d.ts +145 -0
  147. package/build/src/matchmaker/driver/local/LocalDriver.d.ts +17 -0
  148. package/build/src/matchmaker/driver/local/Query.d.ts +12 -0
  149. package/build/src/matchmaker/driver.d.ts +145 -0
  150. package/build/src/matchmaker/routes.d.ts +92 -0
  151. package/build/{presence → src/presence}/LocalPresence.d.ts +1 -1
  152. package/build/{presence → src/presence}/Presence.d.ts +2 -0
  153. package/build/{rooms → src/rooms}/LobbyRoom.d.ts +4 -4
  154. package/build/src/rooms/RankedQueueRoom.d.ts +125 -0
  155. package/build/{rooms → src/rooms}/RelayRoom.d.ts +5 -4
  156. package/build/src/rooms/createRoom.d.ts +65 -0
  157. package/build/src/router/default_routes.d.ts +103 -0
  158. package/build/src/router/index.d.ts +68 -0
  159. package/build/{serializer → src/serializer}/NoneSerializer.d.ts +2 -2
  160. package/build/{serializer → src/serializer}/SchemaSerializer.d.ts +9 -9
  161. package/build/{serializer → src/serializer}/Serializer.d.ts +3 -3
  162. package/build/{utils → src/utils}/DevMode.d.ts +5 -4
  163. package/build/{utils → src/utils}/StandardSchema.d.ts +1 -1
  164. package/build/{utils → src/utils}/Utils.d.ts +15 -4
  165. package/build/utils/DevMode.js +54 -26
  166. package/build/utils/DevMode.js.map +3 -3
  167. package/build/utils/DevMode.mjs +44 -19
  168. package/build/utils/DevMode.mjs.map +2 -2
  169. package/build/utils/StandardSchema.js.map +1 -1
  170. package/build/utils/StandardSchema.mjs.map +1 -1
  171. package/build/utils/Utils.js +8 -15
  172. package/build/utils/Utils.js.map +3 -3
  173. package/build/utils/Utils.mjs +6 -4
  174. package/build/utils/Utils.mjs.map +2 -2
  175. package/package.json +21 -16
  176. package/src/Debug.ts +37 -0
  177. package/src/IPC.ts +124 -0
  178. package/src/Logger.ts +30 -0
  179. package/src/MatchMaker.ts +1119 -0
  180. package/src/Protocol.ts +160 -0
  181. package/src/Room.ts +1797 -0
  182. package/src/Server.ts +325 -0
  183. package/src/Stats.ts +107 -0
  184. package/src/Transport.ts +207 -0
  185. package/src/errors/RoomExceptions.ts +141 -0
  186. package/src/errors/SeatReservationError.ts +5 -0
  187. package/src/errors/ServerError.ts +17 -0
  188. package/src/index.ts +81 -0
  189. package/src/matchmaker/Lobby.ts +68 -0
  190. package/src/matchmaker/LocalDriver/LocalDriver.ts +92 -0
  191. package/src/matchmaker/LocalDriver/Query.ts +94 -0
  192. package/src/matchmaker/RegisteredHandler.ts +172 -0
  193. package/src/matchmaker/controller.ts +64 -0
  194. package/src/matchmaker/driver.ts +191 -0
  195. package/src/presence/LocalPresence.ts +331 -0
  196. package/src/presence/Presence.ts +263 -0
  197. package/src/rooms/LobbyRoom.ts +135 -0
  198. package/src/rooms/RankedQueueRoom.ts +425 -0
  199. package/src/rooms/RelayRoom.ts +90 -0
  200. package/src/router/default_routes.ts +58 -0
  201. package/src/router/index.ts +43 -0
  202. package/src/serializer/NoneSerializer.ts +16 -0
  203. package/src/serializer/SchemaSerializer.ts +194 -0
  204. package/src/serializer/SchemaSerializerDebug.ts +148 -0
  205. package/src/serializer/Serializer.ts +9 -0
  206. package/src/utils/DevMode.ts +133 -0
  207. package/src/utils/StandardSchema.ts +20 -0
  208. package/src/utils/Utils.ts +169 -0
  209. package/src/utils/nanoevents.ts +20 -0
  210. package/build/Protocol.d.ts +0 -37
  211. package/build/Room.d.ts +0 -265
  212. package/build/discovery/index.d.ts +0 -8
  213. package/build/discovery/index.js +0 -50
  214. package/build/discovery/index.js.map +0 -7
  215. package/build/discovery/index.mjs +0 -26
  216. package/build/discovery/index.mjs.map +0 -7
  217. package/build/index.d.ts +0 -24
  218. package/build/matchmaker/Lobby.d.ts +0 -4
  219. package/build/matchmaker/RegisteredHandler.d.ts +0 -19
  220. package/build/matchmaker/driver/Query.d.ts +0 -8
  221. package/build/matchmaker/driver/Query.js +0 -68
  222. package/build/matchmaker/driver/Query.js.map +0 -7
  223. package/build/matchmaker/driver/Query.mjs +0 -45
  224. package/build/matchmaker/driver/Query.mjs.map +0 -7
  225. package/build/matchmaker/driver/RoomData.d.ts +0 -19
  226. package/build/matchmaker/driver/RoomData.js +0 -79
  227. package/build/matchmaker/driver/RoomData.js.map +0 -7
  228. package/build/matchmaker/driver/RoomData.mjs +0 -56
  229. package/build/matchmaker/driver/RoomData.mjs.map +0 -7
  230. package/build/matchmaker/driver/api.d.ts +0 -104
  231. package/build/matchmaker/driver/index.d.ts +0 -13
  232. package/build/matchmaker/driver/index.js +0 -64
  233. package/build/matchmaker/driver/index.js.map +0 -7
  234. package/build/matchmaker/driver/index.mjs +0 -42
  235. package/build/matchmaker/driver/index.mjs.map +0 -7
  236. package/build/matchmaker/driver/interfaces.d.ts +0 -73
  237. package/build/matchmaker/driver/interfaces.js +0 -15
  238. package/build/matchmaker/driver/interfaces.js.map +0 -7
  239. package/build/matchmaker/driver/interfaces.mjs +0 -0
  240. package/build/matchmaker/driver/interfaces.mjs.map +0 -7
  241. package/build/matchmaker/driver/local/LocalDriver.d.ts +0 -13
  242. package/build/matchmaker/driver/local/Query.d.ts +0 -9
  243. package/build/matchmaker/driver/local/RoomData.d.ts +0 -19
  244. package/build/matchmaker/driver/local/RoomData.js +0 -79
  245. package/build/matchmaker/driver/local/RoomData.js.map +0 -7
  246. package/build/matchmaker/driver/local/RoomData.mjs +0 -57
  247. package/build/matchmaker/driver/local/RoomData.mjs.map +0 -7
  248. package/build/utils/types.d.ts +0 -1
  249. package/build/utils/types.js +0 -15
  250. package/build/utils/types.js.map +0 -7
  251. package/build/utils/types.mjs +0 -0
  252. package/build/utils/types.mjs.map +0 -7
  253. /package/build/{Logger.d.ts → src/Logger.d.ts} +0 -0
  254. /package/build/{Stats.d.ts → src/Stats.d.ts} +0 -0
  255. /package/build/{errors → src/errors}/SeatReservationError.d.ts +0 -0
  256. /package/build/{errors → src/errors}/ServerError.d.ts +0 -0
  257. /package/build/{serializer → src/serializer}/SchemaSerializerDebug.d.ts +0 -0
  258. /package/build/{utils → src/utils}/nanoevents.d.ts +0 -0
@@ -0,0 +1,497 @@
1
+ import { ClockTimer as Clock } from '@colyseus/timer';
2
+ import type { Presence } from './presence/Presence.ts';
3
+ import type { Serializer } from './serializer/Serializer.ts';
4
+ import { type Type, Deferred } from './utils/Utils.ts';
5
+ import { type AuthContext, type Client, ClientArray, type ISendOptions, type MessageArgs } from './Transport.ts';
6
+ import { type RoomMethodName, type RoomException } from './errors/RoomExceptions.ts';
7
+ import { type StandardSchemaV1 } from './utils/StandardSchema.ts';
8
+ export declare const DEFAULT_SEAT_RESERVATION_TIME: number;
9
+ export type SimulationCallback = (deltaTime: number) => void;
10
+ export interface RoomOptions {
11
+ state?: object;
12
+ metadata?: any;
13
+ client?: Client;
14
+ }
15
+ export type ExtractRoomState<T> = T extends {
16
+ state?: infer S extends object;
17
+ } ? S : any;
18
+ export type ExtractRoomMetadata<T> = T extends {
19
+ metadata?: infer M;
20
+ } ? M : any;
21
+ export type ExtractRoomClient<T> = T extends {
22
+ client?: infer C extends Client;
23
+ } ? C : Client;
24
+ export interface IBroadcastOptions extends ISendOptions {
25
+ except?: Client | Client[];
26
+ }
27
+ /**
28
+ * Message handler with automatic type inference from format schema.
29
+ * When a format is provided, the message type is automatically inferred from the schema.
30
+ */
31
+ export type MessageHandlerWithFormat<T extends StandardSchemaV1 = any, This = any> = {
32
+ format: T;
33
+ handler: (this: This, client: Client, message: StandardSchemaV1.InferOutput<T>) => void;
34
+ };
35
+ export type MessageHandler<This = any> = ((this: This, client: Client, message: any) => void) | MessageHandlerWithFormat<any, This>;
36
+ /**
37
+ * Extract the message payload type from a message handler.
38
+ * Works with both function handlers and format handlers.
39
+ *
40
+ * (Imported from @colyseus/sdk, not used in the server-side)
41
+ */
42
+ export type ExtractMessageType<T> = T extends {
43
+ format: infer Format extends StandardSchemaV1;
44
+ handler: any;
45
+ } ? StandardSchemaV1.InferOutput<Format> : T extends (this: any, client: any, message: infer Message) => void ? Message : any;
46
+ /**
47
+ * A map of message types to message handlers.
48
+ */
49
+ export type Messages<This extends Room> = Record<string, MessageHandler<This>>;
50
+ /**
51
+ * Helper function to create a validated message handler with automatic type inference.
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * messages = {
56
+ * move: validate(z.object({ x: z.number(), y: z.number() }), (client, message) => {
57
+ * // message.x and message.y are automatically typed as numbers
58
+ * console.log(message.x, message.y);
59
+ * })
60
+ * }
61
+ * ```
62
+ */
63
+ export declare function validate<T extends StandardSchemaV1, This = any>(format: T, handler: (this: This, client: Client, message: StandardSchemaV1.InferOutput<T>) => void): MessageHandlerWithFormat<T, This>;
64
+ export declare const RoomInternalState: {
65
+ readonly CREATING: 0;
66
+ readonly CREATED: 1;
67
+ readonly DISPOSING: 2;
68
+ };
69
+ export type RoomInternalState = (typeof RoomInternalState)[keyof typeof RoomInternalState];
70
+ export type OnCreateOptions<T extends Type<Room>> = Parameters<NonNullable<InstanceType<T>['onCreate']>>[0];
71
+ /**
72
+ * A Room class is meant to implement a game session, and/or serve as the communication channel
73
+ * between a group of clients.
74
+ *
75
+ * - Rooms are created on demand during matchmaking by default
76
+ * - Room classes must be exposed using `.define()`
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * class MyRoom extends Room<{
81
+ * state: MyState,
82
+ * metadata: { difficulty: string },
83
+ * client: MyClient
84
+ * }> {
85
+ * // ...
86
+ * }
87
+ * ```
88
+ */
89
+ export declare class Room<T extends RoomOptions = RoomOptions> {
90
+ #private;
91
+ '~client': ExtractRoomClient<T>;
92
+ '~state': ExtractRoomState<T>;
93
+ '~metadata': ExtractRoomMetadata<T>;
94
+ /**
95
+ * This property will change on these situations:
96
+ * - The maximum number of allowed clients has been reached (`maxClients`)
97
+ * - You manually locked, or unlocked the room using lock() or `unlock()`.
98
+ *
99
+ * @readonly
100
+ */
101
+ get locked(): boolean;
102
+ /**
103
+ * Get the room's matchmaking metadata.
104
+ */
105
+ get metadata(): ExtractRoomMetadata<T>;
106
+ /**
107
+ * Set the room's matchmaking metadata.
108
+ *
109
+ * **Note**: This setter does NOT automatically persist. Use `setMatchmaking()` for automatic persistence.
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * class MyRoom extends Room<{ metadata: { difficulty: string; rating: number } }> {
114
+ * async onCreate() {
115
+ * this.metadata = { difficulty: "hard", rating: 1500 };
116
+ * }
117
+ * }
118
+ * ```
119
+ */
120
+ set metadata(meta: ExtractRoomMetadata<T>);
121
+ /**
122
+ * The room listing cache for matchmaking.
123
+ * @internal
124
+ */
125
+ private _listing;
126
+ /**
127
+ * Timing events tied to the room instance.
128
+ * Intervals and timeouts are cleared when the room is disposed.
129
+ */
130
+ clock: Clock;
131
+ /**
132
+ * Maximum number of clients allowed to connect into the room. When room reaches this limit,
133
+ * it is locked automatically. Unless the room was explicitly locked by you via `lock()` method,
134
+ * the room will be unlocked as soon as a client disconnects from it.
135
+ */
136
+ maxClients: number;
137
+ /**
138
+ * Automatically dispose the room when last client disconnects.
139
+ *
140
+ * @default true
141
+ */
142
+ autoDispose: boolean;
143
+ /**
144
+ * Frequency to send the room state to connected clients, in milliseconds.
145
+ *
146
+ * @default 50ms (20fps)
147
+ */
148
+ patchRate: number | null;
149
+ /**
150
+ * Maximum number of messages a client can send to the server per second.
151
+ * If a client sends more messages than this, it will be disconnected.
152
+ *
153
+ * @default 60
154
+ */
155
+ maxMessagesPerSecond: number;
156
+ /**
157
+ * The state instance you provided to `setState()`.
158
+ */
159
+ state: ExtractRoomState<T>;
160
+ /**
161
+ * The presence instance. Check Presence API for more details.
162
+ *
163
+ * @see [Presence API](https://docs.colyseus.io/server/presence)
164
+ */
165
+ presence: Presence;
166
+ /**
167
+ * The array of connected clients.
168
+ *
169
+ * @see [Client instance](https://docs.colyseus.io/room#client)
170
+ */
171
+ clients: ClientArray<ExtractRoomClient<T>>;
172
+ /**
173
+ * Set the number of seconds a room can wait for a client to effectively join the room.
174
+ * You should consider how long your `onAuth()` will have to wait for setting a different seat reservation time.
175
+ * The default value is 15 seconds. You may set the `COLYSEUS_SEAT_RESERVATION_TIME`
176
+ * environment variable if you'd like to change the seat reservation time globally.
177
+ *
178
+ * @default 15 seconds
179
+ */
180
+ seatReservationTimeout: number;
181
+ private _events;
182
+ private _reservedSeats;
183
+ private _reservedSeatTimeouts;
184
+ private _reconnections;
185
+ messages?: Messages<any>;
186
+ private onMessageEvents;
187
+ private onMessageValidators;
188
+ private onMessageFallbacks;
189
+ private _serializer;
190
+ private _afterNextPatchQueue;
191
+ private _simulationInterval;
192
+ private _internalState;
193
+ private _lockedExplicitly;
194
+ private _autoDisposeTimeout;
195
+ constructor();
196
+ /**
197
+ * This method is called by the MatchMaker before onCreate()
198
+ * @internal
199
+ */
200
+ private __init;
201
+ /**
202
+ * The name of the room you provided as first argument for `gameServer.define()`.
203
+ *
204
+ * @returns roomName string
205
+ */
206
+ get roomName(): string;
207
+ /**
208
+ * Setting the name of the room. Overwriting this property is restricted.
209
+ *
210
+ * @param roomName
211
+ */
212
+ set roomName(roomName: string);
213
+ /**
214
+ * A unique, auto-generated, 9-character-long id of the room.
215
+ * You may replace `this.roomId` during `onCreate()`.
216
+ *
217
+ * @returns roomId string
218
+ */
219
+ get roomId(): string;
220
+ /**
221
+ * Setting the roomId, is restricted in room lifetime except upon room creation.
222
+ *
223
+ * @param roomId
224
+ * @returns roomId string
225
+ */
226
+ set roomId(roomId: string);
227
+ /**
228
+ * This method is called before the latest version of the room's state is broadcasted to all clients.
229
+ */
230
+ onBeforePatch?(state: ExtractRoomState<T>): void | Promise<any>;
231
+ /**
232
+ * This method is called when the room is created.
233
+ * @param options - The options passed to the room when it is created.
234
+ */
235
+ onCreate?(options: any): void | Promise<any>;
236
+ /**
237
+ * This method is called when a client joins the room.
238
+ * @param client - The client that joined the room.
239
+ * @param options - The options passed to the client when it joined the room.
240
+ */
241
+ onJoin?(client: ExtractRoomClient<T>, options?: any): void | Promise<any>;
242
+ /**
243
+ * This method is called when a client leaves the room without consent.
244
+ * You may allow the client to reconnect by calling `allowReconnection` within this method.
245
+ *
246
+ * @param client - The client that was dropped from the room.
247
+ * @param code - The close code of the leave event.
248
+ */
249
+ onDrop?(client: ExtractRoomClient<T>, code?: number): void | Promise<any>;
250
+ /**
251
+ * This method is called when a client reconnects to the room.
252
+ * @param client - The client that reconnected to the room.
253
+ */
254
+ onReconnect?(client: ExtractRoomClient<T>): void | Promise<any>;
255
+ /**
256
+ * This method is called when a client effectively leaves the room.
257
+ * @param client - The client that left the room.
258
+ * @param code - The close code of the leave event.
259
+ */
260
+ onLeave?(client: ExtractRoomClient<T>, code?: number): void | Promise<any>;
261
+ /**
262
+ * This method is called when the room is disposed.
263
+ */
264
+ onDispose?(): void | Promise<any>;
265
+ /**
266
+ * Define a custom exception handler.
267
+ * If defined, all lifecycle hooks will be wrapped by try/catch, and the exception will be forwarded to this method.
268
+ *
269
+ * These methods will be wrapped by try/catch:
270
+ * - `onMessage`
271
+ * - `onAuth` / `onJoin` / `onLeave` / `onCreate` / `onDispose`
272
+ * - `clock.setTimeout` / `clock.setInterval`
273
+ * - `setSimulationInterval`
274
+ *
275
+ * (Experimental: this feature is subject to change in the future - we're currently getting feedback to improve it)
276
+ */
277
+ onUncaughtException?(error: RoomException, methodName: RoomMethodName): void;
278
+ /**
279
+ * This method is called before onJoin() - this is where you should authenticate the client
280
+ * @param client - The client that is authenticating.
281
+ * @param options - The options passed to the client when it is authenticating.
282
+ * @param context - The authentication context, including the token and the client's IP address.
283
+ * @returns The authentication result.
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * return {
288
+ * userId: 123,
289
+ * username: "John Doe",
290
+ * email: "john.doe@example.com",
291
+ * };
292
+ * ```
293
+ */
294
+ onAuth(client: Client, options: any, context: AuthContext): any | Promise<any>;
295
+ static onAuth(token: string, options: any, context: AuthContext): Promise<unknown>;
296
+ /**
297
+ * This method is called during graceful shutdown of the server process
298
+ * You may override this method to dispose the room in your own way.
299
+ *
300
+ * Once process reaches room count of 0, the room process will be terminated.
301
+ */
302
+ onBeforeShutdown(): void;
303
+ /**
304
+ * devMode: When `devMode` is enabled, `onCacheRoom` method is called during
305
+ * graceful shutdown.
306
+ *
307
+ * Implement this method to return custom data to be cached. `onRestoreRoom`
308
+ * will be called with the data returned by `onCacheRoom`
309
+ */
310
+ onCacheRoom?(): any;
311
+ /**
312
+ * devMode: When `devMode` is enabled, `onRestoreRoom` method is called during
313
+ * process startup, with the data returned by the `onCacheRoom` method.
314
+ */
315
+ onRestoreRoom?(cached?: any): void;
316
+ /**
317
+ * Returns whether the sum of connected clients and reserved seats exceeds maximum number of clients.
318
+ *
319
+ * @returns boolean
320
+ */
321
+ hasReachedMaxClients(): boolean;
322
+ /**
323
+ * @deprecated Use `seatReservationTimeout=` instead.
324
+ */
325
+ setSeatReservationTime(seconds: number): this;
326
+ hasReservedSeat(sessionId: string, reconnectionToken?: string): boolean;
327
+ checkReconnectionToken(reconnectionToken: string): string;
328
+ /**
329
+ * (Optional) Set a simulation interval that can change the state of the game.
330
+ * The simulation interval is your game loop.
331
+ *
332
+ * @default 16.6ms (60fps)
333
+ *
334
+ * @param onTickCallback - You can implement your physics or world updates here!
335
+ * This is a good place to update the room state.
336
+ * @param delay - Interval delay on executing `onTickCallback` in milliseconds.
337
+ */
338
+ setSimulationInterval(onTickCallback?: SimulationCallback, delay?: number): void;
339
+ /**
340
+ * @deprecated Use `.patchRate=` instead.
341
+ */
342
+ setPatchRate(milliseconds: number | null): void;
343
+ /**
344
+ * @deprecated Use `.state =` instead.
345
+ */
346
+ setState(newState: ExtractRoomState<T>): void;
347
+ setSerializer(serializer: Serializer<ExtractRoomState<T>>): void;
348
+ setMetadata(meta: Partial<ExtractRoomMetadata<T>>, persist?: boolean): Promise<void>;
349
+ setPrivate(bool?: boolean, persist?: boolean): Promise<void>;
350
+ /**
351
+ * Update multiple matchmaking/listing properties at once with a single persist operation.
352
+ * This is the recommended way to update room listing properties.
353
+ *
354
+ * @param updates - Object containing the properties to update
355
+ *
356
+ * @example
357
+ * ```typescript
358
+ * // Update multiple properties at once
359
+ * await this.setMatchmaking({
360
+ * metadata: { difficulty: "hard", rating: 1500 },
361
+ * private: true,
362
+ * locked: true,
363
+ * maxClients: 10
364
+ * });
365
+ * ```
366
+ *
367
+ * @example
368
+ * ```typescript
369
+ * // Update only metadata
370
+ * await this.setMatchmaking({
371
+ * metadata: { status: "in_progress" }
372
+ * });
373
+ * ```
374
+ *
375
+ * @example
376
+ * ```typescript
377
+ * // Partial metadata update (merges with existing)
378
+ * await this.setMatchmaking({
379
+ * metadata: { ...this.metadata, round: this.metadata.round + 1 }
380
+ * });
381
+ * ```
382
+ */
383
+ setMatchmaking(updates: {
384
+ metadata?: ExtractRoomMetadata<T>;
385
+ private?: boolean;
386
+ locked?: boolean;
387
+ maxClients?: number;
388
+ unlisted?: boolean;
389
+ [key: string]: any;
390
+ }): Promise<void>;
391
+ /**
392
+ * Lock the room. This prevents new clients from joining this room.
393
+ */
394
+ lock(): Promise<void>;
395
+ /**
396
+ * Unlock the room. This allows new clients to join this room, if maxClients is not reached.
397
+ */
398
+ unlock(): Promise<void>;
399
+ /**
400
+ * @deprecated Use `client.send(...)` instead.
401
+ */
402
+ send(client: Client, type: string | number, message: any, options?: ISendOptions): void;
403
+ /**
404
+ * Broadcast a message to all connected clients.
405
+ * @param type - The type of the message.
406
+ * @param message - The message to broadcast.
407
+ * @param options - The options for the broadcast.
408
+ *
409
+ * @example
410
+ * ```typescript
411
+ * this.broadcast('message', { message: 'Hello, world!' });
412
+ * ```
413
+ */
414
+ broadcast<K extends keyof ExtractRoomClient<T>['~messages'] & string | number>(type: K, ...args: MessageArgs<ExtractRoomClient<T>['~messages'][K], IBroadcastOptions>): void;
415
+ /**
416
+ * Broadcast bytes (UInt8Arrays) to a particular room
417
+ */
418
+ broadcastBytes(type: string | number, message: Uint8Array, options: IBroadcastOptions): void;
419
+ /**
420
+ * Checks whether mutations have occurred in the state, and broadcast them to all connected clients.
421
+ */
422
+ broadcastPatch(): boolean;
423
+ /**
424
+ * Register a message handler for a specific message type.
425
+ * This method is used to handle messages sent by clients to the room.
426
+ * @param messageType - The type of the message.
427
+ * @param callback - The callback to call when the message is received.
428
+ * @returns A function to unbind the callback.
429
+ *
430
+ * @example
431
+ * ```typescript
432
+ * this.onMessage('message', (client, message) => {
433
+ * console.log(message);
434
+ * });
435
+ * ```
436
+ *
437
+ * @example
438
+ * ```typescript
439
+ * const unbind = this.onMessage('message', (client, message) => {
440
+ * console.log(message);
441
+ * });
442
+ *
443
+ * // Unbind the callback when no longer needed
444
+ * unbind();
445
+ * ```
446
+ */
447
+ onMessage<T = any, C extends Client = ExtractRoomClient<T>>(messageType: '*', callback: (client: C, type: string | number, message: T) => void): any;
448
+ onMessage<T = any, C extends Client = ExtractRoomClient<T>>(messageType: string | number, callback: (client: C, message: T) => void): any;
449
+ onMessage<T = any, C extends Client = ExtractRoomClient<T>>(messageType: string | number, validationSchema: StandardSchemaV1<T>, callback: (client: C, message: T) => void): any;
450
+ onMessageBytes<T = any, C extends Client = ExtractRoomClient<T>>(messageType: string | number, callback: (client: C, message: T) => void): any;
451
+ onMessageBytes<T = any, C extends Client = ExtractRoomClient<T>>(messageType: string | number, validationSchema: StandardSchemaV1<T>, callback: (client: C, message: T) => void): any;
452
+ /**
453
+ * Disconnect all connected clients, and then dispose the room.
454
+ *
455
+ * @param closeCode WebSocket close code (default = 4000, which is a "consented leave")
456
+ * @returns Promise<void>
457
+ */
458
+ disconnect(closeCode?: number): Promise<any>;
459
+ private _onJoin;
460
+ /**
461
+ * Allow the specified client to reconnect into the room. Must be used inside `onLeave()` method.
462
+ * If seconds is provided, the reconnection is going to be cancelled after the provided amount of seconds.
463
+ *
464
+ * @param client - The client that is allowed to reconnect into the room.
465
+ * @param seconds - The time in seconds that the client is allowed to reconnect into the room.
466
+ *
467
+ * @returns Deferred<Client> - The differed is a promise like type.
468
+ * This type can forcibly reject the promise by calling `.reject()`.
469
+ *
470
+ * @example
471
+ * ```typescript
472
+ * onDrop(client: Client, code: CloseCode) {
473
+ * // Allow the client to reconnect into the room with a 15 seconds timeout.
474
+ * this.allowReconnection(client, 15);
475
+ * }
476
+ * ```
477
+ */
478
+ allowReconnection(previousClient: Client, seconds: number | "manual"): Deferred<Client>;
479
+ private resetAutoDisposeTimeout;
480
+ private broadcastMessageType;
481
+ private sendFullState;
482
+ private _dequeueAfterPatchMessages;
483
+ private _reserveSeat;
484
+ private _reserveMultipleSeats;
485
+ private _onMessage;
486
+ private _onLeave;
487
+ }
488
+ /**
489
+ * (WIP) Alternative, method-based room definition.
490
+ * We should be able to define
491
+ */
492
+ type RoomLifecycleMethods = 'messages' | 'onCreate' | 'onJoin' | 'onLeave' | 'onDispose' | 'onCacheRoom' | 'onRestoreRoom' | 'onDrop' | 'onReconnect' | 'onUncaughtException' | 'onAuth' | 'onBeforeShutdown' | 'onBeforePatch';
493
+ type DefineRoomOptions<T extends RoomOptions = RoomOptions> = Partial<Pick<Room<T>, RoomLifecycleMethods>> & {
494
+ state?: ExtractRoomState<T> | (() => ExtractRoomState<T>);
495
+ } & ThisType<Exclude<Room<T>, RoomLifecycleMethods>> & ThisType<Room<T>>;
496
+ export declare function room<T>(options: DefineRoomOptions<T>): typeof Room<T>;
497
+ export {};
@@ -1,10 +1,10 @@
1
- import http, { IncomingMessage, ServerResponse } from 'http';
2
- import * as matchMaker from './MatchMaker.js';
3
- import { RegisteredHandler } from './matchmaker/RegisteredHandler.js';
4
- import { Presence } from './presence/Presence.js';
5
- import { Room } from './Room.js';
6
- import { Type } from './utils/types.js';
7
- import { Transport } from './Transport.js';
1
+ import * as matchMaker from './MatchMaker.ts';
2
+ import { RegisteredHandler } from './matchmaker/RegisteredHandler.ts';
3
+ import { type OnCreateOptions, Room } from './Room.ts';
4
+ import { type Type } from './utils/Utils.ts';
5
+ import type { Presence } from "./presence/Presence.ts";
6
+ import { Transport } from './Transport.ts';
7
+ import { type Router } from './router/index.ts';
8
8
  export type ServerOptions = {
9
9
  publicAddress?: string;
10
10
  presence?: Presence;
@@ -34,21 +34,20 @@ export type ServerOptions = {
34
34
  * Default: true
35
35
  */
36
36
  greet?: boolean;
37
- /**
38
- * Options below are now part of WebSocketTransport (@colyseus/ws-transport)
39
- * TODO: remove me on 0.15.0
40
- */
41
- /** @deprecated */
42
- pingInterval?: number;
43
- /** @deprecated */
44
- pingMaxRetries?: number;
45
- /** @deprecated */
46
- verifyClient?: any;
47
- /** @deprecated */
48
- server?: http.Server;
49
37
  };
50
- export declare class Server {
38
+ /**
39
+ * Exposed types for the client-side SDK.
40
+ */
41
+ export interface SDKTypes<RoomTypes extends Record<string, RegisteredHandler> = any, Routes extends Router = any> {
42
+ '~rooms': RoomTypes;
43
+ '~routes': Routes;
44
+ }
45
+ export declare class Server<RoomTypes extends Record<string, RegisteredHandler> = any, Routes extends Router = any> implements SDKTypes<RoomTypes, Routes> {
46
+ '~rooms': RoomTypes;
47
+ '~routes': Routes;
51
48
  transport: Transport;
49
+ router: Routes;
50
+ options: ServerOptions;
52
51
  protected presence: Presence;
53
52
  protected driver: matchMaker.MatchMakerDriver;
54
53
  protected port: number;
@@ -65,7 +64,6 @@ export declare class Server {
65
64
  * @param listeningListener
66
65
  */
67
66
  listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Promise<void>;
68
- registerProcessForDiscovery(): Promise<void>;
69
67
  /**
70
68
  * Define a new type of room for matchmaking.
71
69
  *
@@ -73,8 +71,8 @@ export declare class Server {
73
71
  * @param roomClass Room class definition
74
72
  * @param defaultOptions default options for `onCreate`
75
73
  */
76
- define<T extends Type<Room>>(roomClass: T, defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0]): RegisteredHandler;
77
- define<T extends Type<Room>>(name: string, roomClass: T, defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0]): RegisteredHandler;
74
+ define<T extends Type<Room>>(roomClass: T, defaultOptions?: OnCreateOptions<T>): RegisteredHandler;
75
+ define<T extends Type<Room>>(name: string, roomClass: T, defaultOptions?: OnCreateOptions<T>): RegisteredHandler;
78
76
  /**
79
77
  * Remove a room definition from matchmaking.
80
78
  * This method does not destroy any room. It only dissallows matchmaking
@@ -95,6 +93,6 @@ export declare class Server {
95
93
  protected getDefaultTransport(_: any): Transport;
96
94
  protected onShutdownCallback: () => void | Promise<any>;
97
95
  protected onBeforeShutdownCallback: () => void | Promise<any>;
98
- protected attachMatchMakingRoutes(server: http.Server): void;
99
- protected handleMatchMakeRequest(req: IncomingMessage, res: ServerResponse): Promise<void>;
100
96
  }
97
+ export declare function defineServer<T extends Record<string, RegisteredHandler>, R extends Router>(roomHandlers: T, router?: R, serverOptions?: ServerOptions): Server<T, R>;
98
+ export declare function defineRoom<T extends Type<Room>>(roomKlass: T, defaultOptions?: Parameters<NonNullable<InstanceType<T>['onCreate']>>[0]): RegisteredHandler<T>;