@colyseus/core 0.17.53 → 0.17.55
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/build/Room.cjs +5 -2
- package/build/Room.cjs.map +2 -2
- package/build/Room.mjs +5 -2
- package/build/Room.mjs.map +2 -2
- package/build/matchmaker/LocalDriver/Query.cjs +5 -5
- package/build/matchmaker/LocalDriver/Query.cjs.map +2 -2
- package/build/matchmaker/LocalDriver/Query.mjs +5 -5
- package/build/matchmaker/LocalDriver/Query.mjs.map +2 -2
- package/build/matchmaker/RegisteredHandler.cjs +1 -1
- package/build/matchmaker/RegisteredHandler.cjs.map +2 -2
- package/build/matchmaker/RegisteredHandler.mjs +1 -1
- package/build/matchmaker/RegisteredHandler.mjs.map +2 -2
- package/build/utils/Utils.cjs +1 -1
- package/build/utils/Utils.cjs.map +2 -2
- package/build/utils/Utils.mjs +1 -1
- package/build/utils/Utils.mjs.map +2 -2
- package/package.json +8 -8
- package/src/Room.ts +7 -2
- package/src/matchmaker/LocalDriver/Query.ts +5 -5
- package/src/matchmaker/RegisteredHandler.ts +1 -1
- package/src/utils/Utils.ts +2 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/matchmaker/RegisteredHandler.ts"],
|
|
4
|
-
"sourcesContent": ["import { EventEmitter } from 'events';\nimport { logger } from '../Logger.ts';\nimport { Room } from './../Room.ts';\nimport { updateLobby } from './Lobby.ts';\n\nimport type { IRoomCache, SortOptions, IRoomCacheFilterByKeys, IRoomCacheSortByKeys, ExtractRoomCacheMetadata } from './driver.ts';\nimport type { Client } from '../Transport.ts';\nimport type { Type } from \"../utils/Utils.ts\";\n\nexport const INVALID_OPTION_KEYS: Array<keyof IRoomCache> = [\n 'clients',\n 'locked',\n 'private',\n // 'maxClients', - maxClients can be useful as filter options\n 'metadata',\n 'name',\n 'processId',\n 'roomId',\n];\n\n/**\n * Type for filterBy that supports both onCreate options and metadata fields\n */\ntype FilterByKeys<RoomType extends Room> =\n | IRoomCacheFilterByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never)\n\n/**\n * Type for sortBy that supports room cache fields and metadata fields\n */\ntype SortByKeys<RoomType extends Room> =\n | IRoomCacheSortByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never);\n\nexport interface RegisteredHandlerEvents<RoomType extends Room = any> {\n create: [room: RoomType];\n lock: [room: RoomType];\n unlock: [room: RoomType];\n join: [room: RoomType, client: Client];\n leave: [room: RoomType, client: Client, willDispose: boolean];\n dispose: [room: RoomType];\n 'visibility-change': [room: RoomType, isVisible: boolean];\n 'metadata-change': [room: RoomType];\n}\n\nexport class RegisteredHandler<\n RoomType extends Room = any\n> extends EventEmitter<RegisteredHandlerEvents<RoomType>> {\n '~room': RoomType;\n\n public klass: Type<RoomType>;\n public options: any;\n\n public name: string;\n public filterOptions: Array<FilterByKeys<RoomType>> = [];\n public sortOptions?: SortOptions;\n\n public realtimeListingEnabled: boolean = false;\n\n constructor(klass: Type<RoomType>, options?: any) {\n super();\n\n this.klass = klass;\n this.options = options;\n\n if (typeof(klass) !== 'function') {\n logger.debug('You are likely not importing your room class correctly.');\n throw new Error(`class is expected but ${typeof(klass)} was provided.`);\n }\n }\n\n public enableRealtimeListing() {\n this.realtimeListingEnabled = true;\n this.on('create', (room) => updateLobby(room));\n this.on('lock', (room) => updateLobby(room));\n this.on('unlock', (room) => updateLobby(room));\n this.on('join', (room) => updateLobby(room));\n this.on('leave', (room, _, willDispose) => {\n if (!willDispose) {\n updateLobby(room);\n }\n });\n this.on('visibility-change', (room, isVisible) => updateLobby(room, isVisible));\n this.on('metadata-change', (room) => updateLobby(room));\n this.on('dispose', (room) => updateLobby(room, true));\n return this;\n }\n\n /**\n * Define which fields should be used for filtering rooms.\n * Supports both onCreate options and metadata fields using dot notation.\n *\n * @example\n * // Filter by IRoomCache fields\n * .filterBy(['maxClients'])\n *\n * @example\n * // Filter by metadata fields\n * .filterBy(['difficulty', 'metadata.region'])\n *\n * @example\n * // Mix both\n * .filterBy(['mode', 'difficulty', 'maxClients'])\n */\n public filterBy<T extends FilterByKeys<RoomType>>(\n options: T[]\n ) {\n this.filterOptions = options;\n return this;\n }\n\n /**\n * Define how rooms should be sorted when querying.\n * Supports both room cache fields and metadata fields using dot notation.\n *\n * @example\n * // Sort by number of clients (descending)\n * .sortBy({ clients: -1 })\n *\n * @example\n * // Sort by metadata field\n * .sortBy({ 'metadata.rating': -1 })\n *\n * @example\n * // Multiple sort criteria\n * .sortBy({ 'metadata.skillLevel': 1, clients: -1 })\n */\n public sortBy<T extends SortByKeys<RoomType>>(\n options: { [K in T]: SortOptions[string] }\n ): this {\n this.sortOptions = options as unknown as SortOptions;\n return this;\n }\n\n public getMetadataFromOptions(options: any) {\n const metadata = this.getFilterOptions(options);\n\n if (this.sortOptions) {\n for (const field in this.sortOptions) {\n if (field in options && !(field in metadata)) {\n metadata[field] = options[field];\n }\n }\n }\n\n return Object.keys(metadata).length > 0 ? { metadata } : {};\n }\n\n /**\n * Extract filter options from client options.\n */\n public getFilterOptions(options: any) {\n return this.filterOptions.reduce((prev, curr, i, arr) => {\n const field = String(arr[i]);\n\n // Handle regular (non-metadata) fields\n if (
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6B;AAC7B,oBAAuB;AACvB,kBAAqB;AACrB,mBAA4B;AAMrB,IAAM,sBAA+C;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA+BO,IAAM,oBAAN,cAEG,2BAAgD;AAAA,EAYxD,YAAY,OAAuB,SAAe;AAChD,UAAM;AANR,SAAO,gBAA+C,CAAC;AAGvD,SAAO,yBAAkC;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,SAAS,WAAW,EAAE,SAAS,WAAW;AAC5C,mBAAS,KAAK,IAAI,QAAQ,KAAK;AAAA,QACjC;AAAA,MACF;AAAA,IACF;AAEA,WAAO,OAAO,KAAK,QAAQ,EAAE,SAAS,IAAI,EAAE,SAAS,IAAI,CAAC;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA,EAKO,iBAAiB,SAAc;AACpC,WAAO,KAAK,cAAc,OAAO,CAAC,MAAM,MAAM,GAAG,QAAQ;AACvD,YAAM,QAAQ,OAAO,IAAI,CAAC,CAAC;AAG3B,UAAI,
|
|
4
|
+
"sourcesContent": ["import { EventEmitter } from 'events';\nimport { logger } from '../Logger.ts';\nimport { Room } from './../Room.ts';\nimport { updateLobby } from './Lobby.ts';\n\nimport type { IRoomCache, SortOptions, IRoomCacheFilterByKeys, IRoomCacheSortByKeys, ExtractRoomCacheMetadata } from './driver.ts';\nimport type { Client } from '../Transport.ts';\nimport type { Type } from \"../utils/Utils.ts\";\n\nexport const INVALID_OPTION_KEYS: Array<keyof IRoomCache> = [\n 'clients',\n 'locked',\n 'private',\n // 'maxClients', - maxClients can be useful as filter options\n 'metadata',\n 'name',\n 'processId',\n 'roomId',\n];\n\n/**\n * Type for filterBy that supports both onCreate options and metadata fields\n */\ntype FilterByKeys<RoomType extends Room> =\n | IRoomCacheFilterByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never)\n\n/**\n * Type for sortBy that supports room cache fields and metadata fields\n */\ntype SortByKeys<RoomType extends Room> =\n | IRoomCacheSortByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never);\n\nexport interface RegisteredHandlerEvents<RoomType extends Room = any> {\n create: [room: RoomType];\n lock: [room: RoomType];\n unlock: [room: RoomType];\n join: [room: RoomType, client: Client];\n leave: [room: RoomType, client: Client, willDispose: boolean];\n dispose: [room: RoomType];\n 'visibility-change': [room: RoomType, isVisible: boolean];\n 'metadata-change': [room: RoomType];\n}\n\nexport class RegisteredHandler<\n RoomType extends Room = any\n> extends EventEmitter<RegisteredHandlerEvents<RoomType>> {\n '~room': RoomType;\n\n public klass: Type<RoomType>;\n public options: any;\n\n public name: string;\n public filterOptions: Array<FilterByKeys<RoomType>> = [];\n public sortOptions?: SortOptions;\n\n public realtimeListingEnabled: boolean = false;\n\n constructor(klass: Type<RoomType>, options?: any) {\n super();\n\n this.klass = klass;\n this.options = options;\n\n if (typeof(klass) !== 'function') {\n logger.debug('You are likely not importing your room class correctly.');\n throw new Error(`class is expected but ${typeof(klass)} was provided.`);\n }\n }\n\n public enableRealtimeListing() {\n this.realtimeListingEnabled = true;\n this.on('create', (room) => updateLobby(room));\n this.on('lock', (room) => updateLobby(room));\n this.on('unlock', (room) => updateLobby(room));\n this.on('join', (room) => updateLobby(room));\n this.on('leave', (room, _, willDispose) => {\n if (!willDispose) {\n updateLobby(room);\n }\n });\n this.on('visibility-change', (room, isVisible) => updateLobby(room, isVisible));\n this.on('metadata-change', (room) => updateLobby(room));\n this.on('dispose', (room) => updateLobby(room, true));\n return this;\n }\n\n /**\n * Define which fields should be used for filtering rooms.\n * Supports both onCreate options and metadata fields using dot notation.\n *\n * @example\n * // Filter by IRoomCache fields\n * .filterBy(['maxClients'])\n *\n * @example\n * // Filter by metadata fields\n * .filterBy(['difficulty', 'metadata.region'])\n *\n * @example\n * // Mix both\n * .filterBy(['mode', 'difficulty', 'maxClients'])\n */\n public filterBy<T extends FilterByKeys<RoomType>>(\n options: T[]\n ) {\n this.filterOptions = options;\n return this;\n }\n\n /**\n * Define how rooms should be sorted when querying.\n * Supports both room cache fields and metadata fields using dot notation.\n *\n * @example\n * // Sort by number of clients (descending)\n * .sortBy({ clients: -1 })\n *\n * @example\n * // Sort by metadata field\n * .sortBy({ 'metadata.rating': -1 })\n *\n * @example\n * // Multiple sort criteria\n * .sortBy({ 'metadata.skillLevel': 1, clients: -1 })\n */\n public sortBy<T extends SortByKeys<RoomType>>(\n options: { [K in T]: SortOptions[string] }\n ): this {\n this.sortOptions = options as unknown as SortOptions;\n return this;\n }\n\n public getMetadataFromOptions(options: any) {\n const metadata = this.getFilterOptions(options);\n\n if (this.sortOptions) {\n for (const field in this.sortOptions) {\n if (field in options && !(field in metadata)) {\n metadata[field] = options[field];\n }\n }\n }\n\n return Object.keys(metadata).length > 0 ? { metadata } : {};\n }\n\n /**\n * Extract filter options from client options.\n */\n public getFilterOptions(options: any) {\n return this.filterOptions.reduce((prev, curr, i, arr) => {\n const field = String(arr[i]);\n\n // Handle regular (non-metadata) fields\n if (Object.hasOwn(options, field)) {\n if (INVALID_OPTION_KEYS.indexOf(field as any) !== -1) {\n logger.warn(`option \"${field}\" has internal usage and is going to be ignored.`);\n } else {\n prev[field] = options[field];\n }\n }\n\n return prev;\n }, {});\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6B;AAC7B,oBAAuB;AACvB,kBAAqB;AACrB,mBAA4B;AAMrB,IAAM,sBAA+C;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA+BO,IAAM,oBAAN,cAEG,2BAAgD;AAAA,EAYxD,YAAY,OAAuB,SAAe;AAChD,UAAM;AANR,SAAO,gBAA+C,CAAC;AAGvD,SAAO,yBAAkC;AAKvC,SAAK,QAAQ;AACb,SAAK,UAAU;AAEf,QAAI,OAAO,UAAW,YAAY;AAChC,2BAAO,MAAM,yDAAyD;AACtE,YAAM,IAAI,MAAM,yBAAyB,OAAO,KAAM,gBAAgB;AAAA,IACxE;AAAA,EACF;AAAA,EAEO,wBAAwB;AAC7B,SAAK,yBAAyB;AAC9B,SAAK,GAAG,UAAU,CAAC,aAAS,0BAAY,IAAI,CAAC;AAC7C,SAAK,GAAG,QAAQ,CAAC,aAAS,0BAAY,IAA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AO,IAAI,CAAC,CAAC;AAG3B,UAAI,OAAO,OAAO,SAAS,KAAK,GAAG;AACjC,YAAI,oBAAoB,QAAQ,KAAY,MAAM,IAAI;AACpD,+BAAO,KAAK,WAAW,KAAK,kDAAkD;AAAA,QAChF,OAAO;AACL,eAAK,KAAK,IAAI,QAAQ,KAAK;AAAA,QAC7B;AAAA,MACF;AAEA,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACP;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -98,7 +98,7 @@ var RegisteredHandler = class extends EventEmitter {
|
|
|
98
98
|
getFilterOptions(options) {
|
|
99
99
|
return this.filterOptions.reduce((prev, curr, i, arr) => {
|
|
100
100
|
const field = String(arr[i]);
|
|
101
|
-
if (
|
|
101
|
+
if (Object.hasOwn(options, field)) {
|
|
102
102
|
if (INVALID_OPTION_KEYS.indexOf(field) !== -1) {
|
|
103
103
|
logger.warn(`option "${field}" has internal usage and is going to be ignored.`);
|
|
104
104
|
} else {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/matchmaker/RegisteredHandler.ts"],
|
|
4
|
-
"sourcesContent": ["import { EventEmitter } from 'events';\nimport { logger } from '../Logger.ts';\nimport { Room } from './../Room.ts';\nimport { updateLobby } from './Lobby.ts';\n\nimport type { IRoomCache, SortOptions, IRoomCacheFilterByKeys, IRoomCacheSortByKeys, ExtractRoomCacheMetadata } from './driver.ts';\nimport type { Client } from '../Transport.ts';\nimport type { Type } from \"../utils/Utils.ts\";\n\nexport const INVALID_OPTION_KEYS: Array<keyof IRoomCache> = [\n 'clients',\n 'locked',\n 'private',\n // 'maxClients', - maxClients can be useful as filter options\n 'metadata',\n 'name',\n 'processId',\n 'roomId',\n];\n\n/**\n * Type for filterBy that supports both onCreate options and metadata fields\n */\ntype FilterByKeys<RoomType extends Room> =\n | IRoomCacheFilterByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never)\n\n/**\n * Type for sortBy that supports room cache fields and metadata fields\n */\ntype SortByKeys<RoomType extends Room> =\n | IRoomCacheSortByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never);\n\nexport interface RegisteredHandlerEvents<RoomType extends Room = any> {\n create: [room: RoomType];\n lock: [room: RoomType];\n unlock: [room: RoomType];\n join: [room: RoomType, client: Client];\n leave: [room: RoomType, client: Client, willDispose: boolean];\n dispose: [room: RoomType];\n 'visibility-change': [room: RoomType, isVisible: boolean];\n 'metadata-change': [room: RoomType];\n}\n\nexport class RegisteredHandler<\n RoomType extends Room = any\n> extends EventEmitter<RegisteredHandlerEvents<RoomType>> {\n '~room': RoomType;\n\n public klass: Type<RoomType>;\n public options: any;\n\n public name: string;\n public filterOptions: Array<FilterByKeys<RoomType>> = [];\n public sortOptions?: SortOptions;\n\n public realtimeListingEnabled: boolean = false;\n\n constructor(klass: Type<RoomType>, options?: any) {\n super();\n\n this.klass = klass;\n this.options = options;\n\n if (typeof(klass) !== 'function') {\n logger.debug('You are likely not importing your room class correctly.');\n throw new Error(`class is expected but ${typeof(klass)} was provided.`);\n }\n }\n\n public enableRealtimeListing() {\n this.realtimeListingEnabled = true;\n this.on('create', (room) => updateLobby(room));\n this.on('lock', (room) => updateLobby(room));\n this.on('unlock', (room) => updateLobby(room));\n this.on('join', (room) => updateLobby(room));\n this.on('leave', (room, _, willDispose) => {\n if (!willDispose) {\n updateLobby(room);\n }\n });\n this.on('visibility-change', (room, isVisible) => updateLobby(room, isVisible));\n this.on('metadata-change', (room) => updateLobby(room));\n this.on('dispose', (room) => updateLobby(room, true));\n return this;\n }\n\n /**\n * Define which fields should be used for filtering rooms.\n * Supports both onCreate options and metadata fields using dot notation.\n *\n * @example\n * // Filter by IRoomCache fields\n * .filterBy(['maxClients'])\n *\n * @example\n * // Filter by metadata fields\n * .filterBy(['difficulty', 'metadata.region'])\n *\n * @example\n * // Mix both\n * .filterBy(['mode', 'difficulty', 'maxClients'])\n */\n public filterBy<T extends FilterByKeys<RoomType>>(\n options: T[]\n ) {\n this.filterOptions = options;\n return this;\n }\n\n /**\n * Define how rooms should be sorted when querying.\n * Supports both room cache fields and metadata fields using dot notation.\n *\n * @example\n * // Sort by number of clients (descending)\n * .sortBy({ clients: -1 })\n *\n * @example\n * // Sort by metadata field\n * .sortBy({ 'metadata.rating': -1 })\n *\n * @example\n * // Multiple sort criteria\n * .sortBy({ 'metadata.skillLevel': 1, clients: -1 })\n */\n public sortBy<T extends SortByKeys<RoomType>>(\n options: { [K in T]: SortOptions[string] }\n ): this {\n this.sortOptions = options as unknown as SortOptions;\n return this;\n }\n\n public getMetadataFromOptions(options: any) {\n const metadata = this.getFilterOptions(options);\n\n if (this.sortOptions) {\n for (const field in this.sortOptions) {\n if (field in options && !(field in metadata)) {\n metadata[field] = options[field];\n }\n }\n }\n\n return Object.keys(metadata).length > 0 ? { metadata } : {};\n }\n\n /**\n * Extract filter options from client options.\n */\n public getFilterOptions(options: any) {\n return this.filterOptions.reduce((prev, curr, i, arr) => {\n const field = String(arr[i]);\n\n // Handle regular (non-metadata) fields\n if (
|
|
5
|
-
"mappings": ";AAAA,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,OAAqB;AACrB,SAAS,mBAAmB;AAMrB,IAAM,sBAA+C;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA+BO,IAAM,oBAAN,cAEG,aAAgD;AAAA,EAYxD,YAAY,OAAuB,SAAe;AAChD,UAAM;AANR,SAAO,gBAA+C,CAAC;AAGvD,SAAO,yBAAkC;AAKvC,SAAK,QAAQ;AACb,SAAK,UAAU;AAEf,QAAI,OAAO,UAAW,YAAY;AAChC,aAAO,MAAM,yDAAyD;AACtE,YAAM,IAAI,MAAM,yBAAyB,OAAO,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AAS,IAAI,EAAE,SAAS,IAAI,CAAC;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA,EAKO,iBAAiB,SAAc;AACpC,WAAO,KAAK,cAAc,OAAO,CAAC,MAAM,MAAM,GAAG,QAAQ;AACvD,YAAM,QAAQ,OAAO,IAAI,CAAC,CAAC;AAG3B,UAAI,
|
|
4
|
+
"sourcesContent": ["import { EventEmitter } from 'events';\nimport { logger } from '../Logger.ts';\nimport { Room } from './../Room.ts';\nimport { updateLobby } from './Lobby.ts';\n\nimport type { IRoomCache, SortOptions, IRoomCacheFilterByKeys, IRoomCacheSortByKeys, ExtractRoomCacheMetadata } from './driver.ts';\nimport type { Client } from '../Transport.ts';\nimport type { Type } from \"../utils/Utils.ts\";\n\nexport const INVALID_OPTION_KEYS: Array<keyof IRoomCache> = [\n 'clients',\n 'locked',\n 'private',\n // 'maxClients', - maxClients can be useful as filter options\n 'metadata',\n 'name',\n 'processId',\n 'roomId',\n];\n\n/**\n * Type for filterBy that supports both onCreate options and metadata fields\n */\ntype FilterByKeys<RoomType extends Room> =\n | IRoomCacheFilterByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never)\n\n/**\n * Type for sortBy that supports room cache fields and metadata fields\n */\ntype SortByKeys<RoomType extends Room> =\n | IRoomCacheSortByKeys\n | (ExtractRoomCacheMetadata<RoomType> extends object\n ? keyof ExtractRoomCacheMetadata<RoomType> & string\n : never);\n\nexport interface RegisteredHandlerEvents<RoomType extends Room = any> {\n create: [room: RoomType];\n lock: [room: RoomType];\n unlock: [room: RoomType];\n join: [room: RoomType, client: Client];\n leave: [room: RoomType, client: Client, willDispose: boolean];\n dispose: [room: RoomType];\n 'visibility-change': [room: RoomType, isVisible: boolean];\n 'metadata-change': [room: RoomType];\n}\n\nexport class RegisteredHandler<\n RoomType extends Room = any\n> extends EventEmitter<RegisteredHandlerEvents<RoomType>> {\n '~room': RoomType;\n\n public klass: Type<RoomType>;\n public options: any;\n\n public name: string;\n public filterOptions: Array<FilterByKeys<RoomType>> = [];\n public sortOptions?: SortOptions;\n\n public realtimeListingEnabled: boolean = false;\n\n constructor(klass: Type<RoomType>, options?: any) {\n super();\n\n this.klass = klass;\n this.options = options;\n\n if (typeof(klass) !== 'function') {\n logger.debug('You are likely not importing your room class correctly.');\n throw new Error(`class is expected but ${typeof(klass)} was provided.`);\n }\n }\n\n public enableRealtimeListing() {\n this.realtimeListingEnabled = true;\n this.on('create', (room) => updateLobby(room));\n this.on('lock', (room) => updateLobby(room));\n this.on('unlock', (room) => updateLobby(room));\n this.on('join', (room) => updateLobby(room));\n this.on('leave', (room, _, willDispose) => {\n if (!willDispose) {\n updateLobby(room);\n }\n });\n this.on('visibility-change', (room, isVisible) => updateLobby(room, isVisible));\n this.on('metadata-change', (room) => updateLobby(room));\n this.on('dispose', (room) => updateLobby(room, true));\n return this;\n }\n\n /**\n * Define which fields should be used for filtering rooms.\n * Supports both onCreate options and metadata fields using dot notation.\n *\n * @example\n * // Filter by IRoomCache fields\n * .filterBy(['maxClients'])\n *\n * @example\n * // Filter by metadata fields\n * .filterBy(['difficulty', 'metadata.region'])\n *\n * @example\n * // Mix both\n * .filterBy(['mode', 'difficulty', 'maxClients'])\n */\n public filterBy<T extends FilterByKeys<RoomType>>(\n options: T[]\n ) {\n this.filterOptions = options;\n return this;\n }\n\n /**\n * Define how rooms should be sorted when querying.\n * Supports both room cache fields and metadata fields using dot notation.\n *\n * @example\n * // Sort by number of clients (descending)\n * .sortBy({ clients: -1 })\n *\n * @example\n * // Sort by metadata field\n * .sortBy({ 'metadata.rating': -1 })\n *\n * @example\n * // Multiple sort criteria\n * .sortBy({ 'metadata.skillLevel': 1, clients: -1 })\n */\n public sortBy<T extends SortByKeys<RoomType>>(\n options: { [K in T]: SortOptions[string] }\n ): this {\n this.sortOptions = options as unknown as SortOptions;\n return this;\n }\n\n public getMetadataFromOptions(options: any) {\n const metadata = this.getFilterOptions(options);\n\n if (this.sortOptions) {\n for (const field in this.sortOptions) {\n if (field in options && !(field in metadata)) {\n metadata[field] = options[field];\n }\n }\n }\n\n return Object.keys(metadata).length > 0 ? { metadata } : {};\n }\n\n /**\n * Extract filter options from client options.\n */\n public getFilterOptions(options: any) {\n return this.filterOptions.reduce((prev, curr, i, arr) => {\n const field = String(arr[i]);\n\n // Handle regular (non-metadata) fields\n if (Object.hasOwn(options, field)) {\n if (INVALID_OPTION_KEYS.indexOf(field as any) !== -1) {\n logger.warn(`option \"${field}\" has internal usage and is going to be ignored.`);\n } else {\n prev[field] = options[field];\n }\n }\n\n return prev;\n }, {});\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,OAAqB;AACrB,SAAS,mBAAmB;AAMrB,IAAM,sBAA+C;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA+BO,IAAM,oBAAN,cAEG,aAAgD;AAAA,EAYxD,YAAY,OAAuB,SAAe;AAChD,UAAM;AANR,SAAO,gBAA+C,CAAC;AAGvD,SAAO,yBAAkC;AAKvC,SAAK,QAAQ;AACb,SAAK,UAAU;AAEf,QAAI,OAAO,UAAW,YAAY;AAChC,aAAO,MAAM,yDAAyD;AACtE,YAAM,IAAI,MAAM,yBAAyB,OAAO,KAAM,gBAAgB;AAAA,IACxE;AAAA,EACF;AAAA,EAEO,wBAAwB;AAC7B,SAAK,yBAAyB;AAC9B,SAAK,GAAG,UAAU,CAAC,SAAS,YAAY,IAAI,CAAC;AAC7C,SAAK,GAAG,QAAQ,CAAC,SAAS,YAAY,IAAI,CAAC;AAC3C,SAAK,GAAG,UAAU,CAAC,SAAS,YAAY,IAAI,CAAC;AAC7C,SAAK,GAAG,QAAQ,CAAC,SAAS,YAAY,IAAI,CAAC;AAC3C,SAAK,GAAG,SAAS,CAAC,MAAM,GAAG,gBAAgB;AACzC,UAAI,CAAC,aA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AAK;AAAA,QAC7B;AAAA,MACF;AAEA,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACP;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/build/utils/Utils.cjs
CHANGED
|
@@ -105,7 +105,7 @@ function merge(a, ...objs) {
|
|
|
105
105
|
for (let i = 0, len = objs.length; i < len; i++) {
|
|
106
106
|
const b = objs[i];
|
|
107
107
|
for (const key in b) {
|
|
108
|
-
if (
|
|
108
|
+
if (key !== "__proto__" && Object.hasOwn(b, key)) {
|
|
109
109
|
a[key] = b[key];
|
|
110
110
|
}
|
|
111
111
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/Utils.ts"],
|
|
4
|
-
"sourcesContent": ["import { nanoid } from 'nanoid';\nimport { type RoomException, type RoomMethodName } from '../errors/RoomExceptions.ts';\n\nimport { debugAndPrintError, debugMatchMaking } from '../Debug.ts';\n\nexport type Type<T> = new (...args: any[]) => T;\nexport type MethodName<T> = string & {\n [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never\n}[keyof T];\n\n/**\n * Utility type that extracts the return type of a method or the type of a property\n * from a given class/object type.\n *\n * - If the key is a method, returns the awaited return type of that method\n * - If the key is a property, returns the type of that property\n */\nexport type ExtractMethodOrPropertyType<\n TClass,\n TKey extends keyof TClass\n> = TClass[TKey] extends (...args: any[]) => infer R\n ? Awaited<R>\n : TClass[TKey];\n\n/**\n * Return type of `remoteRoomCall()`.\n *\n * Resolves to the method's awaited return type (or the property's type) when\n * the method name was captured as a literal type. Falls back to `any` when it\n * wasn't \u2014 e.g. `remoteRoomCall<MyRoom>(...)` with only the room type given:\n * TypeScript applies the `TMethod` default instead of inferring the literal\n * once an explicit type argument list is present (microsoft/TypeScript#26242).\n * Pass both type arguments (`remoteRoomCall<MyRoom, 'myMethod'>`) for a\n * precise return type.\n */\nexport type RemoteRoomCallReturn<\n TRoom,\n TMethod extends keyof TRoom\n> = keyof TRoom extends TMethod\n ? any\n : ExtractMethodOrPropertyType<TRoom, TMethod>;\n\n// remote room call timeouts\nexport const REMOTE_ROOM_SHORT_TIMEOUT = Number(process.env.COLYSEUS_PRESENCE_SHORT_TIMEOUT || 2000);\nexport const MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME = Number(process.env.COLYSEUS_MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME || 0.5);\n\n// a peer that removes this process's room listings leaves a receipt. this\n// process looks for it every INTERVAL (ms) and restores them. the TTL (seconds)\n// only bounds what dead processes leave behind.\nexport const SWEPT_CHECK_INTERVAL = Number(process.env.COLYSEUS_SWEPT_CHECK_INTERVAL || 5000);\nexport const SWEPT_RECEIPT_TTL = Number(process.env.COLYSEUS_SWEPT_RECEIPT_TTL || 600);\n\nexport function generateId(length: number = 9) {\n return nanoid(length);\n}\n\nexport function getBearerToken(authHeader: string) {\n return (authHeader && authHeader.startsWith(\"Bearer \") && authHeader.substring(7, authHeader.length)) || undefined;\n}\n\n// nodemon sends SIGUSR2 before reloading\n// (https://github.com/remy/nodemon#controlling-shutdown-of-your-script)\n//\nconst signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGUSR2'];\n\nexport function registerGracefulShutdown(callback: (err?: Error) => void) {\n /**\n * Gracefully shutdown on uncaught errors\n */\n process.on('uncaughtException', (err) => {\n debugAndPrintError(err);\n callback(err);\n });\n\n signals.forEach((signal) =>\n process.once(signal, () => callback()));\n}\n\nexport function retry<T = any>(\n cb: Function,\n maxRetries: number = 3,\n errorWhiteList: any[] = [],\n retries: number = 0,\n) {\n return new Promise<T>((resolve, reject) => {\n cb()\n .then(resolve)\n .catch((e: any) => {\n if (\n errorWhiteList.indexOf(e.constructor) !== -1 &&\n retries++ < maxRetries\n ) {\n setTimeout(() => {\n debugMatchMaking(\"retrying due to error (error: %s, retries: %s, maxRetries: %s)\", e.message, retries, maxRetries);\n retry<T>(cb, maxRetries, errorWhiteList, retries).\n then(resolve).\n catch((e2) => reject(e2));\n }, Math.floor(Math.random() * Math.pow(2, retries) * 400));\n\n } else {\n reject(e);\n }\n });\n });\n}\n\nexport function spliceOne(arr: any[], index: number): boolean {\n // manually splice availableRooms array\n // http://jsperf.com/manual-splice\n if (index === -1 || index >= arr.length) {\n return false;\n }\n\n const len = arr.length - 1;\n for (let i = index; i < len; i++) {\n arr[i] = arr[i + 1];\n }\n\n arr.length = len;\n return true;\n}\n\nexport class Deferred<T = any> {\n public promise: Promise<T>;\n\n public resolve: Function;\n public reject: Function;\n\n constructor(promise?: Promise<T>) {\n this.promise = promise ?? new Promise<T>((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n public then(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any) {\n return this.promise.then(onFulfilled, onRejected);\n }\n\n public catch(func: (value: any) => any) {\n return this.promise.catch(func);\n }\n\n static reject (reason?: any) {\n return new Deferred(Promise.reject(reason));\n }\n\n static resolve<T = any>(value?: T) {\n return new Deferred<T>(Promise.resolve(value));\n }\n\n}\n\nexport function merge(a: any, ...objs: any[]): any {\n for (let i = 0, len = objs.length; i < len; i++) {\n const b = objs[i];\n for (const key in b) {\n if (
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AACvB,4BAAwD;AAExD,mBAAqD;AAwC9C,IAAM,4BAA4B,OAAO,QAAQ,IAAI,mCAAmC,GAAI;AAC5F,IAAM,uCAAuC,OAAO,QAAQ,IAAI,iDAAiD,GAAG;AAKpH,IAAM,uBAAuB,OAAO,QAAQ,IAAI,iCAAiC,GAAI;AACrF,IAAM,oBAAoB,OAAO,QAAQ,IAAI,8BAA8B,GAAG;AAE9E,SAAS,WAAW,SAAiB,GAAG;AAC7C,aAAO,sBAAO,MAAM;AACtB;AAEO,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SAAsB;AAChC,SAAK,UAAU,WAAW,IAAI,QAAW,CAAC,SAAS,WAAW;AAC5D,WAAK,UAAU;AACf,WAAK,SAAS;AAAA,IAChB,CAAC;AAAA,EACH;AAAA,EAEO,KAAK,aAAiC,YAAmC;AAC9E,WAAO,KAAK,QAAQ,KAAK,aAAa,UAAU;AAAA,EAClD;AAAA,EAEO,MAAM,MAA2B;AACtC,WAAO,KAAK,QAAQ,MAAM,IAAI;AAAA,EAChC;AAAA,EAEA,OAAO,OAAQ,QAAc;AAC3B,WAAO,IAAI,UAAS,QAAQ,OAAO,MAAM,CAAC;AAAA,EAC5C;AAAA,EAEA,OAAO,QAAiB,OAAW;AACjC,WAAO,IAAI,UAAY,QAAQ,QAAQ,KAAK,CAAC;AAAA,EAC/C;AAEF;AAEO,SAAS,MAAM,MAAW,MAAkB;AACjD,WAAS,IAAI,GAAG,MAAM,KAAK,QAAQ,IAAI,KAAK,KAAK;AAC/C,UAAM,IAAI,KAAK,CAAC;AAChB,eAAW,OAAO,GAAG;
|
|
4
|
+
"sourcesContent": ["import { nanoid } from 'nanoid';\nimport { type RoomException, type RoomMethodName } from '../errors/RoomExceptions.ts';\n\nimport { debugAndPrintError, debugMatchMaking } from '../Debug.ts';\n\nexport type Type<T> = new (...args: any[]) => T;\nexport type MethodName<T> = string & {\n [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never\n}[keyof T];\n\n/**\n * Utility type that extracts the return type of a method or the type of a property\n * from a given class/object type.\n *\n * - If the key is a method, returns the awaited return type of that method\n * - If the key is a property, returns the type of that property\n */\nexport type ExtractMethodOrPropertyType<\n TClass,\n TKey extends keyof TClass\n> = TClass[TKey] extends (...args: any[]) => infer R\n ? Awaited<R>\n : TClass[TKey];\n\n/**\n * Return type of `remoteRoomCall()`.\n *\n * Resolves to the method's awaited return type (or the property's type) when\n * the method name was captured as a literal type. Falls back to `any` when it\n * wasn't \u2014 e.g. `remoteRoomCall<MyRoom>(...)` with only the room type given:\n * TypeScript applies the `TMethod` default instead of inferring the literal\n * once an explicit type argument list is present (microsoft/TypeScript#26242).\n * Pass both type arguments (`remoteRoomCall<MyRoom, 'myMethod'>`) for a\n * precise return type.\n */\nexport type RemoteRoomCallReturn<\n TRoom,\n TMethod extends keyof TRoom\n> = keyof TRoom extends TMethod\n ? any\n : ExtractMethodOrPropertyType<TRoom, TMethod>;\n\n// remote room call timeouts\nexport const REMOTE_ROOM_SHORT_TIMEOUT = Number(process.env.COLYSEUS_PRESENCE_SHORT_TIMEOUT || 2000);\nexport const MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME = Number(process.env.COLYSEUS_MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME || 0.5);\n\n// a peer that removes this process's room listings leaves a receipt. this\n// process looks for it every INTERVAL (ms) and restores them. the TTL (seconds)\n// only bounds what dead processes leave behind.\nexport const SWEPT_CHECK_INTERVAL = Number(process.env.COLYSEUS_SWEPT_CHECK_INTERVAL || 5000);\nexport const SWEPT_RECEIPT_TTL = Number(process.env.COLYSEUS_SWEPT_RECEIPT_TTL || 600);\n\nexport function generateId(length: number = 9) {\n return nanoid(length);\n}\n\nexport function getBearerToken(authHeader: string) {\n return (authHeader && authHeader.startsWith(\"Bearer \") && authHeader.substring(7, authHeader.length)) || undefined;\n}\n\n// nodemon sends SIGUSR2 before reloading\n// (https://github.com/remy/nodemon#controlling-shutdown-of-your-script)\n//\nconst signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGUSR2'];\n\nexport function registerGracefulShutdown(callback: (err?: Error) => void) {\n /**\n * Gracefully shutdown on uncaught errors\n */\n process.on('uncaughtException', (err) => {\n debugAndPrintError(err);\n callback(err);\n });\n\n signals.forEach((signal) =>\n process.once(signal, () => callback()));\n}\n\nexport function retry<T = any>(\n cb: Function,\n maxRetries: number = 3,\n errorWhiteList: any[] = [],\n retries: number = 0,\n) {\n return new Promise<T>((resolve, reject) => {\n cb()\n .then(resolve)\n .catch((e: any) => {\n if (\n errorWhiteList.indexOf(e.constructor) !== -1 &&\n retries++ < maxRetries\n ) {\n setTimeout(() => {\n debugMatchMaking(\"retrying due to error (error: %s, retries: %s, maxRetries: %s)\", e.message, retries, maxRetries);\n retry<T>(cb, maxRetries, errorWhiteList, retries).\n then(resolve).\n catch((e2) => reject(e2));\n }, Math.floor(Math.random() * Math.pow(2, retries) * 400));\n\n } else {\n reject(e);\n }\n });\n });\n}\n\nexport function spliceOne(arr: any[], index: number): boolean {\n // manually splice availableRooms array\n // http://jsperf.com/manual-splice\n if (index === -1 || index >= arr.length) {\n return false;\n }\n\n const len = arr.length - 1;\n for (let i = index; i < len; i++) {\n arr[i] = arr[i + 1];\n }\n\n arr.length = len;\n return true;\n}\n\nexport class Deferred<T = any> {\n public promise: Promise<T>;\n\n public resolve: Function;\n public reject: Function;\n\n constructor(promise?: Promise<T>) {\n this.promise = promise ?? new Promise<T>((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n public then(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any) {\n return this.promise.then(onFulfilled, onRejected);\n }\n\n public catch(func: (value: any) => any) {\n return this.promise.catch(func);\n }\n\n static reject (reason?: any) {\n return new Deferred(Promise.reject(reason));\n }\n\n static resolve<T = any>(value?: T) {\n return new Deferred<T>(Promise.resolve(value));\n }\n\n}\n\nexport function merge(a: any, ...objs: any[]): any {\n for (let i = 0, len = objs.length; i < len; i++) {\n const b = objs[i];\n for (const key in b) {\n // JSON.parse keeps \"__proto__\" as an own key: assigning it replaces a's prototype\n if (key !== \"__proto__\" && Object.hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n }\n return a;\n}\n\nexport function wrapTryCatch(\n method: Function,\n onError: (error: RoomException, methodName: RoomMethodName) => void,\n exceptionClass: Type<RoomException>,\n methodName: RoomMethodName,\n rethrow: boolean = false,\n ...additionalErrorArgs: any[]\n) {\n return (...args: any[]) => {\n try {\n const result = method(...args);\n if (typeof (result?.catch) === \"function\") {\n return result.catch((e: Error) => {\n onError(new exceptionClass(e, e.message, ...args, ...additionalErrorArgs), methodName);\n if (rethrow) { throw e; }\n });\n }\n return result;\n } catch (e: any) {\n onError(new exceptionClass(e, e.message, ...args, ...additionalErrorArgs), methodName);\n if (rethrow) { throw e; }\n }\n };\n}\n\n/**\n * Dynamically import a module using either require() or import()\n * based on the current module system (CJS vs ESM).\n *\n * This avoids double-loading packages when running in mixed ESM/CJS environments.\n * Errors are silently caught - await the promise and handle errors at usage site.\n */\nexport function dynamicImport<T = any>(moduleName: string): Promise<T> {\n // __dirname exists in CJS but not in ESM\n if (\n typeof __dirname !== 'undefined' &&\n // @ts-ignore\n typeof (Bun) === 'undefined' // prevent bun from loading CJS modules\n ) {\n // CJS context - use require()\n try {\n return Promise.resolve(require(moduleName));\n } catch (e: any) {\n // If the error is not a MODULE_NOT_FOUND error, reject with the error.\n if (e.code !== 'MODULE_NOT_FOUND') {\n return Promise.reject(e);\n }\n return Promise.resolve(undefined);\n }\n } else {\n // ESM context - use import()\n const promise = import(/* @vite-ignore */ moduleName);\n promise.catch(() => {}); // prevent unhandled rejection warnings\n return promise;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AACvB,4BAAwD;AAExD,mBAAqD;AAwC9C,IAAM,4BAA4B,OAAO,QAAQ,IAAI,mCAAmC,GAAI;AAC5F,IAAM,uCAAuC,OAAO,QAAQ,IAAI,iDAAiD,GAAG;AAKpH,IAAM,uBAAuB,OAAO,QAAQ,IAAI,iCAAiC,GAAI;AACrF,IAAM,oBAAoB,OAAO,QAAQ,IAAI,8BAA8B,GAAG;AAE9E,SAAS,WAAW,SAAiB,GAAG;AAC7C,aAAO,sBAAO,MAAM;AACtB;AAEO,SAAS,eAAe,YAAoB;AACjD,SAAQ,cAAc,WAAW,WAAW,SAAS,KAAK,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AAA,IAC1B;AAAA,EACF;AACF;AASO,SAAS,cAAuB,YAAgC;AAErE,MACE,OAAO,cAAc;AAAA,EAErB,OAAQ,QAAS,aACjB;AAEA,QAAI;AACF,aAAO,QAAQ,QAAQ,QAAQ,UAAU,CAAC;AAAA,IAC5C,SAAS,GAAQ;AAEf,UAAI,EAAE,SAAS,oBAAoB;AACjC,eAAO,QAAQ,OAAO,CAAC;AAAA,MACzB;AACA,aAAO,QAAQ,QAAQ,MAAS;AAAA,IAClC;AAAA,EACF,OAAO;AAEL,UAAM,UAAU;AAAA;AAAA,MAA0B;AAAA;AAC1C,YAAQ,MAAM,MAAM;AAAA,IAAC,CAAC;AACtB,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/build/utils/Utils.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/Utils.ts"],
|
|
4
|
-
"sourcesContent": ["import { nanoid } from 'nanoid';\nimport { type RoomException, type RoomMethodName } from '../errors/RoomExceptions.ts';\n\nimport { debugAndPrintError, debugMatchMaking } from '../Debug.ts';\n\nexport type Type<T> = new (...args: any[]) => T;\nexport type MethodName<T> = string & {\n [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never\n}[keyof T];\n\n/**\n * Utility type that extracts the return type of a method or the type of a property\n * from a given class/object type.\n *\n * - If the key is a method, returns the awaited return type of that method\n * - If the key is a property, returns the type of that property\n */\nexport type ExtractMethodOrPropertyType<\n TClass,\n TKey extends keyof TClass\n> = TClass[TKey] extends (...args: any[]) => infer R\n ? Awaited<R>\n : TClass[TKey];\n\n/**\n * Return type of `remoteRoomCall()`.\n *\n * Resolves to the method's awaited return type (or the property's type) when\n * the method name was captured as a literal type. Falls back to `any` when it\n * wasn't \u2014 e.g. `remoteRoomCall<MyRoom>(...)` with only the room type given:\n * TypeScript applies the `TMethod` default instead of inferring the literal\n * once an explicit type argument list is present (microsoft/TypeScript#26242).\n * Pass both type arguments (`remoteRoomCall<MyRoom, 'myMethod'>`) for a\n * precise return type.\n */\nexport type RemoteRoomCallReturn<\n TRoom,\n TMethod extends keyof TRoom\n> = keyof TRoom extends TMethod\n ? any\n : ExtractMethodOrPropertyType<TRoom, TMethod>;\n\n// remote room call timeouts\nexport const REMOTE_ROOM_SHORT_TIMEOUT = Number(process.env.COLYSEUS_PRESENCE_SHORT_TIMEOUT || 2000);\nexport const MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME = Number(process.env.COLYSEUS_MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME || 0.5);\n\n// a peer that removes this process's room listings leaves a receipt. this\n// process looks for it every INTERVAL (ms) and restores them. the TTL (seconds)\n// only bounds what dead processes leave behind.\nexport const SWEPT_CHECK_INTERVAL = Number(process.env.COLYSEUS_SWEPT_CHECK_INTERVAL || 5000);\nexport const SWEPT_RECEIPT_TTL = Number(process.env.COLYSEUS_SWEPT_RECEIPT_TTL || 600);\n\nexport function generateId(length: number = 9) {\n return nanoid(length);\n}\n\nexport function getBearerToken(authHeader: string) {\n return (authHeader && authHeader.startsWith(\"Bearer \") && authHeader.substring(7, authHeader.length)) || undefined;\n}\n\n// nodemon sends SIGUSR2 before reloading\n// (https://github.com/remy/nodemon#controlling-shutdown-of-your-script)\n//\nconst signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGUSR2'];\n\nexport function registerGracefulShutdown(callback: (err?: Error) => void) {\n /**\n * Gracefully shutdown on uncaught errors\n */\n process.on('uncaughtException', (err) => {\n debugAndPrintError(err);\n callback(err);\n });\n\n signals.forEach((signal) =>\n process.once(signal, () => callback()));\n}\n\nexport function retry<T = any>(\n cb: Function,\n maxRetries: number = 3,\n errorWhiteList: any[] = [],\n retries: number = 0,\n) {\n return new Promise<T>((resolve, reject) => {\n cb()\n .then(resolve)\n .catch((e: any) => {\n if (\n errorWhiteList.indexOf(e.constructor) !== -1 &&\n retries++ < maxRetries\n ) {\n setTimeout(() => {\n debugMatchMaking(\"retrying due to error (error: %s, retries: %s, maxRetries: %s)\", e.message, retries, maxRetries);\n retry<T>(cb, maxRetries, errorWhiteList, retries).\n then(resolve).\n catch((e2) => reject(e2));\n }, Math.floor(Math.random() * Math.pow(2, retries) * 400));\n\n } else {\n reject(e);\n }\n });\n });\n}\n\nexport function spliceOne(arr: any[], index: number): boolean {\n // manually splice availableRooms array\n // http://jsperf.com/manual-splice\n if (index === -1 || index >= arr.length) {\n return false;\n }\n\n const len = arr.length - 1;\n for (let i = index; i < len; i++) {\n arr[i] = arr[i + 1];\n }\n\n arr.length = len;\n return true;\n}\n\nexport class Deferred<T = any> {\n public promise: Promise<T>;\n\n public resolve: Function;\n public reject: Function;\n\n constructor(promise?: Promise<T>) {\n this.promise = promise ?? new Promise<T>((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n public then(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any) {\n return this.promise.then(onFulfilled, onRejected);\n }\n\n public catch(func: (value: any) => any) {\n return this.promise.catch(func);\n }\n\n static reject (reason?: any) {\n return new Deferred(Promise.reject(reason));\n }\n\n static resolve<T = any>(value?: T) {\n return new Deferred<T>(Promise.resolve(value));\n }\n\n}\n\nexport function merge(a: any, ...objs: any[]): any {\n for (let i = 0, len = objs.length; i < len; i++) {\n const b = objs[i];\n for (const key in b) {\n if (
|
|
5
|
-
"mappings": ";;;;;;;;AAAA,SAAS,cAAc;AACvB,OAAwD;AAExD,SAAS,oBAAoB,wBAAwB;AAwC9C,IAAM,4BAA4B,OAAO,QAAQ,IAAI,mCAAmC,GAAI;AAC5F,IAAM,uCAAuC,OAAO,QAAQ,IAAI,iDAAiD,GAAG;AAKpH,IAAM,uBAAuB,OAAO,QAAQ,IAAI,iCAAiC,GAAI;AACrF,IAAM,oBAAoB,OAAO,QAAQ,IAAI,8BAA8B,GAAG;AAE9E,SAAS,WAAW,SAAiB,GAAG;AAC7C,SAAO,OAAO,MAAM;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AM7B,YAAY,SAAsB;AAChC,SAAK,UAAU,WAAW,IAAI,QAAW,CAAC,SAAS,WAAW;AAC5D,WAAK,UAAU;AACf,WAAK,SAAS;AAAA,IAChB,CAAC;AAAA,EACH;AAAA,EAEO,KAAK,aAAiC,YAAmC;AAC9E,WAAO,KAAK,QAAQ,KAAK,aAAa,UAAU;AAAA,EAClD;AAAA,EAEO,MAAM,MAA2B;AACtC,WAAO,KAAK,QAAQ,MAAM,IAAI;AAAA,EAChC;AAAA,EAEA,OAAO,OAAQ,QAAc;AAC3B,WAAO,IAAI,UAAS,QAAQ,OAAO,MAAM,CAAC;AAAA,EAC5C;AAAA,EAEA,OAAO,QAAiB,OAAW;AACjC,WAAO,IAAI,UAAY,QAAQ,QAAQ,KAAK,CAAC;AAAA,EAC/C;AAEF;AAEO,SAAS,MAAM,MAAW,MAAkB;AACjD,WAAS,IAAI,GAAG,MAAM,KAAK,QAAQ,IAAI,KAAK,KAAK;AAC/C,UAAM,IAAI,KAAK,CAAC;AAChB,eAAW,OAAO,GAAG;
|
|
4
|
+
"sourcesContent": ["import { nanoid } from 'nanoid';\nimport { type RoomException, type RoomMethodName } from '../errors/RoomExceptions.ts';\n\nimport { debugAndPrintError, debugMatchMaking } from '../Debug.ts';\n\nexport type Type<T> = new (...args: any[]) => T;\nexport type MethodName<T> = string & {\n [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never\n}[keyof T];\n\n/**\n * Utility type that extracts the return type of a method or the type of a property\n * from a given class/object type.\n *\n * - If the key is a method, returns the awaited return type of that method\n * - If the key is a property, returns the type of that property\n */\nexport type ExtractMethodOrPropertyType<\n TClass,\n TKey extends keyof TClass\n> = TClass[TKey] extends (...args: any[]) => infer R\n ? Awaited<R>\n : TClass[TKey];\n\n/**\n * Return type of `remoteRoomCall()`.\n *\n * Resolves to the method's awaited return type (or the property's type) when\n * the method name was captured as a literal type. Falls back to `any` when it\n * wasn't \u2014 e.g. `remoteRoomCall<MyRoom>(...)` with only the room type given:\n * TypeScript applies the `TMethod` default instead of inferring the literal\n * once an explicit type argument list is present (microsoft/TypeScript#26242).\n * Pass both type arguments (`remoteRoomCall<MyRoom, 'myMethod'>`) for a\n * precise return type.\n */\nexport type RemoteRoomCallReturn<\n TRoom,\n TMethod extends keyof TRoom\n> = keyof TRoom extends TMethod\n ? any\n : ExtractMethodOrPropertyType<TRoom, TMethod>;\n\n// remote room call timeouts\nexport const REMOTE_ROOM_SHORT_TIMEOUT = Number(process.env.COLYSEUS_PRESENCE_SHORT_TIMEOUT || 2000);\nexport const MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME = Number(process.env.COLYSEUS_MAX_CONCURRENT_CREATE_ROOM_WAIT_TIME || 0.5);\n\n// a peer that removes this process's room listings leaves a receipt. this\n// process looks for it every INTERVAL (ms) and restores them. the TTL (seconds)\n// only bounds what dead processes leave behind.\nexport const SWEPT_CHECK_INTERVAL = Number(process.env.COLYSEUS_SWEPT_CHECK_INTERVAL || 5000);\nexport const SWEPT_RECEIPT_TTL = Number(process.env.COLYSEUS_SWEPT_RECEIPT_TTL || 600);\n\nexport function generateId(length: number = 9) {\n return nanoid(length);\n}\n\nexport function getBearerToken(authHeader: string) {\n return (authHeader && authHeader.startsWith(\"Bearer \") && authHeader.substring(7, authHeader.length)) || undefined;\n}\n\n// nodemon sends SIGUSR2 before reloading\n// (https://github.com/remy/nodemon#controlling-shutdown-of-your-script)\n//\nconst signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGUSR2'];\n\nexport function registerGracefulShutdown(callback: (err?: Error) => void) {\n /**\n * Gracefully shutdown on uncaught errors\n */\n process.on('uncaughtException', (err) => {\n debugAndPrintError(err);\n callback(err);\n });\n\n signals.forEach((signal) =>\n process.once(signal, () => callback()));\n}\n\nexport function retry<T = any>(\n cb: Function,\n maxRetries: number = 3,\n errorWhiteList: any[] = [],\n retries: number = 0,\n) {\n return new Promise<T>((resolve, reject) => {\n cb()\n .then(resolve)\n .catch((e: any) => {\n if (\n errorWhiteList.indexOf(e.constructor) !== -1 &&\n retries++ < maxRetries\n ) {\n setTimeout(() => {\n debugMatchMaking(\"retrying due to error (error: %s, retries: %s, maxRetries: %s)\", e.message, retries, maxRetries);\n retry<T>(cb, maxRetries, errorWhiteList, retries).\n then(resolve).\n catch((e2) => reject(e2));\n }, Math.floor(Math.random() * Math.pow(2, retries) * 400));\n\n } else {\n reject(e);\n }\n });\n });\n}\n\nexport function spliceOne(arr: any[], index: number): boolean {\n // manually splice availableRooms array\n // http://jsperf.com/manual-splice\n if (index === -1 || index >= arr.length) {\n return false;\n }\n\n const len = arr.length - 1;\n for (let i = index; i < len; i++) {\n arr[i] = arr[i + 1];\n }\n\n arr.length = len;\n return true;\n}\n\nexport class Deferred<T = any> {\n public promise: Promise<T>;\n\n public resolve: Function;\n public reject: Function;\n\n constructor(promise?: Promise<T>) {\n this.promise = promise ?? new Promise<T>((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n public then(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any) {\n return this.promise.then(onFulfilled, onRejected);\n }\n\n public catch(func: (value: any) => any) {\n return this.promise.catch(func);\n }\n\n static reject (reason?: any) {\n return new Deferred(Promise.reject(reason));\n }\n\n static resolve<T = any>(value?: T) {\n return new Deferred<T>(Promise.resolve(value));\n }\n\n}\n\nexport function merge(a: any, ...objs: any[]): any {\n for (let i = 0, len = objs.length; i < len; i++) {\n const b = objs[i];\n for (const key in b) {\n // JSON.parse keeps \"__proto__\" as an own key: assigning it replaces a's prototype\n if (key !== \"__proto__\" && Object.hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n }\n return a;\n}\n\nexport function wrapTryCatch(\n method: Function,\n onError: (error: RoomException, methodName: RoomMethodName) => void,\n exceptionClass: Type<RoomException>,\n methodName: RoomMethodName,\n rethrow: boolean = false,\n ...additionalErrorArgs: any[]\n) {\n return (...args: any[]) => {\n try {\n const result = method(...args);\n if (typeof (result?.catch) === \"function\") {\n return result.catch((e: Error) => {\n onError(new exceptionClass(e, e.message, ...args, ...additionalErrorArgs), methodName);\n if (rethrow) { throw e; }\n });\n }\n return result;\n } catch (e: any) {\n onError(new exceptionClass(e, e.message, ...args, ...additionalErrorArgs), methodName);\n if (rethrow) { throw e; }\n }\n };\n}\n\n/**\n * Dynamically import a module using either require() or import()\n * based on the current module system (CJS vs ESM).\n *\n * This avoids double-loading packages when running in mixed ESM/CJS environments.\n * Errors are silently caught - await the promise and handle errors at usage site.\n */\nexport function dynamicImport<T = any>(moduleName: string): Promise<T> {\n // __dirname exists in CJS but not in ESM\n if (\n typeof __dirname !== 'undefined' &&\n // @ts-ignore\n typeof (Bun) === 'undefined' // prevent bun from loading CJS modules\n ) {\n // CJS context - use require()\n try {\n return Promise.resolve(require(moduleName));\n } catch (e: any) {\n // If the error is not a MODULE_NOT_FOUND error, reject with the error.\n if (e.code !== 'MODULE_NOT_FOUND') {\n return Promise.reject(e);\n }\n return Promise.resolve(undefined);\n }\n } else {\n // ESM context - use import()\n const promise = import(/* @vite-ignore */ moduleName);\n promise.catch(() => {}); // prevent unhandled rejection warnings\n return promise;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAAA,SAAS,cAAc;AACvB,OAAwD;AAExD,SAAS,oBAAoB,wBAAwB;AAwC9C,IAAM,4BAA4B,OAAO,QAAQ,IAAI,mCAAmC,GAAI;AAC5F,IAAM,uCAAuC,OAAO,QAAQ,IAAI,iDAAiD,GAAG;AAKpH,IAAM,uBAAuB,OAAO,QAAQ,IAAI,iCAAiC,GAAI;AACrF,IAAM,oBAAoB,OAAO,QAAQ,IAAI,8BAA8B,GAAG;AAE9E,SAAS,WAAW,SAAiB,GAAG;AAC7C,SAAO,OAAO,MAAM;AACtB;AAEO,SAAS,eAAe,YAAoB;AACjD,SAAQ,cAAc,WAAW,WAAW,SAAS,KAAK,WAAW,UAAU,GAAG,WAAW,MAAM,KAAM;AAC3G;AAKA,IAAM,UAA4B,CAAC,UAAU,WAAW,SAAS;AA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AAQ,QAAS,aACjB;AAEA,QAAI;AACF,aAAO,QAAQ,QAAQ,UAAQ,UAAU,CAAC;AAAA,IAC5C,SAAS,GAAQ;AAEf,UAAI,EAAE,SAAS,oBAAoB;AACjC,eAAO,QAAQ,OAAO,CAAC;AAAA,MACzB;AACA,aAAO,QAAQ,QAAQ,MAAS;AAAA,IAClC;AAAA,EACF,OAAO;AAEL,UAAM,UAAU;AAAA;AAAA,MAA0B;AAAA;AAC1C,YAAQ,MAAM,MAAM;AAAA,IAAC,CAAC;AACtB,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@colyseus/core",
|
|
3
|
-
"version": "0.17.
|
|
3
|
+
"version": "0.17.55",
|
|
4
4
|
"description": "Multiplayer Framework for Node.js.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"input": "./src/index.ts",
|
|
@@ -46,30 +46,30 @@
|
|
|
46
46
|
"node": ">= 22.x"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
+
"@colyseus/shared-types": "^0.17.6",
|
|
49
50
|
"@colyseus/msgpackr": "^1.11.3",
|
|
50
51
|
"@colyseus/timer": "^2.0.0",
|
|
51
52
|
"@standard-schema/spec": "^1.0.0",
|
|
52
53
|
"debug": "^4.3.4",
|
|
53
54
|
"nanoid": "^3.3.11",
|
|
54
55
|
"@colyseus/greeting-banner": "^3.0.8",
|
|
55
|
-
"@colyseus/better-call": "^1.3.1"
|
|
56
|
-
"@colyseus/shared-types": "^0.17.6"
|
|
56
|
+
"@colyseus/better-call": "^1.3.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@colyseus/schema": "^4.0.7",
|
|
60
60
|
"express": "^5.0.0",
|
|
61
61
|
"vitest": "^3.1.1",
|
|
62
|
-
"@colyseus/
|
|
63
|
-
"@colyseus/redis-
|
|
64
|
-
"@colyseus/
|
|
62
|
+
"@colyseus/redis-presence": "^0.17.9",
|
|
63
|
+
"@colyseus/redis-driver": "^0.17.9",
|
|
64
|
+
"@colyseus/tools": "^0.17.22"
|
|
65
65
|
},
|
|
66
66
|
"peerDependencies": {
|
|
67
|
+
"@colyseus/ws-transport": "0.17.x",
|
|
67
68
|
"@colyseus/schema": "^4.0.7",
|
|
68
69
|
"@pm2/io": "^6.1.0",
|
|
69
70
|
"express": "^4.16.0 || ^5.0.0",
|
|
70
71
|
"zod": "^4.1.12",
|
|
71
|
-
"@colyseus/better-call": "^1.3.1"
|
|
72
|
-
"@colyseus/ws-transport": "^0.17.13"
|
|
72
|
+
"@colyseus/better-call": "^1.3.1"
|
|
73
73
|
},
|
|
74
74
|
"peerDependenciesMeta": {
|
|
75
75
|
"@colyseus/ws-transport": {
|
package/src/Room.ts
CHANGED
|
@@ -678,7 +678,8 @@ export class Room<T extends RoomOptions = RoomOptions> {
|
|
|
678
678
|
|
|
679
679
|
} else {
|
|
680
680
|
for (const field in meta) {
|
|
681
|
-
|
|
681
|
+
// JSON.parse keeps "__proto__" as an own key: assigning it replaces metadata's prototype
|
|
682
|
+
if (field === "__proto__" || !Object.hasOwn(meta, field)) { continue; }
|
|
682
683
|
this._listing.metadata[field] = meta[field];
|
|
683
684
|
}
|
|
684
685
|
|
|
@@ -1374,6 +1375,7 @@ export class Room<T extends RoomOptions = RoomOptions> {
|
|
|
1374
1375
|
}
|
|
1375
1376
|
|
|
1376
1377
|
const cleanup = () => {
|
|
1378
|
+
clearTimeout(this._reservedSeatTimeouts[sessionId]);
|
|
1377
1379
|
delete this._reconnections[reconnectionToken];
|
|
1378
1380
|
delete this._reservedSeats[sessionId];
|
|
1379
1381
|
delete this._reservedSeatTimeouts[sessionId];
|
|
@@ -1389,7 +1391,6 @@ export class Room<T extends RoomOptions = RoomOptions> {
|
|
|
1389
1391
|
previousClient.state = ClientState.RECONNECTED;
|
|
1390
1392
|
previousClient.ref = newClient.ref;
|
|
1391
1393
|
previousClient.reconnectionToken = newClient.reconnectionToken;
|
|
1392
|
-
clearTimeout(this._reservedSeatTimeouts[sessionId]);
|
|
1393
1394
|
|
|
1394
1395
|
}, () => {
|
|
1395
1396
|
this.resetAutoDisposeTimeout();
|
|
@@ -1589,6 +1590,10 @@ export class Room<T extends RoomOptions = RoomOptions> {
|
|
|
1589
1590
|
this._autoDisposeTimeout = undefined;
|
|
1590
1591
|
}
|
|
1591
1592
|
|
|
1593
|
+
for (const sessionId in this._reservedSeatTimeouts) {
|
|
1594
|
+
clearTimeout(this._reservedSeatTimeouts[sessionId]);
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1592
1597
|
// clear all timeouts/intervals + force to stop ticking
|
|
1593
1598
|
this.clock.clear();
|
|
1594
1599
|
this.clock.stop();
|
|
@@ -25,7 +25,7 @@ export class Query<T extends IRoomCache> {
|
|
|
25
25
|
return rooms.sort((room1: T, room2: T) => {
|
|
26
26
|
for (const field in this.sortOptions) {
|
|
27
27
|
const direction = this.sortOptions[field];
|
|
28
|
-
if (
|
|
28
|
+
if (Object.hasOwn(room1, field)) {
|
|
29
29
|
/**
|
|
30
30
|
* IRoomCache field
|
|
31
31
|
*/
|
|
@@ -37,7 +37,7 @@ export class Query<T extends IRoomCache> {
|
|
|
37
37
|
if (room1[field] > room2[field]) { return -1; }
|
|
38
38
|
if (room1[field] < room2[field]) { return 1; }
|
|
39
39
|
}
|
|
40
|
-
} else if (room1.metadata
|
|
40
|
+
} else if (room1.metadata && Object.hasOwn(room1.metadata, field)) {
|
|
41
41
|
/**
|
|
42
42
|
* metadata field
|
|
43
43
|
*/
|
|
@@ -57,13 +57,13 @@ export class Query<T extends IRoomCache> {
|
|
|
57
57
|
private applyFilter(rooms: T[], conditions: any): T[] {
|
|
58
58
|
return rooms.filter(((room) => {
|
|
59
59
|
for (const field in conditions) {
|
|
60
|
-
if (
|
|
60
|
+
if (Object.hasOwn(conditions, field)) {
|
|
61
61
|
// Check if field exists in room (IRoomCache base fields)
|
|
62
|
-
if (
|
|
62
|
+
if (Object.hasOwn(room, field)) {
|
|
63
63
|
if (room[field] !== conditions[field]) {
|
|
64
64
|
return false;
|
|
65
65
|
}
|
|
66
|
-
} else if (room.metadata
|
|
66
|
+
} else if (room.metadata && Object.hasOwn(room.metadata, field)) {
|
|
67
67
|
// Check if field exists in metadata
|
|
68
68
|
if (room.metadata[field] !== conditions[field]) {
|
|
69
69
|
return false;
|
|
@@ -158,7 +158,7 @@ export class RegisteredHandler<
|
|
|
158
158
|
const field = String(arr[i]);
|
|
159
159
|
|
|
160
160
|
// Handle regular (non-metadata) fields
|
|
161
|
-
if (
|
|
161
|
+
if (Object.hasOwn(options, field)) {
|
|
162
162
|
if (INVALID_OPTION_KEYS.indexOf(field as any) !== -1) {
|
|
163
163
|
logger.warn(`option "${field}" has internal usage and is going to be ignored.`);
|
|
164
164
|
} else {
|
package/src/utils/Utils.ts
CHANGED
|
@@ -155,7 +155,8 @@ export function merge(a: any, ...objs: any[]): any {
|
|
|
155
155
|
for (let i = 0, len = objs.length; i < len; i++) {
|
|
156
156
|
const b = objs[i];
|
|
157
157
|
for (const key in b) {
|
|
158
|
-
|
|
158
|
+
// JSON.parse keeps "__proto__" as an own key: assigning it replaces a's prototype
|
|
159
|
+
if (key !== "__proto__" && Object.hasOwn(b, key)) {
|
|
159
160
|
a[key] = b[key];
|
|
160
161
|
}
|
|
161
162
|
}
|