migrate to Protobuf ES

This commit is contained in:
seavor 2026-04-13 15:03:57 -05:00
parent 68e22d22bf
commit fd55f4fb7f
133 changed files with 1745 additions and 1621 deletions

View file

@ -8,6 +8,7 @@
# generated ./src files
/src/proto-files.json
/src/server-props.json
/src/generated/
# testing
/coverage

8
webclient/buf.gen.yaml Normal file
View file

@ -0,0 +1,8 @@
version: v2
inputs:
- directory: ../libcockatrice_protocol/libcockatrice/protocol/pb
plugins:
- local: protoc-gen-es
out: src/generated/proto
opt:
- target=ts

View file

@ -8,6 +8,7 @@
"name": "webclient",
"version": "1.0.0",
"dependencies": {
"@bufbuild/protobuf": "^2.11.0",
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.5.1",
@ -39,6 +40,8 @@
"rxjs": "^7.5.4"
},
"devDependencies": {
"@bufbuild/buf": "^1.67.0",
"@bufbuild/protoc-gen-es": "^2.11.0",
"@mui/types": "^7.1.3",
"@testing-library/jest-dom": "^6.4.0",
"@testing-library/react": "^13.4.0",
@ -433,6 +436,207 @@
"dev": true,
"license": "MIT"
},
"node_modules/@bufbuild/buf": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf/-/buf-1.67.0.tgz",
"integrity": "sha512-BLfgGmNFiHM79PcaafFNiP/+xxbdyFp1neDDdJd6R0tu7McO+WgJHM6vyNYRm7vXOSgO1uUPE4X3YFdBgcWk2Q==",
"dev": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"bin": {
"buf": "bin/buf",
"protoc-gen-buf-breaking": "bin/protoc-gen-buf-breaking",
"protoc-gen-buf-lint": "bin/protoc-gen-buf-lint"
},
"engines": {
"node": ">=12"
},
"optionalDependencies": {
"@bufbuild/buf-darwin-arm64": "1.67.0",
"@bufbuild/buf-darwin-x64": "1.67.0",
"@bufbuild/buf-linux-aarch64": "1.67.0",
"@bufbuild/buf-linux-armv7": "1.67.0",
"@bufbuild/buf-linux-x64": "1.67.0",
"@bufbuild/buf-win32-arm64": "1.67.0",
"@bufbuild/buf-win32-x64": "1.67.0"
}
},
"node_modules/@bufbuild/buf-darwin-arm64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-darwin-arm64/-/buf-darwin-arm64-1.67.0.tgz",
"integrity": "sha512-9h/1E2FNCSIt9m4wriGiXt8gHrg8VBOOpmUPVr68axZxb17krPQrIZBPsx05yNpbyvSrPj26/jO2aoqpZsG1vw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@bufbuild/buf-darwin-x64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-darwin-x64/-/buf-darwin-x64-1.67.0.tgz",
"integrity": "sha512-9kNu0JBR+TQvxCD6NBooy03g8sLNZGEd0umkWHzdO/05HuV/J6GecMGx1kJ2MYlZQHM4/MljfIuYQUblP1nP4A==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@bufbuild/buf-linux-aarch64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-linux-aarch64/-/buf-linux-aarch64-1.67.0.tgz",
"integrity": "sha512-hlA20Oot20nW/9CzPBMPPPMfUarKvzqni+Njgrw8T43IFoQWQv8iIRoWWOgOQTGCm4PmjYwiojzEHOEaaKrzTg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@bufbuild/buf-linux-armv7": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-linux-armv7/-/buf-linux-armv7-1.67.0.tgz",
"integrity": "sha512-hO9FEEtloITNaxW89rzKUjAsgnX1+rth7IZbK0Z+ohatXdanYg7Kv66yWffytaYf2iHltTbY6W/H4C3x0Uimbg==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@bufbuild/buf-linux-x64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-linux-x64/-/buf-linux-x64-1.67.0.tgz",
"integrity": "sha512-KBOWZ0NbhJSfXLM3JEX2AEs32jyHvTKD7wkIYudqOTxPUqwM1MXUg7m2Xw5nP1pcKH4RKS5HFijPMeOW/XUQ8Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@bufbuild/buf-win32-arm64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-win32-arm64/-/buf-win32-arm64-1.67.0.tgz",
"integrity": "sha512-ARGPwOv0lkUp3FU7bUMpYzqoJInx2qkk1ECBEC9XZMnRKmhCbyzmBoBKChBBJhEyDFdzPivhjg//zk5AlQ3bFA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@bufbuild/buf-win32-x64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-win32-x64/-/buf-win32-x64-1.67.0.tgz",
"integrity": "sha512-x9fkxEbjb2U4petBbESvNx+sfSQJONJxKOQzPfEKALksqRlvh7ktoHrYbygErnRZBSTNgrXzAqFI1GxMGEGSLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@bufbuild/protobuf": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.11.0.tgz",
"integrity": "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==",
"license": "(Apache-2.0 AND BSD-3-Clause)"
},
"node_modules/@bufbuild/protoc-gen-es": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protoc-gen-es/-/protoc-gen-es-2.11.0.tgz",
"integrity": "sha512-VzQuwEQDXipbZ1soWUuAWm1Z0C3B/IDWGeysnbX6ogJ6As91C2mdvAND/ekQ4YIWgen4d5nqLfIBOWLqCCjYUA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@bufbuild/protobuf": "2.11.0",
"@bufbuild/protoplugin": "2.11.0"
},
"bin": {
"protoc-gen-es": "bin/protoc-gen-es"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@bufbuild/protobuf": "2.11.0"
},
"peerDependenciesMeta": {
"@bufbuild/protobuf": {
"optional": true
}
}
},
"node_modules/@bufbuild/protoplugin": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protoplugin/-/protoplugin-2.11.0.tgz",
"integrity": "sha512-lyZVNFUHArIOt4W0+dwYBe5GBwbKzbOy8ObaloEqsw9Mmiwv2O48TwddDoHN4itylC+BaEGqFdI1W8WQt2vWJQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@bufbuild/protobuf": "2.11.0",
"@typescript/vfs": "^1.6.2",
"typescript": "5.4.5"
}
},
"node_modules/@bufbuild/protoplugin/node_modules/typescript": {
"version": "5.4.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/@csstools/color-helpers": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
@ -2543,6 +2747,19 @@
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript/vfs": {
"version": "1.6.4",
"resolved": "https://registry.npmjs.org/@typescript/vfs/-/vfs-1.6.4.tgz",
"integrity": "sha512-PJFXFS4ZJKiJ9Qiuix6Dz/OwEIqHD7Dme1UwZhTK11vR+5dqW2ACbdndWQexBzCx+CPuMe5WBYQWCsFyGlQLlQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.4.3"
},
"peerDependencies": {
"typescript": "*"
}
},
"node_modules/@ungap/structured-clone": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@ -3254,11 +3471,12 @@
}
},
"node_modules/debug": {
"version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "2.1.2"
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
@ -5369,9 +5587,10 @@
"license": "MIT"
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.8",
@ -7649,6 +7868,104 @@
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true
},
"@bufbuild/buf": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf/-/buf-1.67.0.tgz",
"integrity": "sha512-BLfgGmNFiHM79PcaafFNiP/+xxbdyFp1neDDdJd6R0tu7McO+WgJHM6vyNYRm7vXOSgO1uUPE4X3YFdBgcWk2Q==",
"dev": true,
"requires": {
"@bufbuild/buf-darwin-arm64": "1.67.0",
"@bufbuild/buf-darwin-x64": "1.67.0",
"@bufbuild/buf-linux-aarch64": "1.67.0",
"@bufbuild/buf-linux-armv7": "1.67.0",
"@bufbuild/buf-linux-x64": "1.67.0",
"@bufbuild/buf-win32-arm64": "1.67.0",
"@bufbuild/buf-win32-x64": "1.67.0"
}
},
"@bufbuild/buf-darwin-arm64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-darwin-arm64/-/buf-darwin-arm64-1.67.0.tgz",
"integrity": "sha512-9h/1E2FNCSIt9m4wriGiXt8gHrg8VBOOpmUPVr68axZxb17krPQrIZBPsx05yNpbyvSrPj26/jO2aoqpZsG1vw==",
"dev": true,
"optional": true
},
"@bufbuild/buf-darwin-x64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-darwin-x64/-/buf-darwin-x64-1.67.0.tgz",
"integrity": "sha512-9kNu0JBR+TQvxCD6NBooy03g8sLNZGEd0umkWHzdO/05HuV/J6GecMGx1kJ2MYlZQHM4/MljfIuYQUblP1nP4A==",
"dev": true,
"optional": true
},
"@bufbuild/buf-linux-aarch64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-linux-aarch64/-/buf-linux-aarch64-1.67.0.tgz",
"integrity": "sha512-hlA20Oot20nW/9CzPBMPPPMfUarKvzqni+Njgrw8T43IFoQWQv8iIRoWWOgOQTGCm4PmjYwiojzEHOEaaKrzTg==",
"dev": true,
"optional": true
},
"@bufbuild/buf-linux-armv7": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-linux-armv7/-/buf-linux-armv7-1.67.0.tgz",
"integrity": "sha512-hO9FEEtloITNaxW89rzKUjAsgnX1+rth7IZbK0Z+ohatXdanYg7Kv66yWffytaYf2iHltTbY6W/H4C3x0Uimbg==",
"dev": true,
"optional": true
},
"@bufbuild/buf-linux-x64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-linux-x64/-/buf-linux-x64-1.67.0.tgz",
"integrity": "sha512-KBOWZ0NbhJSfXLM3JEX2AEs32jyHvTKD7wkIYudqOTxPUqwM1MXUg7m2Xw5nP1pcKH4RKS5HFijPMeOW/XUQ8Q==",
"dev": true,
"optional": true
},
"@bufbuild/buf-win32-arm64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-win32-arm64/-/buf-win32-arm64-1.67.0.tgz",
"integrity": "sha512-ARGPwOv0lkUp3FU7bUMpYzqoJInx2qkk1ECBEC9XZMnRKmhCbyzmBoBKChBBJhEyDFdzPivhjg//zk5AlQ3bFA==",
"dev": true,
"optional": true
},
"@bufbuild/buf-win32-x64": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@bufbuild/buf-win32-x64/-/buf-win32-x64-1.67.0.tgz",
"integrity": "sha512-x9fkxEbjb2U4petBbESvNx+sfSQJONJxKOQzPfEKALksqRlvh7ktoHrYbygErnRZBSTNgrXzAqFI1GxMGEGSLQ==",
"dev": true,
"optional": true
},
"@bufbuild/protobuf": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.11.0.tgz",
"integrity": "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ=="
},
"@bufbuild/protoc-gen-es": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protoc-gen-es/-/protoc-gen-es-2.11.0.tgz",
"integrity": "sha512-VzQuwEQDXipbZ1soWUuAWm1Z0C3B/IDWGeysnbX6ogJ6As91C2mdvAND/ekQ4YIWgen4d5nqLfIBOWLqCCjYUA==",
"dev": true,
"requires": {
"@bufbuild/protobuf": "2.11.0",
"@bufbuild/protoplugin": "2.11.0"
}
},
"@bufbuild/protoplugin": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protoplugin/-/protoplugin-2.11.0.tgz",
"integrity": "sha512-lyZVNFUHArIOt4W0+dwYBe5GBwbKzbOy8ObaloEqsw9Mmiwv2O48TwddDoHN4itylC+BaEGqFdI1W8WQt2vWJQ==",
"dev": true,
"requires": {
"@bufbuild/protobuf": "2.11.0",
"@typescript/vfs": "^1.6.2",
"typescript": "5.4.5"
},
"dependencies": {
"typescript": {
"version": "5.4.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
"dev": true
}
}
},
"@csstools/color-helpers": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
@ -8911,6 +9228,15 @@
"eslint-visitor-keys": "^3.3.0"
}
},
"@typescript/vfs": {
"version": "1.6.4",
"resolved": "https://registry.npmjs.org/@typescript/vfs/-/vfs-1.6.4.tgz",
"integrity": "sha512-PJFXFS4ZJKiJ9Qiuix6Dz/OwEIqHD7Dme1UwZhTK11vR+5dqW2ACbdndWQexBzCx+CPuMe5WBYQWCsFyGlQLlQ==",
"dev": true,
"requires": {
"debug": "^4.4.3"
}
},
"@ungap/structured-clone": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@ -9403,11 +9729,11 @@
}
},
"debug": {
"version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"requires": {
"ms": "2.1.2"
"ms": "^2.1.3"
}
},
"decimal.js": {
@ -10927,9 +11253,9 @@
}
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"nanoid": {
"version": "3.3.8",

View file

@ -14,9 +14,11 @@
"lint:fix": "eslint src/**/*.{ts,tsx} --fix",
"golden": "npm run lint && npm run test",
"prepare": "cd .. && husky install",
"translate": "node prebuild.js -i18nOnly"
"translate": "node prebuild.js -i18nOnly",
"proto:generate": "npx buf generate"
},
"dependencies": {
"@bufbuild/protobuf": "^2.11.0",
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.5.1",
@ -32,7 +34,6 @@
"intl-messageformat": "^10.2.1",
"lodash": "^4.17.21",
"prop-types": "^15.8.1",
"protobufjs": "^7.2.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-final-form": "^6.5.8",
@ -48,6 +49,8 @@
"rxjs": "^7.5.4"
},
"devDependencies": {
"@bufbuild/buf": "^1.67.0",
"@bufbuild/protoc-gen-es": "^2.11.0",
"@mui/types": "^7.1.3",
"@testing-library/jest-dom": "^6.4.0",
"@testing-library/react": "^13.4.0",

View file

@ -6,13 +6,10 @@ const exec = util.promisify(require('child_process').exec);
const ROOT_DIR = './src';
const PUBLIC_DIR = './public';
const protoFilesDir = `${PUBLIC_DIR}/pb`;
const i18nDefaultFile = `${ROOT_DIR}/i18n-default.json`;
const serverPropsFile = `${ROOT_DIR}/server-props.json`;
const masterProtoFile = `${ROOT_DIR}/proto-files.json`;
const sharedFiles = [
['../libcockatrice_protocol/libcockatrice/protocol/pb', protoFilesDir],
['../cockatrice/resources/countries', `${ROOT_DIR}/images/countries`],
];
@ -26,10 +23,8 @@ const i18nOnly = process.argv.indexOf('-i18nOnly') > -1;
return;
}
// make sure these files finish copying before master file is created
await copySharedFiles();
await createMasterProtoFile();
await createServerProps();
await createI18NDefault();
})();
@ -43,19 +38,6 @@ async function copySharedFiles() {
}
}
async function createMasterProtoFile() {
try {
fse.readdir(protoFilesDir, (err, files) => {
if (err) throw err;
fse.outputFile(masterProtoFile, JSON.stringify(files.filter(file => /\.proto$/.test(file))));
});
} catch (e) {
console.error(e);
process.exitCode = 1;
}
}
async function createServerProps() {
try {
fse.outputFile(serverPropsFile, JSON.stringify({

View file

@ -8,15 +8,9 @@ vi.mock('websocket', () => ({
},
}));
vi.mock('websocket/services/ProtoController', () => ({
ProtoController: {
root: {
ServerInfo_User: {
UserLevelFlag: {
IsModerator: 4,
},
},
},
vi.mock('generated/proto/serverinfo_user_pb', () => ({
ServerInfo_User_UserLevelFlag: {
IsModerator: 4,
},
}));

View file

@ -1,6 +1,6 @@
import { StatusEnum, User, WebSocketConnectReason, WebSocketConnectOptions } from 'types';
import { SessionCommands, webClient } from 'websocket';
import { ProtoController } from 'websocket/services/ProtoController';
import { ServerInfo_User_UserLevelFlag } from 'generated/proto/serverinfo_user_pb';
export class AuthenticationService {
static login(options: WebSocketConnectOptions): void {
@ -40,7 +40,7 @@ export class AuthenticationService {
}
static isModerator(user: User): boolean {
const moderatorLevel = ProtoController.root.ServerInfo_User.UserLevelFlag.IsModerator;
const moderatorLevel = ServerInfo_User_UserLevelFlag.IsModerator;
// @TODO tell cockatrice not to do this so shittily
return (user.userLevel & moderatorLevel) === moderatorLevel;
}

View file

@ -1,10 +1,2 @@
import protobuf from 'protobufjs';
// ensure jest-dom is always available during testing to cut down on boilerplate
import '@testing-library/jest-dom/vitest';
class MockProtobufRoot {
load() {}
}
(protobuf as any).Root = MockProtobufRoot;

View file

@ -118,9 +118,9 @@ describe('sortByFields', () => {
describe('sortUsersByField', () => {
it('sorts by userLevel DESC first, then name ASC', () => {
const users = [
{ name: 'Alice', userLevel: 1, accountageSecs: 0, privlevel: 0 },
{ name: 'Bob', userLevel: 8, accountageSecs: 0, privlevel: 0 },
{ name: 'Carol', userLevel: 1, accountageSecs: 0, privlevel: 0 },
{ name: 'Alice', userLevel: 1, accountageSecs: 0n, privlevel: '' },
{ name: 'Bob', userLevel: 8, accountageSecs: 0n, privlevel: '' },
{ name: 'Carol', userLevel: 1, accountageSecs: 0n, privlevel: '' },
];
SortUtil.sortUsersByField(users as any, { field: 'name', order: SortDirection.ASC });
expect(users[0].name).toBe('Bob');
@ -136,8 +136,8 @@ describe('sortUsersByField', () => {
it('returns 0 (stable) when two users tie on both userLevel and name', () => {
const users = [
{ name: 'Alice', userLevel: 1, accountageSecs: 0, privlevel: 0 },
{ name: 'Alice', userLevel: 1, accountageSecs: 0, privlevel: 0 },
{ name: 'Alice', userLevel: 1, accountageSecs: 0n, privlevel: '' },
{ name: 'Alice', userLevel: 1, accountageSecs: 0n, privlevel: '' },
];
expect(() =>
SortUtil.sortUsersByField(users as any, { field: 'name', order: SortDirection.ASC })

View file

@ -4,7 +4,6 @@ import {
Room,
SortDirection,
User,
UserPrivLevel,
UserSortField,
} from 'types';
import { Message, RoomsState } from '../rooms.interfaces';
@ -12,8 +11,8 @@ import { Message, RoomsState } from '../rooms.interfaces';
export function makeUser(overrides: Partial<User> = {}): User {
return {
name: 'TestUser',
accountageSecs: 0,
privlevel: UserPrivLevel.NONE,
accountageSecs: 0n,
privlevel: '',
userLevel: 0,
...overrides,
};

View file

@ -7,7 +7,6 @@ import {
SortDirection,
StatusEnum,
User,
UserPrivLevel,
UserSortField,
WebSocketConnectOptions,
WarnHistoryItem,
@ -18,8 +17,8 @@ import { ServerState } from '../server.interfaces';
export function makeUser(overrides: Partial<User> = {}): User {
return {
name: 'TestUser',
accountageSecs: 0,
privlevel: UserPrivLevel.NONE,
accountageSecs: 0n,
privlevel: '',
userLevel: 0,
...overrides,
};

View file

@ -1,11 +1,77 @@
export interface Game {
description: string;
gameId: number;
// ── Imports from generated proto files ───────────────────────────────────────
import type { GameEventContext } from 'generated/proto/game_event_context_pb';
import type { CardToMove, Command_MoveCard } from 'generated/proto/command_move_card_pb';
import type { Command_DrawCards } from 'generated/proto/command_draw_cards_pb';
import type { Command_RollDie } from 'generated/proto/command_roll_die_pb';
import type { Command_Shuffle } from 'generated/proto/command_shuffle_pb';
import type { Command_FlipCard } from 'generated/proto/command_flip_card_pb';
import type { Command_AttachCard } from 'generated/proto/command_attach_card_pb';
import type { Command_CreateToken } from 'generated/proto/command_create_token_pb';
import type { Command_SetCardAttr } from 'generated/proto/command_set_card_attr_pb';
import type { Command_SetCardCounter } from 'generated/proto/command_set_card_counter_pb';
import type { Command_IncCardCounter } from 'generated/proto/command_inc_card_counter_pb';
import type { Command_RevealCards } from 'generated/proto/command_reveal_cards_pb';
import type { Command_DumpZone } from 'generated/proto/command_dump_zone_pb';
import type { Command_ChangeZoneProperties } from 'generated/proto/command_change_zone_properties_pb';
import type { Command_CreateArrow } from 'generated/proto/command_create_arrow_pb';
import type { Command_DeleteArrow } from 'generated/proto/command_delete_arrow_pb';
import type { Command_CreateCounter } from 'generated/proto/command_create_counter_pb';
import type { Command_SetCounter } from 'generated/proto/command_set_counter_pb';
import type { Command_IncCounter } from 'generated/proto/command_inc_counter_pb';
import type { Command_DelCounter } from 'generated/proto/command_del_counter_pb';
import type { Command_KickFromGame } from 'generated/proto/command_kick_from_game_pb';
import type { Command_ReadyStart } from 'generated/proto/command_ready_start_pb';
import type { Command_Mulligan } from 'generated/proto/command_mulligan_pb';
import type { Command_DeckSelect } from 'generated/proto/command_deck_select_pb';
import type { MoveCard_ToZone } from 'generated/proto/move_card_to_zone_pb';
import type { Command_SetSideboardPlan } from 'generated/proto/command_set_sideboard_plan_pb';
import type { Command_SetSideboardLock } from 'generated/proto/command_set_sideboard_lock_pb';
import type { Command_SetActivePhase } from 'generated/proto/command_set_active_phase_pb';
import type { Command_GameSay } from 'generated/proto/command_game_say_pb';
import type { Event_GameStateChanged } from 'generated/proto/event_game_state_changed_pb';
import type { Event_GameSay } from 'generated/proto/event_game_say_pb';
import type { Event_MoveCard } from 'generated/proto/event_move_card_pb';
import type { Event_FlipCard } from 'generated/proto/event_flip_card_pb';
import type { Event_DestroyCard } from 'generated/proto/event_destroy_card_pb';
import type { Event_AttachCard } from 'generated/proto/event_attach_card_pb';
import type { Event_CreateToken } from 'generated/proto/event_create_token_pb';
import type { Event_SetCardAttr } from 'generated/proto/event_set_card_attr_pb';
import type { Event_SetCardCounter } from 'generated/proto/event_set_card_counter_pb';
import type { Event_CreateArrow } from 'generated/proto/event_create_arrow_pb';
import type { Event_DeleteArrow } from 'generated/proto/event_delete_arrow_pb';
import type { Event_CreateCounter } from 'generated/proto/event_create_counter_pb';
import type { Event_SetCounter } from 'generated/proto/event_set_counter_pb';
import type { Event_DelCounter } from 'generated/proto/event_del_counter_pb';
import type { Event_DrawCards } from 'generated/proto/event_draw_cards_pb';
import type { Event_RevealCards } from 'generated/proto/event_reveal_cards_pb';
import type { Event_Shuffle } from 'generated/proto/event_shuffle_pb';
import type { Event_RollDie } from 'generated/proto/event_roll_die_pb';
import type { Event_DumpZone } from 'generated/proto/event_dump_zone_pb';
import type { Event_ChangeZoneProperties } from 'generated/proto/event_change_zone_properties_pb';
import type { Event_SetActivePlayer } from 'generated/proto/event_set_active_player_pb';
import type { Event_SetActivePhase } from 'generated/proto/event_set_active_phase_pb';
import type { Event_ReverseTurn } from 'generated/proto/event_reverse_turn_pb';
import type { ServerInfo_Game } from 'generated/proto/serverinfo_game_pb';
import type { color } from 'generated/proto/color_pb';
import type { ServerInfo_CardCounter } from 'generated/proto/serverinfo_cardcounter_pb';
import type { ServerInfo_Card } from 'generated/proto/serverinfo_card_pb';
import type { ServerInfo_Zone } from 'generated/proto/serverinfo_zone_pb';
import type { ServerInfo_Counter } from 'generated/proto/serverinfo_counter_pb';
import type { ServerInfo_Arrow } from 'generated/proto/serverinfo_arrow_pb';
import type { ServerInfo_PlayerProperties } from 'generated/proto/serverinfo_playerproperties_pb';
import type { ServerInfo_Player } from 'generated/proto/serverinfo_player_pb';
// ── Enum re-exports from generated proto files ────────────────────────────────
export { CardAttribute } from 'generated/proto/card_attributes_pb';
export { ServerInfo_Zone_ZoneType as ZoneType } from 'generated/proto/serverinfo_zone_pb';
// ── UI types (not proto mirrors) ──────────────────────────────────────────────
export type Game = ServerInfo_Game & {
gameType: string;
gameTypes: string[];
roomId: number;
started: boolean;
}
};
export enum GameSortField {
START_TIME = 'startTime'
@ -14,7 +80,7 @@ export enum GameSortField {
export interface GameConfig {
description: string;
password: string;
maxPlayer: number;
maxPlayers: number;
onlyBuddies: boolean;
onlyRegistered: boolean;
spectatorsAllowed: boolean;
@ -24,6 +90,8 @@ export interface GameConfig {
gameTypeIds: number[];
joinAsJudge: boolean;
joinAsSpectator: boolean;
startingLifeTotal?: number;
shareDecklistsOnLoad?: boolean;
}
export interface JoinGameParams {
@ -41,283 +109,52 @@ export enum LeaveGameReason {
USER_DISCONNECTED = 4
}
// ── Enums ────────────────────────────────────────────────────────────────────
// ── Type aliases for generated state mirror types ─────────────────────────────
export enum ZoneType {
PrivateZone = 0,
PublicZone = 1,
HiddenZone = 2,
}
export type Color = color;
export type CardCounterInfo = ServerInfo_CardCounter;
export type CardInfo = ServerInfo_Card;
export type ZoneInfo = ServerInfo_Zone;
export type CounterInfo = ServerInfo_Counter;
export type ArrowInfo = ServerInfo_Arrow;
export type PlayerProperties = ServerInfo_PlayerProperties;
export type PlayerInfo = ServerInfo_Player;
/** Matches CardAttribute enum in card_attributes.proto */
export enum CardAttribute {
AttrTapped = 1,
AttrAttacking = 2,
AttrFaceDown = 3,
AttrColor = 4,
AttrPT = 5,
AttrAnnotation = 6,
AttrDoesntUntap = 7,
}
// ── Type aliases for generated event data types ───────────────────────────────
// ── Primitive data structures (mirrors ServerInfo_* protos) ──────────────────
export type GameStateChangedData = Event_GameStateChanged;
export type GameSayData = Event_GameSay;
export type MoveCardData = Event_MoveCard;
export type FlipCardData = Event_FlipCard;
export type DestroyCardData = Event_DestroyCard;
export type AttachCardData = Event_AttachCard;
export type CreateTokenData = Event_CreateToken;
export type SetCardAttrData = Event_SetCardAttr;
export type SetCardCounterData = Event_SetCardCounter;
export type CreateArrowData = Event_CreateArrow;
export type DeleteArrowData = Event_DeleteArrow;
export type CreateCounterData = Event_CreateCounter;
export type SetCounterData = Event_SetCounter;
export type DelCounterData = Event_DelCounter;
export type DrawCardsData = Event_DrawCards;
export type RevealCardsData = Event_RevealCards;
export type ShuffleData = Event_Shuffle;
export type RollDieData = Event_RollDie;
export type DumpZoneData = Event_DumpZone;
export type ChangeZonePropertiesData = Event_ChangeZoneProperties;
export type SetActivePlayerData = Event_SetActivePlayer;
export type SetActivePhaseData = Event_SetActivePhase;
export type ReverseTurnData = Event_ReverseTurn;
export interface Color {
r: number;
g: number;
b: number;
a: number;
}
// ── GameEventContext (re-export of generated type) ────────────────────────────
/** Mirrors ServerInfo_CardCounter */
export interface CardCounterInfo {
id: number;
value: number;
}
/** Mirrors ServerInfo_Card */
export interface CardInfo {
id: number;
name: string;
x: number;
y: number;
faceDown: boolean;
tapped: boolean;
attacking: boolean;
color: string;
pt: string;
annotation: string;
destroyOnZoneChange: boolean;
doesntUntap: boolean;
counterList: CardCounterInfo[];
attachPlayerId: number;
attachZone: string;
attachCardId: number;
providerId: string;
}
/** Mirrors ServerInfo_Zone */
export interface ZoneInfo {
name: string;
type: ZoneType;
withCoords: boolean;
cardCount: number;
cardList: CardInfo[];
alwaysRevealTopCard: boolean;
alwaysLookAtTopCard: boolean;
}
/** Mirrors ServerInfo_Counter */
export interface CounterInfo {
id: number;
name: string;
counterColor: Color;
radius: number;
count: number;
}
/** Mirrors ServerInfo_Arrow */
export interface ArrowInfo {
id: number;
startPlayerId: number;
startZone: string;
startCardId: number;
targetPlayerId: number;
targetZone: string;
targetCardId: number;
arrowColor: Color;
}
/** Mirrors ServerInfo_PlayerProperties */
export interface PlayerProperties {
playerId: number;
userInfo: any;
spectator: boolean;
conceded: boolean;
readyStart: boolean;
deckHash: string;
pingSeconds: number;
sideboardLocked: boolean;
judge: boolean;
}
/** Mirrors ServerInfo_Player */
export interface PlayerInfo {
properties: PlayerProperties;
deckList: string;
zoneList: ZoneInfo[];
counterList: CounterInfo[];
arrowList: ArrowInfo[];
}
// ── Game event payload interfaces (data arriving from server events) ──────────
export interface GameStateChangedData {
playerList: PlayerInfo[];
gameStarted: boolean;
activePlayerId: number;
activePhase: number;
secondsElapsed: number;
}
export interface GameSayData {
message: string;
}
export interface MoveCardData {
cardId: number;
cardName: string;
startPlayerId: number;
startZone: string;
position: number;
targetPlayerId: number;
targetZone: string;
x: number;
y: number;
newCardId: number;
faceDown: boolean;
newCardProviderId: string;
}
export interface FlipCardData {
zoneName: string;
cardId: number;
cardName: string;
faceDown: boolean;
cardProviderId: string;
}
export interface DestroyCardData {
zoneName: string;
cardId: number;
}
export interface AttachCardData {
startZone: string;
cardId: number;
targetPlayerId: number;
targetZone: string;
targetCardId: number;
}
export interface CreateTokenData {
zoneName: string;
cardId: number;
cardName: string;
color: string;
pt: string;
annotation: string;
destroyOnZoneChange: boolean;
x: number;
y: number;
cardProviderId: string;
faceDown: boolean;
}
export interface SetCardAttrData {
zoneName: string;
cardId: number;
attribute: CardAttribute;
attrValue: string;
}
export interface SetCardCounterData {
zoneName: string;
cardId: number;
counterId: number;
counterValue: number;
}
export interface CreateArrowData {
arrowInfo: ArrowInfo;
}
export interface DeleteArrowData {
arrowId: number;
}
export interface CreateCounterData {
counterInfo: CounterInfo;
}
export interface SetCounterData {
counterId: number;
value: number;
}
export interface DelCounterData {
counterId: number;
}
export interface DrawCardsData {
number: number;
cards: CardInfo[];
}
export interface RevealCardsData {
zoneName: string;
cardId: number[];
otherPlayerId: number;
cards: CardInfo[];
grantWriteAccess: boolean;
numberOfCards: number;
}
export interface ShuffleData {
zoneName: string;
start: number;
end: number;
}
export interface RollDieData {
sides: number;
value: number;
values: number[];
}
export interface DumpZoneData {
zoneOwnerId: number;
zoneName: string;
numberCards: number;
isReversed: boolean;
}
export interface ChangeZonePropertiesData {
zoneName: string;
alwaysRevealTopCard: boolean;
alwaysLookAtTopCard: boolean;
}
export interface SetActivePlayerData {
activePlayerId: number;
}
export interface SetActivePhaseData {
phase: number;
}
export interface ReverseTurnData {
reversed: boolean;
}
export type { GameEventContext };
/**
* Passed to every game event handler alongside the event payload.
* Contains per-container metadata from GameEventContainer.
* Not stored in Redux transient routing metadata only.
*/
export interface GameEventContext {
'.Context_ReadyStart.ext'?: {};
'.Context_Concede.ext'?: {};
'.Context_DeckSelect.ext'?: {};
'.Context_UndoDraw.ext'?: {};
'.Context_MoveCard.ext'?: {};
'.Context_Mulligan.ext'?: {};
'.Context_PingChanged.ext'?: {};
'.Context_ConnectionStateChanged.ext'?: {};
'.Context_SetSideboardLock.ext'?: {};
'.Context_Unconcede.ext'?: {};
}
export interface GameEventMeta {
gameId: number;
playerId: number;
@ -328,186 +165,34 @@ export interface GameEventMeta {
forcedByJudge: number;
}
// ── Command parameter interfaces ─────────────────────────────────────────────
// ── Type aliases for generated command param types ────────────────────────────
export interface CardToMove {
cardId: number;
faceDown?: boolean;
pt?: string;
tapped?: boolean;
}
export interface MoveCardParams {
startPlayerId: number;
startZone: string;
cardsToMove: { card: CardToMove[] };
targetPlayerId: number;
targetZone: string;
x?: number;
y?: number;
isReversed?: boolean;
}
export interface DrawCardsParams {
number: number;
}
export interface RollDieParams {
sides: number;
count?: number;
}
export interface ShuffleParams {
zoneName: string;
start?: number;
end?: number;
}
export interface FlipCardParams {
zone: string;
cardId: number;
faceDown: boolean;
pt?: string;
}
export interface AttachCardParams {
startZone: string;
cardId: number;
targetPlayerId?: number;
targetZone?: string;
targetCardId?: number;
}
export interface CreateTokenParams {
zone: string;
cardName: string;
color?: string;
pt?: string;
annotation?: string;
destroyOnZoneChange?: boolean;
x?: number;
y?: number;
targetZone?: string;
targetCardId?: number;
targetMode?: number;
cardProviderId?: string;
faceDown?: boolean;
}
export interface SetCardAttrParams {
zone: string;
cardId: number;
attribute: CardAttribute;
attrValue: string;
}
export interface SetCardCounterParams {
zone: string;
cardId: number;
counterId: number;
counterValue: number;
}
export interface IncCardCounterParams {
zone: string;
cardId: number;
counterId: number;
counterDelta: number;
}
export interface RevealCardsParams {
zoneName: string;
cardId?: number[];
playerId?: number;
grantWriteAccess?: boolean;
topCards?: number;
}
export interface DumpZoneParams {
playerId: number;
zoneName: string;
numberCards: number;
isReversed?: boolean;
}
export interface ChangeZonePropertiesParams {
zoneName: string;
alwaysRevealTopCard?: boolean;
alwaysLookAtTopCard?: boolean;
}
export interface CreateArrowParams {
startPlayerId: number;
startZone: string;
startCardId: number;
targetPlayerId: number;
targetZone?: string;
targetCardId?: number;
arrowColor: Color;
deleteInPhase?: number;
}
export interface DeleteArrowParams {
arrowId: number;
}
export interface CreateCounterParams {
counterName: string;
counterColor: Color;
radius: number;
value: number;
}
export interface SetCounterParams {
counterId: number;
value: number;
}
export interface IncCounterParams {
counterId: number;
delta: number;
}
export interface DelCounterParams {
counterId: number;
}
export interface KickFromGameParams {
playerId: number;
}
export interface ReadyStartParams {
ready: boolean;
forceStart?: boolean;
}
export interface MulliganParams {
number: number;
}
export interface DeckSelectParams {
deck?: string;
deckId?: number;
}
export interface MoveCardToZone {
cardName: string;
startZone: string;
targetZone: string;
}
export interface SetSideboardPlanParams {
moveList: MoveCardToZone[];
}
export interface SetSideboardLockParams {
locked: boolean;
}
export interface SetActivePhaseParams {
phase: number;
}
export interface GameSayParams {
message: string;
}
export type { CardToMove };
export type MoveCardParams = Command_MoveCard;
export type DrawCardsParams = Command_DrawCards;
export type RollDieParams = Command_RollDie;
export type ShuffleParams = Command_Shuffle;
export type FlipCardParams = Command_FlipCard;
export type AttachCardParams = Command_AttachCard;
export type CreateTokenParams = Command_CreateToken;
export type SetCardAttrParams = Command_SetCardAttr;
export type SetCardCounterParams = Command_SetCardCounter;
export type IncCardCounterParams = Command_IncCardCounter;
export type RevealCardsParams = Command_RevealCards;
export type DumpZoneParams = Command_DumpZone;
export type ChangeZonePropertiesParams = Command_ChangeZoneProperties;
export type CreateArrowParams = Command_CreateArrow;
export type DeleteArrowParams = Command_DeleteArrow;
export type CreateCounterParams = Command_CreateCounter;
export type SetCounterParams = Command_SetCounter;
export type IncCounterParams = Command_IncCounter;
export type DelCounterParams = Command_DelCounter;
export type KickFromGameParams = Command_KickFromGame;
export type ReadyStartParams = Command_ReadyStart;
export type MulliganParams = Command_Mulligan;
export type DeckSelectParams = Command_DeckSelect;
export type MoveCardToZone = MoveCard_ToZone;
export type SetSideboardPlanParams = Command_SetSideboardPlan;
export type SetSideboardLockParams = Command_SetSideboardLock;
export type SetActivePhaseParams = Command_SetActivePhase;
export type GameSayParams = Command_GameSay;

View file

@ -1,7 +1,5 @@
export interface Message {
name: string;
message: string;
messageType: number;
timeOf: number;
import type { Event_RoomSay } from 'generated/proto/event_room_say_pb';
export type Message = Event_RoomSay & {
timeReceived: number;
}
};

View file

@ -1,16 +1,5 @@
export interface Replay {
replayId: number;
replayName: string;
duration: number;
}
import type { ServerInfo_Replay } from 'generated/proto/serverinfo_replay_pb';
import type { ServerInfo_ReplayMatch } from 'generated/proto/serverinfo_replay_match_pb';
export interface ReplayMatch {
replayList: Replay[];
gameId: number;
roomName: string;
timeStarted: number;
length: number;
gameName: string;
playerNames: string[];
doNotHide: boolean;
}
export type Replay = ServerInfo_Replay;
export type ReplayMatch = ServerInfo_ReplayMatch;

View file

@ -1,23 +1,8 @@
import { User } from './user';
export interface Room {
autoJoin: boolean
description: string;
gameCount: number;
gameList: any[];
gametypeList: any[];
gametypeMap: GametypeMap;
name: string;
permissionlevel: RoomAccessLevel;
playerCount: number;
privilegelevel: RoomAccessLevel;
roomId: number;
userList: User[];
order: number;
}
import type { ServerInfo_Room } from 'generated/proto/serverinfo_room_pb';
export interface GametypeMap { [index: number]: string }
export enum RoomAccessLevel {
'none'
}
export type Room = ServerInfo_Room & {
gametypeMap: GametypeMap;
order: number;
};

View file

@ -1,7 +1 @@
export enum NotificationType {
UNKNOWN = 0,
PROMOTED = 1,
WARNING = 2,
IDLEWARNING = 3,
CUSTOM = 4,
};
export { Event_NotifyUser_NotificationType as NotificationType } from 'generated/proto/event_notify_user_pb';

View file

@ -1,27 +1,7 @@
export interface User {
accountageSecs: number;
name: string;
privlevel: UserPrivLevel;
userLevel: number;
realName?: string;
country?: string;
avatarBmp?: Uint8Array;
}
import type { ServerInfo_User } from 'generated/proto/serverinfo_user_pb';
export enum UserLevelFlag {
IsNothing = 0,
IsUser = 1,
IsRegistered = 2,
IsModerator = 4,
IsAdmin = 8,
IsJudge = 16,
}
export enum UserPrivLevel {
NONE = 0,
VIP = 1,
DONOR = 2
}
export type User = ServerInfo_User;
export { ServerInfo_User_UserLevelFlag as UserLevelFlag } from 'generated/proto/serverinfo_user_pb';
export enum UserSortField {
NAME = 'name'

View file

@ -17,7 +17,7 @@ vi.mock('./services/ProtobufService', () => ({
vi.mock('./persistence', () => ({
RoomPersistence: { clearStore: vi.fn() },
SessionPersistence: { clearStore: vi.fn() },
SessionPersistence: { clearStore: vi.fn(), initialized: vi.fn() },
}));
import { WebClient } from './WebClient';
@ -60,6 +60,10 @@ describe('WebClient', () => {
messageSubject.next(event);
expect(client.protobuf.handleMessageEvent).toHaveBeenCalledWith(event);
});
it('calls SessionPersistence.initialized', () => {
expect(SessionPersistence.initialized).toHaveBeenCalled();
});
});
describe('connect', () => {

View file

@ -47,6 +47,8 @@ export class WebClient {
this.protobuf.handleMessageEvent(message);
});
SessionPersistence.initialized();
if (import.meta.env.MODE !== 'test') {
console.log(this);
}

View file

@ -4,8 +4,8 @@
* @param mockFn - The vi.Mock for the BackendService send method
* (e.g. BackendService.sendSessionCommand as vi.Mock).
* @param optsArgIndex - Index of the options argument in the mock call.
* Defaults to 2 (commandName, params, options).
* Use 3 for sendRoomCommand (roomId, commandName, params, options).
* Defaults to 2 (ext, value, options).
* Use 3 for sendRoomCommand (roomId, ext, value, options).
*/
export function makeCallbackHelpers(mockFn: vi.Mock, optsArgIndex = 2) {
function getLastSendOpts() {

View file

@ -1,54 +1,9 @@
/**
* Shared mock factories for websocket layer unit tests.
* Import the helpers you need in each spec file via:
* import { makeMockProtoRoot, makeMockWebSocket } from '../__mocks__/helpers';
* import { makeMockWebSocket } from '../__mocks__/helpers';
*/
/** Builds a minimal mock of ProtoController.root */
export function makeMockProtoRoot() {
const encode = { finish: vi.fn().mockReturnValue(new Uint8Array()) };
return {
CommandContainer: {
create: vi.fn(args => ({ ...args })),
encode: vi.fn().mockReturnValue(encode),
},
SessionCommand: { create: vi.fn(args => ({ ...args })) },
RoomCommand: { create: vi.fn(args => ({ ...args })) },
ModeratorCommand: { create: vi.fn(args => ({ ...args })) },
AdminCommand: { create: vi.fn(args => ({ ...args })) },
ServerMessage: {
decode: vi.fn(),
MessageType: {
RESPONSE: 'RESPONSE',
ROOM_EVENT: 'ROOM_EVENT',
SESSION_EVENT: 'SESSION_EVENT',
GAME_EVENT_CONTAINER: 'GAME_EVENT_CONTAINER',
},
},
Response: {
ResponseCode: {
RespOk: 0,
RespRegistrationRequired: 1,
},
},
Event_ServerIdentification: {
ServerOptions: { SupportsPasswordHash: 2 },
},
Event_ConnectionClosed: {
CloseReason: {
USER_LIMIT_REACHED: 1,
TOO_MANY_CONNECTIONS: 2,
BANNED: 3,
DEMOTED: 4,
SERVER_SHUTDOWN: 5,
USERNAMEINVALID: 6,
LOGGEDINELSEWERE: 7,
OTHER: 8,
},
},
};
}
/** Builds a mock WebSocket instance */
export function makeMockWebSocketInstance() {
return {

View file

@ -25,38 +25,6 @@ export function makeWebClientMock() {
};
}
/** Superset ProtoController.root mock — includes all ResponseCode values and Event_ServerIdentification. */
export function makeProtoControllerRootMock() {
return {
Response: {
ResponseCode: {
RespOk: 0,
RespClientUpdateRequired: 1,
RespWrongPassword: 2,
RespUsernameInvalid: 3,
RespWouldOverwriteOldSession: 4,
RespUserIsBanned: 5,
RespRegistrationRequired: 6,
RespClientIdRequired: 7,
RespContextError: 8,
RespAccountNotActivated: 9,
RespRegistrationAccepted: 10,
RespRegistrationAcceptedNeedsActivation: 11,
RespUserAlreadyExists: 12,
RespPasswordTooShort: 13,
RespEmailRequiredToRegister: 14,
RespEmailBlackListed: 15,
RespTooManyRequests: 16,
RespRegistrationDisabled: 17,
RespActivationAccepted: 18,
},
},
Event_ServerIdentification: {
ServerOptions: { SupportsPasswordHash: 2 },
},
};
}
/** Utils mock with unified return values. */
export function makeUtilsMock() {
return {

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_AdjustMod_ext, Command_AdjustModSchema } from 'generated/proto/admin_commands_pb';
import { AdminPersistence } from '../../persistence';
export function adjustMod(userName: string, shouldBeMod?: boolean, shouldBeJudge?: boolean): void {
BackendService.sendAdminCommand('Command_AdjustMod', { userName, shouldBeMod, shouldBeJudge }, {
BackendService.sendAdminCommand(Command_AdjustMod_ext, create(Command_AdjustModSchema, { userName, shouldBeMod, shouldBeJudge }), {
onSuccess: () => {
AdminPersistence.adjustMod(userName, shouldBeMod, shouldBeJudge);
},

View file

@ -22,7 +22,8 @@ import { shutdownServer } from './shutdownServer';
import { updateServerMessage } from './updateServerMessage';
const { getLastSendOpts, invokeOnSuccess } = makeCallbackHelpers(
BackendService.sendAdminCommand as vi.Mock
BackendService.sendAdminCommand as vi.Mock,
2
);
beforeEach(() => vi.clearAllMocks());
@ -34,11 +35,7 @@ describe('adjustMod', () => {
it('calls sendAdminCommand with Command_AdjustMod', () => {
adjustMod('alice', true, false);
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith(
'Command_AdjustMod',
expect.objectContaining({ userName: 'alice', shouldBeMod: true, shouldBeJudge: false }),
expect.any(Object)
);
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), expect.any(Object));
});
it('onSuccess calls AdminPersistence.adjustMod', () => {
@ -55,7 +52,7 @@ describe('reloadConfig', () => {
it('calls sendAdminCommand with Command_ReloadConfig', () => {
reloadConfig();
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith('Command_ReloadConfig', {}, expect.any(Object));
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), expect.any(Object));
});
it('onSuccess calls AdminPersistence.reloadConfig', () => {
@ -72,11 +69,7 @@ describe('shutdownServer', () => {
it('calls sendAdminCommand with Command_ShutdownServer', () => {
shutdownServer('maintenance', 10);
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith(
'Command_ShutdownServer',
{ reason: 'maintenance', minutes: 10 },
expect.any(Object)
);
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), expect.any(Object));
});
it('onSuccess calls AdminPersistence.shutdownServer', () => {
@ -93,7 +86,7 @@ describe('updateServerMessage', () => {
it('calls sendAdminCommand with Command_UpdateServerMessage', () => {
updateServerMessage();
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith('Command_UpdateServerMessage', {}, expect.any(Object));
expect(BackendService.sendAdminCommand).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), expect.any(Object));
});
it('onSuccess calls AdminPersistence.updateServerMessage', () => {

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ReloadConfig_ext, Command_ReloadConfigSchema } from 'generated/proto/admin_commands_pb';
import { AdminPersistence } from '../../persistence';
export function reloadConfig(): void {
BackendService.sendAdminCommand('Command_ReloadConfig', {}, {
BackendService.sendAdminCommand(Command_ReloadConfig_ext, create(Command_ReloadConfigSchema), {
onSuccess: () => {
AdminPersistence.reloadConfig();
},

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ShutdownServer_ext, Command_ShutdownServerSchema } from 'generated/proto/admin_commands_pb';
import { AdminPersistence } from '../../persistence';
export function shutdownServer(reason: string, minutes: number): void {
BackendService.sendAdminCommand('Command_ShutdownServer', { reason, minutes }, {
BackendService.sendAdminCommand(Command_ShutdownServer_ext, create(Command_ShutdownServerSchema, { reason, minutes }), {
onSuccess: () => {
AdminPersistence.shutdownServer();
},

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_UpdateServerMessage_ext, Command_UpdateServerMessageSchema } from 'generated/proto/admin_commands_pb';
import { AdminPersistence } from '../../persistence';
export function updateServerMessage(): void {
BackendService.sendAdminCommand('Command_UpdateServerMessage', {}, {
BackendService.sendAdminCommand(Command_UpdateServerMessage_ext, create(Command_UpdateServerMessageSchema), {
onSuccess: () => {
AdminPersistence.updateServerMessage();
},

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_AttachCardSchema, Command_AttachCard_ext } from 'generated/proto/command_attach_card_pb';
import { AttachCardParams } from 'types';
export function attachCard(gameId: number, params: AttachCardParams): void {
BackendService.sendGameCommand(gameId, 'Command_AttachCard', params);
BackendService.sendGameCommand(gameId, Command_AttachCard_ext, create(Command_AttachCardSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ChangeZonePropertiesSchema, Command_ChangeZoneProperties_ext } from 'generated/proto/command_change_zone_properties_pb';
import { ChangeZonePropertiesParams } from 'types';
export function changeZoneProperties(gameId: number, params: ChangeZonePropertiesParams): void {
BackendService.sendGameCommand(gameId, 'Command_ChangeZoneProperties', params);
BackendService.sendGameCommand(gameId, Command_ChangeZoneProperties_ext, create(Command_ChangeZonePropertiesSchema, params));
}

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ConcedeSchema, Command_Concede_ext } from 'generated/proto/command_concede_pb';
export function concede(gameId: number): void {
BackendService.sendGameCommand(gameId, 'Command_Concede', {});
BackendService.sendGameCommand(gameId, Command_Concede_ext, create(Command_ConcedeSchema));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_CreateArrowSchema, Command_CreateArrow_ext } from 'generated/proto/command_create_arrow_pb';
import { CreateArrowParams } from 'types';
export function createArrow(gameId: number, params: CreateArrowParams): void {
BackendService.sendGameCommand(gameId, 'Command_CreateArrow', params);
BackendService.sendGameCommand(gameId, Command_CreateArrow_ext, create(Command_CreateArrowSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_CreateCounterSchema, Command_CreateCounter_ext } from 'generated/proto/command_create_counter_pb';
import { CreateCounterParams } from 'types';
export function createCounter(gameId: number, params: CreateCounterParams): void {
BackendService.sendGameCommand(gameId, 'Command_CreateCounter', params);
BackendService.sendGameCommand(gameId, Command_CreateCounter_ext, create(Command_CreateCounterSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_CreateTokenSchema, Command_CreateToken_ext } from 'generated/proto/command_create_token_pb';
import { CreateTokenParams } from 'types';
export function createToken(gameId: number, params: CreateTokenParams): void {
BackendService.sendGameCommand(gameId, 'Command_CreateToken', params);
BackendService.sendGameCommand(gameId, Command_CreateToken_ext, create(Command_CreateTokenSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DeckSelectSchema, Command_DeckSelect_ext } from 'generated/proto/command_deck_select_pb';
import { DeckSelectParams } from 'types';
export function deckSelect(gameId: number, params: DeckSelectParams): void {
BackendService.sendGameCommand(gameId, 'Command_DeckSelect', params);
BackendService.sendGameCommand(gameId, Command_DeckSelect_ext, create(Command_DeckSelectSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DelCounterSchema, Command_DelCounter_ext } from 'generated/proto/command_del_counter_pb';
import { DelCounterParams } from 'types';
export function delCounter(gameId: number, params: DelCounterParams): void {
BackendService.sendGameCommand(gameId, 'Command_DelCounter', params);
BackendService.sendGameCommand(gameId, Command_DelCounter_ext, create(Command_DelCounterSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DeleteArrowSchema, Command_DeleteArrow_ext } from 'generated/proto/command_delete_arrow_pb';
import { DeleteArrowParams } from 'types';
export function deleteArrow(gameId: number, params: DeleteArrowParams): void {
BackendService.sendGameCommand(gameId, 'Command_DeleteArrow', params);
BackendService.sendGameCommand(gameId, Command_DeleteArrow_ext, create(Command_DeleteArrowSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DrawCardsSchema, Command_DrawCards_ext } from 'generated/proto/command_draw_cards_pb';
import { DrawCardsParams } from 'types';
export function drawCards(gameId: number, params: DrawCardsParams): void {
BackendService.sendGameCommand(gameId, 'Command_DrawCards', params);
BackendService.sendGameCommand(gameId, Command_DrawCards_ext, create(Command_DrawCardsSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DumpZoneSchema, Command_DumpZone_ext } from 'generated/proto/command_dump_zone_pb';
import { DumpZoneParams } from 'types';
export function dumpZone(gameId: number, params: DumpZoneParams): void {
BackendService.sendGameCommand(gameId, 'Command_DumpZone', params);
BackendService.sendGameCommand(gameId, Command_DumpZone_ext, create(Command_DumpZoneSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_FlipCardSchema, Command_FlipCard_ext } from 'generated/proto/command_flip_card_pb';
import { FlipCardParams } from 'types';
export function flipCard(gameId: number, params: FlipCardParams): void {
BackendService.sendGameCommand(gameId, 'Command_FlipCard', params);
BackendService.sendGameCommand(gameId, Command_FlipCard_ext, create(Command_FlipCardSchema, params));
}

View file

@ -1,4 +1,37 @@
import { BackendService } from '../../services/BackendService';
import { create, setExtension } from '@bufbuild/protobuf';
import { GameCommandSchema, Command_Judge_ext } from 'generated/proto/game_commands_pb';
import { Command_DrawCardsSchema, Command_DrawCards_ext } from 'generated/proto/command_draw_cards_pb';
import { Command_AttachCard_ext } from 'generated/proto/command_attach_card_pb';
import { Command_ChangeZoneProperties_ext } from 'generated/proto/command_change_zone_properties_pb';
import { Command_Concede_ext, Command_Unconcede_ext } from 'generated/proto/command_concede_pb';
import { Command_CreateArrow_ext } from 'generated/proto/command_create_arrow_pb';
import { Command_CreateCounter_ext } from 'generated/proto/command_create_counter_pb';
import { Command_CreateToken_ext } from 'generated/proto/command_create_token_pb';
import { Command_DeckSelect_ext } from 'generated/proto/command_deck_select_pb';
import { Command_DelCounter_ext } from 'generated/proto/command_del_counter_pb';
import { Command_DeleteArrow_ext } from 'generated/proto/command_delete_arrow_pb';
import { Command_DumpZone_ext } from 'generated/proto/command_dump_zone_pb';
import { Command_FlipCard_ext } from 'generated/proto/command_flip_card_pb';
import { Command_GameSay_ext } from 'generated/proto/command_game_say_pb';
import { Command_IncCardCounter_ext } from 'generated/proto/command_inc_card_counter_pb';
import { Command_IncCounter_ext } from 'generated/proto/command_inc_counter_pb';
import { Command_KickFromGame_ext } from 'generated/proto/command_kick_from_game_pb';
import { Command_LeaveGame_ext } from 'generated/proto/command_leave_game_pb';
import { Command_MoveCard_ext } from 'generated/proto/command_move_card_pb';
import { Command_Mulligan_ext } from 'generated/proto/command_mulligan_pb';
import { Command_NextTurn_ext } from 'generated/proto/command_next_turn_pb';
import { Command_ReadyStart_ext } from 'generated/proto/command_ready_start_pb';
import { Command_RevealCards_ext } from 'generated/proto/command_reveal_cards_pb';
import { Command_ReverseTurn_ext } from 'generated/proto/command_reverse_turn_pb';
import { Command_SetActivePhase_ext } from 'generated/proto/command_set_active_phase_pb';
import { Command_SetCardAttr_ext } from 'generated/proto/command_set_card_attr_pb';
import { Command_SetCardCounter_ext } from 'generated/proto/command_set_card_counter_pb';
import { Command_SetCounter_ext } from 'generated/proto/command_set_counter_pb';
import { Command_SetSideboardLock_ext } from 'generated/proto/command_set_sideboard_lock_pb';
import { Command_SetSideboardPlan_ext } from 'generated/proto/command_set_sideboard_plan_pb';
import { Command_Shuffle_ext } from 'generated/proto/command_shuffle_pb';
import { Command_UndoDraw_ext } from 'generated/proto/command_undo_draw_pb';
import { attachCard } from './attachCard';
import { changeZoneProperties } from './changeZoneProperties';
import { concede } from './concede';
@ -38,7 +71,6 @@ vi.mock('../../services/BackendService', () => ({
}));
const gameId = 1;
const params = {} as any;
beforeEach(() => {
(BackendService.sendGameCommand as vi.Mock).mockClear();
@ -46,172 +78,208 @@ beforeEach(() => {
describe('Game commands — delegate to BackendService.sendGameCommand', () => {
it('attachCard sends Command_AttachCard', () => {
attachCard(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_AttachCard', params);
attachCard(gameId, { cardId: 10, startZone: 'hand' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_AttachCard_ext, expect.objectContaining({ cardId: 10, startZone: 'hand' })
);
});
it('changeZoneProperties sends Command_ChangeZoneProperties', () => {
changeZoneProperties(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_ChangeZoneProperties', params);
changeZoneProperties(gameId, { zoneName: 'side' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_ChangeZoneProperties_ext, expect.objectContaining({ zoneName: 'side' })
);
});
it('concede sends Command_Concede with empty object', () => {
concede(gameId);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_Concede', {});
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_Concede_ext, expect.any(Object));
});
it('createArrow sends Command_CreateArrow', () => {
createArrow(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_CreateArrow', params);
createArrow(gameId, { startPlayerId: 1, startZone: 'hand' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_CreateArrow_ext, expect.objectContaining({ startPlayerId: 1, startZone: 'hand' })
);
});
it('createCounter sends Command_CreateCounter', () => {
createCounter(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_CreateCounter', params);
createCounter(gameId, { counterName: 'life' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_CreateCounter_ext, expect.objectContaining({ counterName: 'life' })
);
});
it('createToken sends Command_CreateToken', () => {
createToken(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_CreateToken', params);
createToken(gameId, { cardName: 'Goblin', zone: 'play' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_CreateToken_ext, expect.objectContaining({ cardName: 'Goblin', zone: 'play' })
);
});
it('deckSelect sends Command_DeckSelect', () => {
deckSelect(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_DeckSelect', params);
deckSelect(gameId, { deckId: 5 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_DeckSelect_ext, expect.objectContaining({ deckId: 5 }));
});
it('delCounter sends Command_DelCounter', () => {
delCounter(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_DelCounter', params);
delCounter(gameId, { counterId: 3 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_DelCounter_ext, expect.objectContaining({ counterId: 3 }));
});
it('deleteArrow sends Command_DeleteArrow', () => {
deleteArrow(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_DeleteArrow', params);
deleteArrow(gameId, { arrowId: 2 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_DeleteArrow_ext, expect.objectContaining({ arrowId: 2 }));
});
it('drawCards sends Command_DrawCards', () => {
drawCards(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_DrawCards', params);
drawCards(gameId, { number: 3 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_DrawCards_ext, expect.objectContaining({ number: 3 }));
});
it('dumpZone sends Command_DumpZone', () => {
dumpZone(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_DumpZone', params);
dumpZone(gameId, { playerId: 2, zoneName: 'library' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_DumpZone_ext, expect.objectContaining({ playerId: 2, zoneName: 'library' })
);
});
it('flipCard sends Command_FlipCard', () => {
flipCard(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_FlipCard', params);
flipCard(gameId, { cardId: 7, faceDown: false });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_FlipCard_ext, expect.objectContaining({ cardId: 7, faceDown: false })
);
});
it('gameSay sends Command_GameSay', () => {
gameSay(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_GameSay', params);
gameSay(gameId, { message: 'hello' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_GameSay_ext, expect.objectContaining({ message: 'hello' }));
});
it('incCardCounter sends Command_IncCardCounter', () => {
incCardCounter(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_IncCardCounter', params);
incCardCounter(gameId, { cardId: 5, counterId: 1 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_IncCardCounter_ext, expect.objectContaining({ cardId: 5, counterId: 1 })
);
});
it('incCounter sends Command_IncCounter', () => {
incCounter(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_IncCounter', params);
incCounter(gameId, { counterId: 1, delta: 5 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_IncCounter_ext, expect.objectContaining({ counterId: 1, delta: 5 })
);
});
it('kickFromGame sends Command_KickFromGame', () => {
kickFromGame(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_KickFromGame', params);
kickFromGame(gameId, { playerId: 2 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_KickFromGame_ext, expect.objectContaining({ playerId: 2 }));
});
it('leaveGame sends Command_LeaveGame with empty object', () => {
leaveGame(gameId);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_LeaveGame', {});
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_LeaveGame_ext, expect.any(Object));
});
it('moveCard sends Command_MoveCard', () => {
moveCard(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_MoveCard', params);
moveCard(gameId, { startZone: 'hand', targetZone: 'graveyard' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_MoveCard_ext,
expect.objectContaining({ startZone: 'hand', targetZone: 'graveyard' })
);
});
it('mulligan sends Command_Mulligan', () => {
mulligan(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_Mulligan', params);
mulligan(gameId, { number: 7 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_Mulligan_ext, expect.objectContaining({ number: 7 }));
});
it('nextTurn sends Command_NextTurn with empty object', () => {
nextTurn(gameId);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_NextTurn', {});
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_NextTurn_ext, expect.any(Object));
});
it('readyStart sends Command_ReadyStart', () => {
readyStart(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_ReadyStart', params);
readyStart(gameId, { ready: true });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_ReadyStart_ext, expect.objectContaining({ ready: true }));
});
it('revealCards sends Command_RevealCards', () => {
revealCards(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_RevealCards', params);
revealCards(gameId, { zoneName: 'hand', cardId: [1, 2] });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_RevealCards_ext, expect.objectContaining({ zoneName: 'hand', cardId: [1, 2] })
);
});
it('reverseTurn sends Command_ReverseTurn with empty object', () => {
reverseTurn(gameId);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_ReverseTurn', {});
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_ReverseTurn_ext, expect.any(Object));
});
it('setActivePhase sends Command_SetActivePhase', () => {
setActivePhase(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_SetActivePhase', params);
setActivePhase(gameId, { phase: 2 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_SetActivePhase_ext, expect.objectContaining({ phase: 2 }));
});
it('setCardAttr sends Command_SetCardAttr', () => {
setCardAttr(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_SetCardAttr', params);
setCardAttr(gameId, { zone: 'play', cardId: 5, attrValue: '2' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_SetCardAttr_ext,
expect.objectContaining({ zone: 'play', cardId: 5, attrValue: '2' })
);
});
it('setCardCounter sends Command_SetCardCounter', () => {
setCardCounter(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_SetCardCounter', params);
setCardCounter(gameId, { cardId: 5, counterId: 1 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_SetCardCounter_ext, expect.objectContaining({ cardId: 5, counterId: 1 })
);
});
it('setCounter sends Command_SetCounter', () => {
setCounter(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_SetCounter', params);
setCounter(gameId, { counterId: 1, value: 10 });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_SetCounter_ext, expect.objectContaining({ counterId: 1, value: 10 })
);
});
it('setSideboardLock sends Command_SetSideboardLock', () => {
setSideboardLock(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_SetSideboardLock', params);
setSideboardLock(gameId, { locked: true });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_SetSideboardLock_ext, expect.objectContaining({ locked: true })
);
});
it('setSideboardPlan sends Command_SetSideboardPlan', () => {
setSideboardPlan(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_SetSideboardPlan', params);
setSideboardPlan(gameId, { moveList: [] });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId, Command_SetSideboardPlan_ext, expect.objectContaining({ moveList: expect.any(Array) })
);
});
it('shuffle sends Command_Shuffle', () => {
shuffle(gameId, params);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_Shuffle', params);
shuffle(gameId, { zoneName: 'hand' });
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_Shuffle_ext, expect.objectContaining({ zoneName: 'hand' }));
});
it('undoDraw sends Command_UndoDraw with empty object', () => {
undoDraw(gameId);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_UndoDraw', {});
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_UndoDraw_ext, expect.any(Object));
});
it('unconcede sends Command_Unconcede with empty object', () => {
unconcede(gameId);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_Unconcede', {});
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, Command_Unconcede_ext, expect.any(Object));
});
it('judge sends Command_Judge with targetId and wrapped gameCommand array', () => {
const targetId = 3;
const innerGameCommand = { '.Command_DrawCards.ext': { numberOfCards: 2 } };
judge(gameId, targetId, innerGameCommand);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(gameId, 'Command_Judge', {
targetId,
gameCommand: [innerGameCommand],
});
const innerCmd = create(GameCommandSchema);
setExtension(innerCmd, Command_DrawCards_ext, create(Command_DrawCardsSchema, { number: 2 }));
judge(gameId, targetId, innerCmd);
expect(BackendService.sendGameCommand).toHaveBeenCalledWith(
gameId,
Command_Judge_ext,
expect.objectContaining({ targetId: 3, gameCommand: expect.any(Array) })
);
});
});

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_GameSaySchema, Command_GameSay_ext } from 'generated/proto/command_game_say_pb';
import { GameSayParams } from 'types';
export function gameSay(gameId: number, params: GameSayParams): void {
BackendService.sendGameCommand(gameId, 'Command_GameSay', params);
BackendService.sendGameCommand(gameId, Command_GameSay_ext, create(Command_GameSaySchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_IncCardCounterSchema, Command_IncCardCounter_ext } from 'generated/proto/command_inc_card_counter_pb';
import { IncCardCounterParams } from 'types';
export function incCardCounter(gameId: number, params: IncCardCounterParams): void {
BackendService.sendGameCommand(gameId, 'Command_IncCardCounter', params);
BackendService.sendGameCommand(gameId, Command_IncCardCounter_ext, create(Command_IncCardCounterSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_IncCounterSchema, Command_IncCounter_ext } from 'generated/proto/command_inc_counter_pb';
import { IncCounterParams } from 'types';
export function incCounter(gameId: number, params: IncCounterParams): void {
BackendService.sendGameCommand(gameId, 'Command_IncCounter', params);
BackendService.sendGameCommand(gameId, Command_IncCounter_ext, create(Command_IncCounterSchema, params));
}

View file

@ -1,8 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_JudgeSchema, Command_Judge_ext } from 'generated/proto/game_commands_pb';
import type { GameCommand } from 'generated/proto/game_commands_pb';
export function judge(gameId: number, targetId: number, innerGameCommand: any): void {
BackendService.sendGameCommand(gameId, 'Command_Judge', {
export function judge(gameId: number, targetId: number, innerGameCommand: GameCommand): void {
BackendService.sendGameCommand(gameId, Command_Judge_ext, create(Command_JudgeSchema, {
targetId,
gameCommand: [innerGameCommand],
});
}));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_KickFromGameSchema, Command_KickFromGame_ext } from 'generated/proto/command_kick_from_game_pb';
import { KickFromGameParams } from 'types';
export function kickFromGame(gameId: number, params: KickFromGameParams): void {
BackendService.sendGameCommand(gameId, 'Command_KickFromGame', params);
BackendService.sendGameCommand(gameId, Command_KickFromGame_ext, create(Command_KickFromGameSchema, params));
}

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_LeaveGameSchema, Command_LeaveGame_ext } from 'generated/proto/command_leave_game_pb';
export function leaveGame(gameId: number): void {
BackendService.sendGameCommand(gameId, 'Command_LeaveGame', {});
BackendService.sendGameCommand(gameId, Command_LeaveGame_ext, create(Command_LeaveGameSchema));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_MoveCardSchema, Command_MoveCard_ext } from 'generated/proto/command_move_card_pb';
import { MoveCardParams } from 'types';
export function moveCard(gameId: number, params: MoveCardParams): void {
BackendService.sendGameCommand(gameId, 'Command_MoveCard', params);
BackendService.sendGameCommand(gameId, Command_MoveCard_ext, create(Command_MoveCardSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_MulliganSchema, Command_Mulligan_ext } from 'generated/proto/command_mulligan_pb';
import { MulliganParams } from 'types';
export function mulligan(gameId: number, params: MulliganParams): void {
BackendService.sendGameCommand(gameId, 'Command_Mulligan', params);
BackendService.sendGameCommand(gameId, Command_Mulligan_ext, create(Command_MulliganSchema, params));
}

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_NextTurnSchema, Command_NextTurn_ext } from 'generated/proto/command_next_turn_pb';
export function nextTurn(gameId: number): void {
BackendService.sendGameCommand(gameId, 'Command_NextTurn', {});
BackendService.sendGameCommand(gameId, Command_NextTurn_ext, create(Command_NextTurnSchema));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ReadyStartSchema, Command_ReadyStart_ext } from 'generated/proto/command_ready_start_pb';
import { ReadyStartParams } from 'types';
export function readyStart(gameId: number, params: ReadyStartParams): void {
BackendService.sendGameCommand(gameId, 'Command_ReadyStart', params);
BackendService.sendGameCommand(gameId, Command_ReadyStart_ext, create(Command_ReadyStartSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_RevealCardsSchema, Command_RevealCards_ext } from 'generated/proto/command_reveal_cards_pb';
import { RevealCardsParams } from 'types';
export function revealCards(gameId: number, params: RevealCardsParams): void {
BackendService.sendGameCommand(gameId, 'Command_RevealCards', params);
BackendService.sendGameCommand(gameId, Command_RevealCards_ext, create(Command_RevealCardsSchema, params));
}

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ReverseTurnSchema, Command_ReverseTurn_ext } from 'generated/proto/command_reverse_turn_pb';
export function reverseTurn(gameId: number): void {
BackendService.sendGameCommand(gameId, 'Command_ReverseTurn', {});
BackendService.sendGameCommand(gameId, Command_ReverseTurn_ext, create(Command_ReverseTurnSchema));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_SetActivePhaseSchema, Command_SetActivePhase_ext } from 'generated/proto/command_set_active_phase_pb';
import { SetActivePhaseParams } from 'types';
export function setActivePhase(gameId: number, params: SetActivePhaseParams): void {
BackendService.sendGameCommand(gameId, 'Command_SetActivePhase', params);
BackendService.sendGameCommand(gameId, Command_SetActivePhase_ext, create(Command_SetActivePhaseSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_SetCardAttrSchema, Command_SetCardAttr_ext } from 'generated/proto/command_set_card_attr_pb';
import { SetCardAttrParams } from 'types';
export function setCardAttr(gameId: number, params: SetCardAttrParams): void {
BackendService.sendGameCommand(gameId, 'Command_SetCardAttr', params);
BackendService.sendGameCommand(gameId, Command_SetCardAttr_ext, create(Command_SetCardAttrSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_SetCardCounterSchema, Command_SetCardCounter_ext } from 'generated/proto/command_set_card_counter_pb';
import { SetCardCounterParams } from 'types';
export function setCardCounter(gameId: number, params: SetCardCounterParams): void {
BackendService.sendGameCommand(gameId, 'Command_SetCardCounter', params);
BackendService.sendGameCommand(gameId, Command_SetCardCounter_ext, create(Command_SetCardCounterSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_SetCounterSchema, Command_SetCounter_ext } from 'generated/proto/command_set_counter_pb';
import { SetCounterParams } from 'types';
export function setCounter(gameId: number, params: SetCounterParams): void {
BackendService.sendGameCommand(gameId, 'Command_SetCounter', params);
BackendService.sendGameCommand(gameId, Command_SetCounter_ext, create(Command_SetCounterSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_SetSideboardLockSchema, Command_SetSideboardLock_ext } from 'generated/proto/command_set_sideboard_lock_pb';
import { SetSideboardLockParams } from 'types';
export function setSideboardLock(gameId: number, params: SetSideboardLockParams): void {
BackendService.sendGameCommand(gameId, 'Command_SetSideboardLock', params);
BackendService.sendGameCommand(gameId, Command_SetSideboardLock_ext, create(Command_SetSideboardLockSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_SetSideboardPlanSchema, Command_SetSideboardPlan_ext } from 'generated/proto/command_set_sideboard_plan_pb';
import { SetSideboardPlanParams } from 'types';
export function setSideboardPlan(gameId: number, params: SetSideboardPlanParams): void {
BackendService.sendGameCommand(gameId, 'Command_SetSideboardPlan', params);
BackendService.sendGameCommand(gameId, Command_SetSideboardPlan_ext, create(Command_SetSideboardPlanSchema, params));
}

View file

@ -1,6 +1,8 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ShuffleSchema, Command_Shuffle_ext } from 'generated/proto/command_shuffle_pb';
import { ShuffleParams } from 'types';
export function shuffle(gameId: number, params: ShuffleParams): void {
BackendService.sendGameCommand(gameId, 'Command_Shuffle', params);
BackendService.sendGameCommand(gameId, Command_Shuffle_ext, create(Command_ShuffleSchema, params));
}

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_UnconcedeSchema, Command_Unconcede_ext } from 'generated/proto/command_concede_pb';
export function unconcede(gameId: number): void {
BackendService.sendGameCommand(gameId, 'Command_Unconcede', {});
BackendService.sendGameCommand(gameId, Command_Unconcede_ext, create(Command_UnconcedeSchema));
}

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_UndoDrawSchema, Command_UndoDraw_ext } from 'generated/proto/command_undo_draw_pb';
export function undoDraw(gameId: number): void {
BackendService.sendGameCommand(gameId, 'Command_UndoDraw', {});
BackendService.sendGameCommand(gameId, Command_UndoDraw_ext, create(Command_UndoDrawSchema));
}

View file

@ -1,11 +1,13 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_BanFromServer_ext, Command_BanFromServerSchema } from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
export function banFromServer(minutes: number, userName?: string, address?: string, reason?: string,
visibleReason?: string, clientid?: string, removeMessages?: number): void {
BackendService.sendModeratorCommand('Command_BanFromServer', {
BackendService.sendModeratorCommand(Command_BanFromServer_ext, create(Command_BanFromServerSchema, {
minutes, userName, address, reason, visibleReason, clientid, removeMessages
}, {
}), {
onSuccess: () => {
ModeratorPersistence.banFromServer(userName);
},

View file

@ -1,8 +1,13 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import {
Command_ForceActivateUser_ext, Command_ForceActivateUserSchema,
} from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
export function forceActivateUser(usernameToActivate: string, moderatorName: string): void {
BackendService.sendModeratorCommand('Command_ForceActivateUser', { usernameToActivate, moderatorName }, {
const cmd = create(Command_ForceActivateUserSchema, { usernameToActivate, moderatorName });
BackendService.sendModeratorCommand(Command_ForceActivateUser_ext, cmd, {
onSuccess: () => {
ModeratorPersistence.forceActivateUser(usernameToActivate, moderatorName);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_GetAdminNotes_ext, Command_GetAdminNotesSchema } from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
import { Response_GetAdminNotes_ext } from 'generated/proto/response_get_admin_notes_pb';
export function getAdminNotes(userName: string): void {
BackendService.sendModeratorCommand('Command_GetAdminNotes', { userName }, {
responseName: 'Response_GetAdminNotes',
BackendService.sendModeratorCommand(Command_GetAdminNotes_ext, create(Command_GetAdminNotesSchema, { userName }), {
responseExt: Response_GetAdminNotes_ext,
onSuccess: (response) => {
ModeratorPersistence.getAdminNotes(userName, response.notes);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_GetBanHistory_ext, Command_GetBanHistorySchema } from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
import { Response_BanHistory_ext } from 'generated/proto/response_ban_history_pb';
export function getBanHistory(userName: string): void {
BackendService.sendModeratorCommand('Command_GetBanHistory', { userName }, {
responseName: 'Response_BanHistory',
BackendService.sendModeratorCommand(Command_GetBanHistory_ext, create(Command_GetBanHistorySchema, { userName }), {
responseExt: Response_BanHistory_ext,
onSuccess: (response) => {
ModeratorPersistence.banHistory(userName, response.banList);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_GetWarnHistory_ext, Command_GetWarnHistorySchema } from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
import { Response_WarnHistory_ext } from 'generated/proto/response_warn_history_pb';
export function getWarnHistory(userName: string): void {
BackendService.sendModeratorCommand('Command_GetWarnHistory', { userName }, {
responseName: 'Response_WarnHistory',
BackendService.sendModeratorCommand(Command_GetWarnHistory_ext, create(Command_GetWarnHistorySchema, { userName }), {
responseExt: Response_WarnHistory_ext,
onSuccess: (response) => {
ModeratorPersistence.warnHistory(userName, response.warnList);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_GetWarnList_ext, Command_GetWarnListSchema } from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
import { Response_WarnList_ext } from 'generated/proto/response_warn_list_pb';
export function getWarnList(modName: string, userName: string, userClientid: string): void {
BackendService.sendModeratorCommand('Command_GetWarnList', { modName, userName, userClientid }, {
responseName: 'Response_WarnList',
BackendService.sendModeratorCommand(Command_GetWarnList_ext, create(Command_GetWarnListSchema, { modName, userName, userClientid }), {
responseExt: Response_WarnList_ext,
onSuccess: (response) => {
ModeratorPersistence.warnListOptions(response.warning);
},

View file

@ -1,8 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import {
Command_GrantReplayAccess_ext, Command_GrantReplayAccessSchema,
} from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
export function grantReplayAccess(replayId: number, moderatorName: string): void {
BackendService.sendModeratorCommand('Command_GrantReplayAccess', { replayId, moderatorName }, {
BackendService.sendModeratorCommand(Command_GrantReplayAccess_ext, create(Command_GrantReplayAccessSchema, { replayId, moderatorName }), {
onSuccess: () => {
ModeratorPersistence.grantReplayAccess(replayId, moderatorName);
},

View file

@ -22,6 +22,23 @@ vi.mock('../../persistence', () => ({
import { makeCallbackHelpers } from '../../__mocks__/callbackHelpers';
import { BackendService } from '../../services/BackendService';
import { ModeratorPersistence } from '../../persistence';
import {
Command_BanFromServer_ext,
Command_ForceActivateUser_ext,
Command_GetAdminNotes_ext,
Command_GetBanHistory_ext,
Command_GetWarnHistory_ext,
Command_GetWarnList_ext,
Command_GrantReplayAccess_ext,
Command_UpdateAdminNotes_ext,
Command_ViewLogHistory_ext,
Command_WarnUser_ext,
} from 'generated/proto/moderator_commands_pb';
import { Response_GetAdminNotes_ext } from 'generated/proto/response_get_admin_notes_pb';
import { Response_BanHistory_ext } from 'generated/proto/response_ban_history_pb';
import { Response_WarnHistory_ext } from 'generated/proto/response_warn_history_pb';
import { Response_WarnList_ext } from 'generated/proto/response_warn_list_pb';
import { Response_ViewLogHistory_ext } from 'generated/proto/response_viewlog_history_pb';
import { banFromServer } from './banFromServer';
import { forceActivateUser } from './forceActivateUser';
import { getAdminNotes } from './getAdminNotes';
@ -34,7 +51,8 @@ import { viewLogHistory } from './viewLogHistory';
import { warnUser } from './warnUser';
const { getLastSendOpts, invokeOnSuccess } = makeCallbackHelpers(
BackendService.sendModeratorCommand as vi.Mock
BackendService.sendModeratorCommand as vi.Mock,
2
);
beforeEach(() => vi.clearAllMocks());
@ -47,7 +65,7 @@ describe('banFromServer', () => {
it('calls sendModeratorCommand with Command_BanFromServer', () => {
banFromServer(30, 'alice', '1.2.3.4', 'reason', 'visible', 'cid', 1);
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(
'Command_BanFromServer',
Command_BanFromServer_ext,
expect.objectContaining({ minutes: 30, userName: 'alice' }),
expect.any(Object)
);
@ -67,7 +85,7 @@ describe('forceActivateUser', () => {
it('calls sendModeratorCommand with Command_ForceActivateUser', () => {
forceActivateUser('alice', 'mod1');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith('Command_ForceActivateUser', expect.any(Object), expect.any(Object));
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(Command_ForceActivateUser_ext, expect.any(Object), expect.any(Object));
});
it('onSuccess calls ModeratorPersistence.forceActivateUser', () => {
@ -85,16 +103,16 @@ describe('getAdminNotes', () => {
it('calls sendModeratorCommand with Command_GetAdminNotes', () => {
getAdminNotes('alice');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(
'Command_GetAdminNotes',
Command_GetAdminNotes_ext,
expect.any(Object),
expect.objectContaining({ responseName: 'Response_GetAdminNotes' })
expect.objectContaining({ responseExt: Response_GetAdminNotes_ext })
);
});
it('onSuccess calls ModeratorPersistence.getAdminNotes with notes', () => {
getAdminNotes('alice');
const resp = { notes: 'some notes' };
invokeOnSuccess(resp, { responseCode: 0, '.Response_GetAdminNotes.ext': resp });
invokeOnSuccess(resp, { responseCode: 0 });
expect(ModeratorPersistence.getAdminNotes).toHaveBeenCalledWith('alice', 'some notes');
});
});
@ -107,16 +125,16 @@ describe('getBanHistory', () => {
it('calls sendModeratorCommand with Command_GetBanHistory', () => {
getBanHistory('alice');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(
'Command_GetBanHistory',
Command_GetBanHistory_ext,
expect.any(Object),
expect.objectContaining({ responseName: 'Response_BanHistory' })
expect.objectContaining({ responseExt: Response_BanHistory_ext })
);
});
it('onSuccess calls ModeratorPersistence.banHistory with banList', () => {
getBanHistory('alice');
const resp = { banList: [{ id: 1 }] };
invokeOnSuccess(resp, { responseCode: 0, '.Response_BanHistory.ext': resp });
invokeOnSuccess(resp, { responseCode: 0 });
expect(ModeratorPersistence.banHistory).toHaveBeenCalledWith('alice', [{ id: 1 }]);
});
});
@ -129,16 +147,16 @@ describe('getWarnHistory', () => {
it('calls sendModeratorCommand with Command_GetWarnHistory', () => {
getWarnHistory('alice');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(
'Command_GetWarnHistory',
Command_GetWarnHistory_ext,
expect.any(Object),
expect.objectContaining({ responseName: 'Response_WarnHistory' })
expect.objectContaining({ responseExt: Response_WarnHistory_ext })
);
});
it('onSuccess calls ModeratorPersistence.warnHistory with warnList', () => {
getWarnHistory('alice');
const resp = { warnList: [{ id: 2 }] };
invokeOnSuccess(resp, { responseCode: 0, '.Response_WarnHistory.ext': resp });
invokeOnSuccess(resp, { responseCode: 0 });
expect(ModeratorPersistence.warnHistory).toHaveBeenCalledWith('alice', [{ id: 2 }]);
});
});
@ -151,16 +169,16 @@ describe('getWarnList', () => {
it('calls sendModeratorCommand with Command_GetWarnList', () => {
getWarnList('mod1', 'alice', 'US');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(
'Command_GetWarnList',
Command_GetWarnList_ext,
expect.any(Object),
expect.objectContaining({ responseName: 'Response_WarnList' })
expect.objectContaining({ responseExt: Response_WarnList_ext })
);
});
it('onSuccess calls ModeratorPersistence.warnListOptions with warning', () => {
getWarnList('mod1', 'alice', 'US');
const resp = { warning: ['w1', 'w2'] };
invokeOnSuccess(resp, { responseCode: 0, '.Response_WarnList.ext': resp });
invokeOnSuccess(resp, { responseCode: 0 });
expect(ModeratorPersistence.warnListOptions).toHaveBeenCalledWith(['w1', 'w2']);
});
});
@ -172,7 +190,7 @@ describe('grantReplayAccess', () => {
it('calls sendModeratorCommand with Command_GrantReplayAccess', () => {
grantReplayAccess(10, 'mod1');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith('Command_GrantReplayAccess', expect.any(Object), expect.any(Object));
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(Command_GrantReplayAccess_ext, expect.any(Object), expect.any(Object));
});
it('onSuccess calls ModeratorPersistence.grantReplayAccess', () => {
@ -189,7 +207,7 @@ describe('updateAdminNotes', () => {
it('calls sendModeratorCommand with Command_UpdateAdminNotes', () => {
updateAdminNotes('alice', 'new notes');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith('Command_UpdateAdminNotes', expect.any(Object), expect.any(Object));
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(Command_UpdateAdminNotes_ext, expect.any(Object), expect.any(Object));
});
it('onSuccess calls ModeratorPersistence.updateAdminNotes', () => {
@ -205,18 +223,18 @@ describe('updateAdminNotes', () => {
describe('viewLogHistory', () => {
it('calls sendModeratorCommand with Command_ViewLogHistory', () => {
viewLogHistory({ filters: 'all' } as any);
viewLogHistory({ dateRange: 7 } as any);
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(
'Command_ViewLogHistory',
Command_ViewLogHistory_ext,
expect.any(Object),
expect.objectContaining({ responseName: 'Response_ViewLogHistory' })
expect.objectContaining({ responseExt: Response_ViewLogHistory_ext })
);
});
it('onSuccess calls ModeratorPersistence.viewLogs with logMessage', () => {
viewLogHistory({ filters: 'all' } as any);
viewLogHistory({ dateRange: 7 } as any);
const resp = { logMessage: ['log1'] };
invokeOnSuccess(resp, { responseCode: 0, '.Response_ViewLogHistory.ext': resp });
invokeOnSuccess(resp, { responseCode: 0 });
expect(ModeratorPersistence.viewLogs).toHaveBeenCalledWith(['log1']);
});
});
@ -228,7 +246,7 @@ describe('warnUser', () => {
it('calls sendModeratorCommand with Command_WarnUser', () => {
warnUser('alice', 'bad behavior', 'cid');
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith('Command_WarnUser', expect.any(Object), expect.any(Object));
expect(BackendService.sendModeratorCommand).toHaveBeenCalledWith(Command_WarnUser_ext, expect.any(Object), expect.any(Object));
});
it('onSuccess calls ModeratorPersistence.warnUser', () => {

View file

@ -1,8 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import {
Command_UpdateAdminNotes_ext, Command_UpdateAdminNotesSchema,
} from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
export function updateAdminNotes(userName: string, notes: string): void {
BackendService.sendModeratorCommand('Command_UpdateAdminNotes', { userName, notes }, {
BackendService.sendModeratorCommand(Command_UpdateAdminNotes_ext, create(Command_UpdateAdminNotesSchema, { userName, notes }), {
onSuccess: () => {
ModeratorPersistence.updateAdminNotes(userName, notes);
},

View file

@ -1,10 +1,13 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ViewLogHistory_ext, Command_ViewLogHistorySchema } from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
import { Response_ViewLogHistory_ext } from 'generated/proto/response_viewlog_history_pb';
import { LogFilters } from 'types';
export function viewLogHistory(filters: LogFilters): void {
BackendService.sendModeratorCommand('Command_ViewLogHistory', filters, {
responseName: 'Response_ViewLogHistory',
BackendService.sendModeratorCommand(Command_ViewLogHistory_ext, create(Command_ViewLogHistorySchema, filters), {
responseExt: Response_ViewLogHistory_ext,
onSuccess: (response) => {
ModeratorPersistence.viewLogs(response.logMessage);
},

View file

@ -1,8 +1,11 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_WarnUser_ext, Command_WarnUserSchema } from 'generated/proto/moderator_commands_pb';
import { ModeratorPersistence } from '../../persistence';
export function warnUser(userName: string, reason: string, clientid?: string, removeMessages?: number): void {
BackendService.sendModeratorCommand('Command_WarnUser', { userName, reason, clientid, removeMessages }, {
const cmd = create(Command_WarnUserSchema, { userName, reason, clientid, removeMessages });
BackendService.sendModeratorCommand(Command_WarnUser_ext, cmd, {
onSuccess: () => {
ModeratorPersistence.warnUser(userName);
},

View file

@ -1,9 +1,11 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_CreateGame_ext, Command_CreateGameSchema } from 'generated/proto/room_commands_pb';
import { RoomPersistence } from '../../persistence';
import { GameConfig } from 'types';
export function createGame(roomId: number, gameConfig: GameConfig): void {
BackendService.sendRoomCommand(roomId, 'Command_CreateGame', gameConfig, {
BackendService.sendRoomCommand(roomId, Command_CreateGame_ext, create(Command_CreateGameSchema, gameConfig), {
onSuccess: () => {
RoomPersistence.gameCreated(roomId);
},

View file

@ -1,9 +1,11 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_JoinGame_ext, Command_JoinGameSchema } from 'generated/proto/room_commands_pb';
import { RoomPersistence } from '../../persistence';
import { JoinGameParams } from 'types';
export function joinGame(roomId: number, joinGameParams: JoinGameParams): void {
BackendService.sendRoomCommand(roomId, 'Command_JoinGame', joinGameParams, {
BackendService.sendRoomCommand(roomId, Command_JoinGame_ext, create(Command_JoinGameSchema, joinGameParams), {
onSuccess: () => {
RoomPersistence.joinedGame(roomId, joinGameParams.gameId);
},

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_LeaveRoom_ext, Command_LeaveRoomSchema } from 'generated/proto/room_commands_pb';
import { RoomPersistence } from '../../persistence';
export function leaveRoom(roomId: number): void {
BackendService.sendRoomCommand(roomId, 'Command_LeaveRoom', {}, {
BackendService.sendRoomCommand(roomId, Command_LeaveRoom_ext, create(Command_LeaveRoomSchema), {
onSuccess: () => {
RoomPersistence.leaveRoom(roomId);
},

View file

@ -15,6 +15,7 @@ vi.mock('../../persistence', () => ({
import { makeCallbackHelpers } from '../../__mocks__/callbackHelpers';
import { BackendService } from '../../services/BackendService';
import { RoomPersistence } from '../../persistence';
import { Command_CreateGame_ext, Command_JoinGame_ext, Command_LeaveRoom_ext, Command_RoomSay_ext } from 'generated/proto/room_commands_pb';
import { createGame } from './createGame';
import { joinGame } from './joinGame';
import { leaveRoom } from './leaveRoom';
@ -22,7 +23,7 @@ import { roomSay } from './roomSay';
const { getLastSendOpts, invokeOnSuccess } = makeCallbackHelpers(
BackendService.sendRoomCommand as vi.Mock,
// sendRoomCommand(roomId, commandName, params, options) — options at index 3
// sendRoomCommand(roomId, ext, value, options) — options at index 3
3
);
@ -35,7 +36,9 @@ describe('createGame', () => {
it('calls sendRoomCommand with Command_CreateGame', () => {
createGame(5, { maxPlayers: 4 } as any);
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(5, 'Command_CreateGame', { maxPlayers: 4 }, expect.any(Object));
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(
5, Command_CreateGame_ext, expect.objectContaining({ maxPlayers: 4 }), expect.any(Object)
);
});
it('onSuccess calls RoomPersistence.gameCreated with roomId', () => {
@ -52,7 +55,9 @@ describe('joinGame', () => {
it('calls sendRoomCommand with Command_JoinGame', () => {
joinGame(7, { gameId: 42, password: '' } as any);
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(7, 'Command_JoinGame', { gameId: 42, password: '' }, expect.any(Object));
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(
7, Command_JoinGame_ext, expect.objectContaining({ gameId: 42, password: '' }), expect.any(Object)
);
});
it('onSuccess calls RoomPersistence.joinedGame with roomId and gameId', () => {
@ -69,7 +74,7 @@ describe('leaveRoom', () => {
it('calls sendRoomCommand with Command_LeaveRoom', () => {
leaveRoom(3);
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(3, 'Command_LeaveRoom', {}, expect.any(Object));
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(3, Command_LeaveRoom_ext, expect.any(Object), expect.any(Object));
});
it('onSuccess calls RoomPersistence.leaveRoom with roomId', () => {
@ -86,7 +91,11 @@ describe('roomSay', () => {
it('calls sendRoomCommand with trimmed message', () => {
roomSay(2, ' hello ');
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(2, 'Command_RoomSay', { message: 'hello' }, expect.any(Object));
expect(BackendService.sendRoomCommand).toHaveBeenCalledWith(
2,
Command_RoomSay_ext,
expect.objectContaining({ message: 'hello' })
);
});
it('does not call sendRoomCommand when message is blank', () => {

View file

@ -1,4 +1,6 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_RoomSay_ext, Command_RoomSaySchema } from 'generated/proto/room_commands_pb';
export function roomSay(roomId: number, message: string): void {
const trimmed = message.trim();
@ -7,5 +9,5 @@ export function roomSay(roomId: number, message: string): void {
return;
}
BackendService.sendRoomCommand(roomId, 'Command_RoomSay', { message: trimmed }, {});
BackendService.sendRoomCommand(roomId, Command_RoomSay_ext, create(Command_RoomSaySchema, { message: trimmed }));
}

View file

@ -1,8 +1,11 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_AccountEdit_ext, Command_AccountEditSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
export function accountEdit(passwordCheck: string, realName?: string, email?: string, country?: string): void {
BackendService.sendSessionCommand('Command_AccountEdit', { passwordCheck, realName, email, country }, {
const cmd = create(Command_AccountEditSchema, { passwordCheck, realName, email, country });
BackendService.sendSessionCommand(Command_AccountEdit_ext, cmd, {
onSuccess: () => {
SessionPersistence.accountEditChanged(realName, email, country);
},

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_AccountImage_ext, Command_AccountImageSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
export function accountImage(image: Uint8Array): void {
BackendService.sendSessionCommand('Command_AccountImage', { image }, {
BackendService.sendSessionCommand(Command_AccountImage_ext, create(Command_AccountImageSchema, { image }), {
onSuccess: () => {
SessionPersistence.accountImageChanged(image);
},

View file

@ -1,8 +1,11 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_AccountPassword_ext, Command_AccountPasswordSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
export function accountPassword(oldPassword: string, newPassword: string, hashedNewPassword: string): void {
BackendService.sendSessionCommand('Command_AccountPassword', { oldPassword, newPassword, hashedNewPassword }, {
const cmd = create(Command_AccountPasswordSchema, { oldPassword, newPassword, hashedNewPassword });
BackendService.sendSessionCommand(Command_AccountPassword_ext, cmd, {
onSuccess: () => {
SessionPersistence.accountPasswordChange();
},

View file

@ -1,23 +1,25 @@
import { AccountActivationParams } from 'store';
import { StatusEnum, WebSocketConnectOptions } from 'types';
import { create } from '@bufbuild/protobuf';
import webClient from '../../WebClient';
import { BackendService } from '../../services/BackendService';
import { ProtoController } from '../../services/ProtoController';
import { Command_Activate_ext, Command_ActivateSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { Response_ResponseCode } from 'generated/proto/response_pb';
import { disconnect, login, updateStatus } from './';
export function activate(options: WebSocketConnectOptions, password?: string, passwordSalt?: string): void {
const { userName, token } = options as unknown as AccountActivationParams;
BackendService.sendSessionCommand('Command_Activate', {
BackendService.sendSessionCommand(Command_Activate_ext, create(Command_ActivateSchema, {
...webClient.clientConfig,
userName,
token,
}, {
}), {
onResponseCode: {
[ProtoController.root.Response.ResponseCode.RespActivationAccepted]: () => {
[Response_ResponseCode.RespActivationAccepted]: () => {
SessionPersistence.accountActivationSuccess();
login(options, password, passwordSalt);
},

View file

@ -1,4 +1,6 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_AddToList_ext, Command_AddToListSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
export function addToBuddyList(userName: string): void {
@ -10,7 +12,7 @@ export function addToIgnoreList(userName: string): void {
}
export function addToList(list: string, userName: string): void {
BackendService.sendSessionCommand('Command_AddToList', { list, userName }, {
BackendService.sendSessionCommand(Command_AddToList_ext, create(Command_AddToListSchema, { list, userName }), {
onSuccess: () => {
SessionPersistence.addToList(list, userName);
},

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DeckDelSchema, Command_DeckDel_ext } from 'generated/proto/command_deck_del_pb';
import { SessionPersistence } from '../../persistence';
export function deckDel(deckId: number): void {
BackendService.sendSessionCommand('Command_DeckDel', { deckId }, {
BackendService.sendSessionCommand(Command_DeckDel_ext, create(Command_DeckDelSchema, { deckId }), {
onSuccess: () => {
SessionPersistence.deleteServerDeck(deckId);
},

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DeckDelDirSchema, Command_DeckDelDir_ext } from 'generated/proto/command_deck_del_dir_pb';
import { SessionPersistence } from '../../persistence';
export function deckDelDir(path: string): void {
BackendService.sendSessionCommand('Command_DeckDelDir', { path }, {
BackendService.sendSessionCommand(Command_DeckDelDir_ext, create(Command_DeckDelDirSchema, { path }), {
onSuccess: () => {
SessionPersistence.deleteServerDeckDir(path);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DeckListSchema, Command_DeckList_ext } from 'generated/proto/command_deck_list_pb';
import { SessionPersistence } from '../../persistence';
import { Response_DeckList_ext } from 'generated/proto/response_deck_list_pb';
export function deckList(): void {
BackendService.sendSessionCommand('Command_DeckList', {}, {
responseName: 'Response_DeckList',
BackendService.sendSessionCommand(Command_DeckList_ext, create(Command_DeckListSchema), {
responseExt: Response_DeckList_ext,
onSuccess: (response) => {
SessionPersistence.updateServerDecks(response);
},

View file

@ -1,8 +1,10 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DeckNewDirSchema, Command_DeckNewDir_ext } from 'generated/proto/command_deck_new_dir_pb';
import { SessionPersistence } from '../../persistence';
export function deckNewDir(path: string, dirName: string): void {
BackendService.sendSessionCommand('Command_DeckNewDir', { path, dirName }, {
BackendService.sendSessionCommand(Command_DeckNewDir_ext, create(Command_DeckNewDirSchema, { path, dirName }), {
onSuccess: () => {
SessionPersistence.createServerDeckDir(path, dirName);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_DeckUploadSchema, Command_DeckUpload_ext } from 'generated/proto/command_deck_upload_pb';
import { SessionPersistence } from '../../persistence';
import { Response_DeckUpload_ext } from 'generated/proto/response_deck_upload_pb';
export function deckUpload(path: string, deckId: number, deckList: string): void {
BackendService.sendSessionCommand('Command_DeckUpload', { path, deckId, deckList }, {
responseName: 'Response_DeckUpload',
BackendService.sendSessionCommand(Command_DeckUpload_ext, create(Command_DeckUploadSchema, { path, deckId, deckList }), {
responseExt: Response_DeckUpload_ext,
onSuccess: (response) => {
SessionPersistence.uploadServerDeck(path, response.newFile);
},

View file

@ -1,19 +1,23 @@
import { ForgotPasswordChallengeParams } from 'store';
import { StatusEnum, WebSocketConnectOptions } from 'types';
import { create } from '@bufbuild/protobuf';
import webClient from '../../WebClient';
import { BackendService } from '../../services/BackendService';
import {
Command_ForgotPasswordChallenge_ext, Command_ForgotPasswordChallengeSchema,
} from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { disconnect, updateStatus } from './';
export function forgotPasswordChallenge(options: WebSocketConnectOptions): void {
const { userName, email } = options as unknown as ForgotPasswordChallengeParams;
BackendService.sendSessionCommand('Command_ForgotPasswordChallenge', {
BackendService.sendSessionCommand(Command_ForgotPasswordChallenge_ext, create(Command_ForgotPasswordChallengeSchema, {
...webClient.clientConfig,
userName,
email,
}, {
}), {
onSuccess: () => {
updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPassword();

View file

@ -1,20 +1,25 @@
import { ForgotPasswordParams } from 'store';
import { StatusEnum, WebSocketConnectOptions } from 'types';
import { create } from '@bufbuild/protobuf';
import webClient from '../../WebClient';
import { BackendService } from '../../services/BackendService';
import {
Command_ForgotPasswordRequest_ext, Command_ForgotPasswordRequestSchema,
} from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { Response_ForgotPasswordRequest_ext } from 'generated/proto/response_forgotpasswordrequest_pb';
import { disconnect, updateStatus } from './';
export function forgotPasswordRequest(options: WebSocketConnectOptions): void {
const { userName } = options as unknown as ForgotPasswordParams;
BackendService.sendSessionCommand('Command_ForgotPasswordRequest', {
BackendService.sendSessionCommand(Command_ForgotPasswordRequest_ext, create(Command_ForgotPasswordRequestSchema, {
...webClient.clientConfig,
userName,
}, {
responseName: 'Response_ForgotPasswordRequest',
}), {
responseExt: Response_ForgotPasswordRequest_ext,
onSuccess: (resp) => {
if (resp?.challengeEmail) {
updateStatus(StatusEnum.DISCONNECTED, null);

View file

@ -1,8 +1,13 @@
import { ForgotPasswordResetParams } from 'store';
import { StatusEnum, WebSocketConnectOptions } from 'types';
import { create } from '@bufbuild/protobuf';
import type { MessageInitShape } from '@bufbuild/protobuf';
import webClient from '../../WebClient';
import { BackendService } from '../../services/BackendService';
import {
Command_ForgotPasswordReset_ext, Command_ForgotPasswordResetSchema,
} from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { hashPassword } from '../../utils';
@ -11,19 +16,16 @@ import { disconnect, updateStatus } from '.';
export function forgotPasswordReset(options: WebSocketConnectOptions, newPassword?: string, passwordSalt?: string): void {
const { userName, token } = options as unknown as ForgotPasswordResetParams;
const params: any = {
const params: MessageInitShape<typeof Command_ForgotPasswordResetSchema> = {
...webClient.clientConfig,
userName,
token,
...(passwordSalt
? { hashedNewPassword: hashPassword(passwordSalt, newPassword) }
: { newPassword }),
};
if (passwordSalt) {
params.hashedNewPassword = hashPassword(passwordSalt, newPassword);
} else {
params.newPassword = newPassword;
}
BackendService.sendSessionCommand('Command_ForgotPasswordReset', params, {
BackendService.sendSessionCommand(Command_ForgotPasswordReset_ext, create(Command_ForgotPasswordResetSchema, params), {
onSuccess: () => {
updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPasswordSuccess();

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_GetGamesOfUser_ext, Command_GetGamesOfUserSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { Response_GetGamesOfUser_ext } from 'generated/proto/response_get_games_of_user_pb';
export function getGamesOfUser(userName: string): void {
BackendService.sendSessionCommand('Command_GetGamesOfUser', { userName }, {
responseName: 'Response_GetGamesOfUser',
BackendService.sendSessionCommand(Command_GetGamesOfUser_ext, create(Command_GetGamesOfUserSchema, { userName }), {
responseExt: Response_GetGamesOfUser_ext,
onSuccess: (response) => {
SessionPersistence.getGamesOfUser(userName, response);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_GetUserInfo_ext, Command_GetUserInfoSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { Response_GetUserInfo_ext } from 'generated/proto/response_get_user_info_pb';
export function getUserInfo(userName: string): void {
BackendService.sendSessionCommand('Command_GetUserInfo', { userName }, {
responseName: 'Response_GetUserInfo',
BackendService.sendSessionCommand(Command_GetUserInfo_ext, create(Command_GetUserInfoSchema, { userName }), {
responseExt: Response_GetUserInfo_ext,
onSuccess: (response) => {
SessionPersistence.getUserInfo(response.userInfo);
},

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_JoinRoom_ext, Command_JoinRoomSchema } from 'generated/proto/session_commands_pb';
import { RoomPersistence } from '../../persistence';
import { Response_JoinRoom_ext } from 'generated/proto/response_join_room_pb';
export function joinRoom(roomId: number): void {
BackendService.sendSessionCommand('Command_JoinRoom', { roomId }, {
responseName: 'Response_JoinRoom',
BackendService.sendSessionCommand(Command_JoinRoom_ext, create(Command_JoinRoomSchema, { roomId }), {
responseExt: Response_JoinRoom_ext,
onSuccess: (response) => {
RoomPersistence.joinRoom(response.roomInfo);
},

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ListRooms_ext, Command_ListRoomsSchema } from 'generated/proto/session_commands_pb';
export function listRooms(): void {
BackendService.sendSessionCommand('Command_ListRooms', {}, {});
BackendService.sendSessionCommand(Command_ListRooms_ext, create(Command_ListRoomsSchema));
}

View file

@ -1,9 +1,12 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_ListUsers_ext, Command_ListUsersSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { Response_ListUsers_ext } from 'generated/proto/response_list_users_pb';
export function listUsers(): void {
BackendService.sendSessionCommand('Command_ListUsers', {}, {
responseName: 'Response_ListUsers',
BackendService.sendSessionCommand(Command_ListUsers_ext, create(Command_ListUsersSchema), {
responseExt: Response_ListUsers_ext,
onSuccess: (response) => {
SessionPersistence.updateUsers(response.userList);
},

View file

@ -1,9 +1,13 @@
import { StatusEnum, WebSocketConnectOptions } from 'types';
import { create } from '@bufbuild/protobuf';
import type { MessageInitShape } from '@bufbuild/protobuf';
import webClient from '../../WebClient';
import { BackendService } from '../../services/BackendService';
import { ProtoController } from '../../services/ProtoController';
import { Command_Login_ext, Command_LoginSchema } from 'generated/proto/session_commands_pb';
import { hashPassword } from '../../utils';
import { SessionPersistence } from '../../persistence';
import { Response_Login_ext } from 'generated/proto/response_login_pb';
import { Response_ResponseCode } from 'generated/proto/response_pb';
import {
disconnect,
@ -15,20 +19,15 @@ import {
export function login(options: WebSocketConnectOptions, password?: string, passwordSalt?: string): void {
const { userName, hashedPassword } = options;
const loginConfig: any = {
const loginConfig: MessageInitShape<typeof Command_LoginSchema> = {
...webClient.clientConfig,
clientid: 'webatrice',
userName,
...(passwordSalt
? { hashedPassword: hashedPassword || hashPassword(passwordSalt, password) }
: { password }),
};
if (passwordSalt) {
loginConfig.hashedPassword = hashedPassword || hashPassword(passwordSalt, password);
} else {
loginConfig.password = password;
}
const { ResponseCode } = ProtoController.root.Response;
const onLoginError = (message: string, extra?: () => void) => {
updateStatus(StatusEnum.DISCONNECTED, message);
extra?.();
@ -36,8 +35,8 @@ export function login(options: WebSocketConnectOptions, password?: string, passw
disconnect();
};
BackendService.sendSessionCommand('Command_Login', loginConfig, {
responseName: 'Response_Login',
BackendService.sendSessionCommand(Command_Login_ext, create(Command_LoginSchema, loginConfig), {
responseExt: Response_Login_ext,
onSuccess: (resp) => {
const { buddyList, ignoreList, userInfo } = resp;
@ -53,23 +52,23 @@ export function login(options: WebSocketConnectOptions, password?: string, passw
updateStatus(StatusEnum.LOGGED_IN, 'Logged in.');
},
onResponseCode: {
[ResponseCode.RespClientUpdateRequired]: () =>
[Response_ResponseCode.RespClientUpdateRequired]: () =>
onLoginError('Login failed: missing features'),
[ResponseCode.RespWrongPassword]: () =>
[Response_ResponseCode.RespWrongPassword]: () =>
onLoginError('Login failed: incorrect username or password'),
[ResponseCode.RespUsernameInvalid]: () =>
[Response_ResponseCode.RespUsernameInvalid]: () =>
onLoginError('Login failed: incorrect username or password'),
[ResponseCode.RespWouldOverwriteOldSession]: () =>
[Response_ResponseCode.RespWouldOverwriteOldSession]: () =>
onLoginError('Login failed: duplicated user session'),
[ResponseCode.RespUserIsBanned]: () =>
[Response_ResponseCode.RespUserIsBanned]: () =>
onLoginError('Login failed: banned user'),
[ResponseCode.RespRegistrationRequired]: () =>
[Response_ResponseCode.RespRegistrationRequired]: () =>
onLoginError('Login failed: registration required'),
[ResponseCode.RespClientIdRequired]: () =>
[Response_ResponseCode.RespClientIdRequired]: () =>
onLoginError('Login failed: missing client ID'),
[ResponseCode.RespContextError]: () =>
[Response_ResponseCode.RespContextError]: () =>
onLoginError('Login failed: server error'),
[ResponseCode.RespAccountNotActivated]: () =>
[Response_ResponseCode.RespAccountNotActivated]: () =>
onLoginError('Login failed: account not activated',
() => {
const { password: _p, newPassword: _np, ...safeOptions } = options;

View file

@ -1,5 +1,7 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_Message_ext, Command_MessageSchema } from 'generated/proto/session_commands_pb';
export function message(userName: string, message: string): void {
BackendService.sendSessionCommand('Command_Message', { userName, message }, {});
BackendService.sendSessionCommand(Command_Message_ext, create(Command_MessageSchema, { userName, message }));
}

View file

@ -1,7 +1,9 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_Ping_ext, Command_PingSchema } from 'generated/proto/session_commands_pb';
export function ping(pingReceived: Function): void {
BackendService.sendSessionCommand('Command_Ping', {}, {
BackendService.sendSessionCommand(Command_Ping_ext, create(Command_PingSchema), {
onResponse: (raw) => pingReceived(raw),
});
}

View file

@ -1,73 +1,71 @@
import { ServerRegisterParams } from 'store';
import { StatusEnum, WebSocketConnectOptions } from 'types';
import { create } from '@bufbuild/protobuf';
import type { MessageInitShape } from '@bufbuild/protobuf';
import webClient from '../../WebClient';
import { BackendService } from '../../services/BackendService';
import { ProtoController } from '../../services/ProtoController';
import { Command_Register_ext, Command_RegisterSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
import { hashPassword } from '../../utils';
import { Response_ResponseCode } from 'generated/proto/response_pb';
import { login, disconnect, updateStatus } from './';
export function register(options: WebSocketConnectOptions, password?: string, passwordSalt?: string): void {
const { userName, email, country, realName } = options as ServerRegisterParams;
const params: any = {
const params: MessageInitShape<typeof Command_RegisterSchema> = {
...webClient.clientConfig,
userName,
email,
country,
realName,
...(passwordSalt
? { hashedPassword: hashPassword(passwordSalt, password) }
: { password }),
};
if (passwordSalt) {
params.hashedPassword = hashPassword(passwordSalt, password);
} else {
params.password = password;
}
const { ResponseCode } = ProtoController.root.Response;
const onRegistrationError = (action: () => void) => {
action();
updateStatus(StatusEnum.DISCONNECTED, 'Registration failed');
disconnect();
};
BackendService.sendSessionCommand('Command_Register', params, {
BackendService.sendSessionCommand(Command_Register_ext, create(Command_RegisterSchema, params), {
onResponseCode: {
[ResponseCode.RespRegistrationAccepted]: () => {
[Response_ResponseCode.RespRegistrationAccepted]: () => {
login(options, password, passwordSalt);
SessionPersistence.registrationSuccess();
},
[ResponseCode.RespRegistrationAcceptedNeedsActivation]: () => {
[Response_ResponseCode.RespRegistrationAcceptedNeedsActivation]: () => {
updateStatus(StatusEnum.DISCONNECTED, 'Registration accepted, awaiting activation');
const { password: _p, newPassword: _np, ...safeOptions } = options;
SessionPersistence.accountAwaitingActivation(safeOptions);
disconnect();
},
[ResponseCode.RespUserAlreadyExists]: () => onRegistrationError(
[Response_ResponseCode.RespUserAlreadyExists]: () => onRegistrationError(
() => SessionPersistence.registrationUserNameError('Username is taken')
),
[ResponseCode.RespUsernameInvalid]: () => onRegistrationError(
[Response_ResponseCode.RespUsernameInvalid]: () => onRegistrationError(
() => SessionPersistence.registrationUserNameError('Invalid username')
),
[ResponseCode.RespPasswordTooShort]: () => onRegistrationError(
[Response_ResponseCode.RespPasswordTooShort]: () => onRegistrationError(
() => SessionPersistence.registrationPasswordError('Your password was too short')
),
[ResponseCode.RespEmailRequiredToRegister]: () => onRegistrationError(
[Response_ResponseCode.RespEmailRequiredToRegister]: () => onRegistrationError(
() => SessionPersistence.registrationRequiresEmail()
),
[ResponseCode.RespEmailBlackListed]: () => onRegistrationError(
[Response_ResponseCode.RespEmailBlackListed]: () => onRegistrationError(
() => SessionPersistence.registrationEmailError('This email provider has been blocked')
),
[ResponseCode.RespTooManyRequests]: () => onRegistrationError(
[Response_ResponseCode.RespTooManyRequests]: () => onRegistrationError(
() => SessionPersistence.registrationEmailError('Max accounts reached for this email')
),
[ResponseCode.RespRegistrationDisabled]: () => onRegistrationError(
[Response_ResponseCode.RespRegistrationDisabled]: () => onRegistrationError(
() => SessionPersistence.registrationFailed('Registration is currently disabled')
),
[ResponseCode.RespUserIsBanned]: (raw) => onRegistrationError(
[Response_ResponseCode.RespUserIsBanned]: (raw) => onRegistrationError(
() => SessionPersistence.registrationFailed(raw.reasonStr, raw.endTime)
),
},

View file

@ -1,4 +1,6 @@
import { create } from '@bufbuild/protobuf';
import { BackendService } from '../../services/BackendService';
import { Command_RemoveFromList_ext, Command_RemoveFromListSchema } from 'generated/proto/session_commands_pb';
import { SessionPersistence } from '../../persistence';
export function removeFromBuddyList(userName: string): void {
@ -10,7 +12,7 @@ export function removeFromIgnoreList(userName: string): void {
}
export function removeFromList(list: string, userName: string): void {
BackendService.sendSessionCommand('Command_RemoveFromList', { list, userName }, {
BackendService.sendSessionCommand(Command_RemoveFromList_ext, create(Command_RemoveFromListSchema, { list, userName }), {
onSuccess: () => {
SessionPersistence.removeFromList(list, userName);
},

Some files were not shown because too many files have changed in this diff Show more