{"id":22305640,"url":"https://github.com/starwards/colyseus-events","last_synced_at":"2025-07-29T04:32:26.598Z","repository":{"id":40590434,"uuid":"507580282","full_name":"starwards/colyseus-events","owner":"starwards","description":"Generate json-patch events from colyseus state","archived":false,"fork":false,"pushed_at":"2024-03-18T16:18:12.000Z","size":353,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-11-12T18:54:09.132Z","etag":null,"topics":["colyseus","events","json-patch","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"amir-arad/colyseus-mobx","license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/starwards.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-06-26T13:21:35.000Z","updated_at":"2024-03-17T08:00:27.000Z","dependencies_parsed_at":"2023-01-19T20:30:31.163Z","dependency_job_id":null,"html_url":"https://github.com/starwards/colyseus-events","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/starwards%2Fcolyseus-events","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/starwards%2Fcolyseus-events/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/starwards%2Fcolyseus-events/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/starwards%2Fcolyseus-events/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/starwards","download_url":"https://codeload.github.com/starwards/colyseus-events/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227981890,"owners_count":17850920,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["colyseus","events","json-patch","typescript"],"created_at":"2024-12-03T19:12:34.302Z","updated_at":"2024-12-03T19:12:35.068Z","avatar_url":"https://github.com/starwards.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# colyseus-events\n\nGenerate json-patch events from [colyseus](https://www.colyseus.io/) state.\n```typescript\nimport { wireEvents } from 'colyseus-events';\nconst room: Room\u003cGameState\u003e = await client.joinOrCreate(\"game\");\nconst { events } = wireEvents(room.state, new EventEmitter());\n// `events` will emit json-patch events whenever the room state changes\n```\n\n## version support \n\nDue to breaking API changes in Colyseus, this version only supports Colyseus 0.15 and above (@colyseus/schema 2.x)\n\n## Pending support\n\nThe schema types new to Colyseus 0.14 (`CollectionSchema` and `SetSchema`) are not yet supported. please open an issue if you would like to see them supported.\n\n## Installation\n`npm install colyseus-events --save`\n\n## How to use\n### wireEvents\nImport `wireEvents` and call it once when connecting to a room on the client side: \n```typescript\nimport { wireEvents } from 'colyseus-events';\nconst room: Room\u003cGameState\u003e = await client.joinOrCreate(\"game\");\nconst { events } = wireEvents(room.state, new EventEmitter());\n// `events` will emit json-patch events whenever the room state changes\n```\nthen you can wire listeners to `events` using the [JSON-pointer](https://github.com/janl/node-jsonpointer) of target field as event name.\n\n### customWireEvents\nTo change the behavior for parts or all of your state, use `customWireEvents` to produce your own version of `wireEvents`:\n```typescript\nimport { customWireEvents, coreVisitors} from 'colyseus-events';\nconst special = {\n    visit: (traverse: Traverse, state: Container, events: Events, jsonPath: string): boolean =\u003e { /* see Visitor implementation below*/},\n};\nconst wireEvents = customWireEvents([ special, ...coreVisitors]);\nconst room: Room\u003cGameState\u003e = await client.joinOrCreate(\"game\");\nconst { events } = wireEvents(room.state, new EventEmitter());\n// `events` will emit json-patch events whenever the room state changes\n```\n`customWireEvents` accepts a single argument, a collection of `Visitor` objects, and returns afunctyion compatible with the default `wireEvents`. In fact, the default `wireEvents` function is itself the result `customWireEvents` when using `coreVisitors` as the argument. it is defined in [wire-events.ts](src/wire-events.ts#L42) by the following line:\n```typescript\nexport const wireEvents = customWireEvents(coreVisitors);\n```\nThe order of the visitors is crucial: they are executed as a fallback chain: the first visitor to return `true` will stop the chain and prevent later visitors from wiring the same state. So be sure to order them by specificity: the more specific handlers should first check for their use case before the generic visitors, and `coreVisitors` should be the last visitors.\n#### Visitor implementation\nA visitor must implement a single method, `visit`. This method should:\n1. Check if it is going to handle the state object, and return `false` if not.\n2. Call the traverse function for each child member of the state.\n3. Hook on the state's [Client-side Callbacks](https://docs.colyseus.io/state/schema-callbacks/#state-sync-client-side-callbacks). Make sure to only hook once per state object. This may become trickey with Proxies, and 'stickey' callbacks.\n4. For every new value in each child member of the state, call the traverse function and emit the events using the event emitter.\nExamples can be found in [core-visitors.ts](src/core-visitors.ts). Here is a brief of the visitor that handles `MapSchema`:\n```typescript\n{\n    \n    visit: (traverse: Traverse, state: Container, events: Events, namespace: string) =\u003e {\n            // Check if it is going to handle the state object, and return `false` if not.\n            if (!(state instanceof MapSchema)) {\n                return false;\n            }\n            // Hook on new elements\n            state.onAdd = (value: Colyseus, field) =\u003e {\n                const fieldNamespace = `${namespace}/${field}`; // path to the new element\n                events.emit(namespace, Add(fieldNamespace, value)); // emit the add event\n                traverse(value, events, fieldNamespace); // call the traverse function on the new value\n            };\n            \n            ...\n\n            // finally return true. this will break the visitors fallback chain and complete the wiring for this object.\n            return true;\n        }\n}\n```\nIn addition to the code above, there ais also code to handle duplicate events and keeping only one registration per state object.\n## Examples\n\nFor example, given the room state:\n```typescript\nexport class Inner extends Schema {\n    @type('uint8') public x = 0;\n    @type('uint8') public y = 0;\n}\nexport class GameState extends Schema {\n    @type('uint8') public foo = 0;\n    @type(Inner) public bar = new Inner();\n    @type(['uint8']) public numbersArray = new ArraySchema\u003cnumber\u003e();\n    @type({ map: 'uint8' }) public mapNumbers = new MapSchema\u003cnumber\u003e();\n}\n```\n### changing values\nwhen changing a value in Schema or collection (ArraySchema or MapSchema), an event will be emitted. The name of the event will be the [JSON-pointer](https://github.com/janl/node-jsonpointer) describing the location of the property. The event value will be a [\"replace\" JSON Patch](https://jsonpatch.com/#replace) corresponding with the change.\nFor example:\n - when the server executes: `room.state.foo = 1` an event named `'/foo'` will be emitted with value `{ op: 'replace', path: '/foo', value: 1 }`\n - when the server executes: `room.numbersArray[0] = 1` (assuming numbersArray had a previous value at index 0) an event named `'/numbersArray/1'` will be emitted with value `{ op: 'replace', path: '/numbersArray/1', value: 1 }`\n - when the server executes: `room.mapNumbers.set('F00', 1)` (assuming mapNumbers had a previous value at key `F00`) an event named `'/mapNumbers/F00'` will be emitted with value `{ op: 'replace', path: '/mapNumbers/F00', value: 1 }`\n - when the server executes: `room.state.bar.x = 1` an event named `'/bar/x'` will be emitted with value `{ op: 'replace', path: '/bar/x', value: 1 }`\n - when the server executes: `room.state.bar = new Inner()` an event named `'/bar'` will be emitted with value `{ op: 'replace', path: '/bar', value: {{the actual object in state.bar }} }`\n\n...and so on.\n### adding and removing elements in collections\nwhen adding or removing elements in a collection (ArraySchema or MapSchema), an event will be also be emitted. The name of the event will be the [JSON-pointer](https://github.com/janl/node-jsonpointer) describing the location of the **container**. The event value will be a [\"add\"](https://jsonpatch.com/#add) or [\"remove\"](https://jsonpatch.com/#remove) JSON Patch corresponding with the change. the `path` in the event value will point to the location of the **element** that was added or removed.\nFor example:\n - when the server executes: `room.numbersArray.push(1)` an event named `'/numbersArray'` will be triggered with value `{ op: 'add', path: '/numbersArray/0', value: 1 }`\n - when the server executes: `room.numbersArray.pop()` an event named `'/numbersArray'` will be triggered with value `{ op: 'remove', path: '/numbersArray/0' }`\n - when the server executes: `room.mapNumbers.set('F00', 1)` an event named `'/mapNumbers'` will be triggered with value `{ op: 'add', path: '/mapNumbers/F00', value: 1 }`\n - when the server executes: `room.mapNumbers.delete('F00')` an event named `'/mapNumbers'` will be triggered with value `{ op: 'remove', path: '/mapNumbers/F00' }`\n\n...and so on.\n\nYou are welcomed to explore the tests in the github repo for more examples.\n## Contributor instructions\n\n### Installing workspace\n\nto install a development environment, you need to have node.js git installd.\nThen, `git clone` this repo locally and run:\n```\n$ npm install\n$ npm test\n```\nand that's it, you've just installed the development environment!\n\nThis project is written with [VSCode](https://code.visualstudio.com/) in mind. specifically configured for these extensions: [dbaeumer.vscode-eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint), [esbenp.prettier-vscode](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode).\n\n### test\n\n`npm run test`\n\nexecute all tests.\n\n### clean\n\n`npm run clean`\n\nRemoves any built code and any built executables.\n\n### build\n\n`npm run build`\n\nCleans, then builds the library.\n\nYour built code will be in the `./dist/` directory.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstarwards%2Fcolyseus-events","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstarwards%2Fcolyseus-events","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstarwards%2Fcolyseus-events/lists"}