@pieai/swimmer-game-server-kit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,41 @@
1
+ PieAI Limited Use License 1.0
2
+
3
+ Copyright (c) 2026 PieAI. All rights reserved.
4
+
5
+ Subject to the restrictions below, PieAI grants you a limited,
6
+ non-exclusive, non-transferable, revocable license to:
7
+
8
+ 1. download and install this package;
9
+ 2. read the source code for evaluation and integration purposes;
10
+ 3. use the unmodified package as a dependency in your applications; and
11
+ 4. perform ordinary build-time transformations, including bundling,
12
+ transpilation, tree-shaking, and minification, solely to include the
13
+ package in an application.
14
+
15
+ You may not:
16
+
17
+ 1. modify or create derivative works from the source code or visual assets;
18
+ 2. redistribute, sublicense, publish, sell, or provide this package or its
19
+ visual assets as a standalone library, asset pack, template, or competing
20
+ product;
21
+ 3. extract or redistribute the visual assets separately from an application
22
+ that uses this package;
23
+ 4. remove or alter copyright, license, attribution, or proprietary notices;
24
+ or
25
+ 5. use PieAI names, logos, or trademarks to imply endorsement.
26
+
27
+ Distribution of bundled or minified application output is permitted only when
28
+ this package is an inseparable dependency of that application and is not
29
+ offered as a reusable library or asset collection.
30
+
31
+ This license does not grant ownership of any source code, visual asset,
32
+ trademark, or other intellectual property. Third-party materials, if any,
33
+ remain subject to their respective rights and terms.
34
+
35
+ THE SOFTWARE AND ASSETS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
36
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
37
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
38
+ PIEAI WILL NOT BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY ARISING
39
+ FROM THE SOFTWARE, ASSETS, OR THEIR USE.
40
+
41
+ Any use outside these terms requires prior written permission from PieAI.
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # SwimmerGameServerKit
2
+
3
+ Shared Colyseus game-server kit for PieAI Swimmer-based games.
4
+
5
+ This repository is the central template for PieAI multiplayer game servers.
6
+ Games such as Non-Heroes, Break, and future experiments should keep their own
7
+ gameplay rules, rooms, protocols, and product data, while sharing the server
8
+ shell that creates, deploys, verifies, and authenticates authoritative Colyseus
9
+ rooms.
10
+
11
+ ## Why This Exists
12
+
13
+ PieAI game projects should not each invent a different multiplayer server. The
14
+ standard server stack is:
15
+
16
+ - Colyseus / Colyseus Cloud for authoritative game rooms.
17
+ - `@colyseus/tools` app config for cloud-compatible server boot.
18
+ - `@colyseus/sdk` on clients.
19
+ - SwimmerBackend Supabase Auth JWTs for player identity.
20
+ - Project-prefixed environment variables.
21
+ - `/health` and `/rooms` HTTP probes.
22
+ - A reusable cloud smoke path before owner playtest.
23
+
24
+ Non-Heroes is the first mature source project for this standard. This kit
25
+ extracts the reusable shape without importing Non-Heroes gameplay.
26
+
27
+ ## Scope
28
+
29
+ This package owns:
30
+
31
+ - Generic Colyseus server app creation.
32
+ - Generic room registration.
33
+ - Project-prefixed server config resolution.
34
+ - SwimmerBackend JWT verification.
35
+ - Common `/health`, `/rooms`, and optional Colyseus monitor routes.
36
+ - Minimal Colyseus Cloud smoke helpers.
37
+ - A starter template for new game servers.
38
+
39
+ This package deliberately does not own:
40
+
41
+ - Game-specific protocol messages.
42
+ - Gameplay state machines or rules.
43
+ - Boss AI, card logic, chase logic, or combat logic.
44
+ - Product persistence schema.
45
+ - Supabase migrations.
46
+ - Cloud secrets or deployment credentials.
47
+ - A single shared production endpoint for every game.
48
+
49
+ Each game should deploy its own Colyseus Cloud application unless a later
50
+ platform decision creates a multi-game runtime service.
51
+
52
+ ## Install From A Product
53
+
54
+ Install the exact reviewed npm version:
55
+
56
+ ```json
57
+ {
58
+ "dependencies": {
59
+ "@pieai/swimmer-game-server-kit": "0.1.0"
60
+ }
61
+ }
62
+ ```
63
+
64
+ ## Server Usage
65
+
66
+ ```ts
67
+ import {
68
+ createSwimmerColyseusRoom,
69
+ createSwimmerGameServerApp,
70
+ defineSwimmerGame,
71
+ listenSwimmerGameServer,
72
+ resolveGameServerConfig
73
+ } from "@pieai/swimmer-game-server-kit";
74
+ import { createBreakWorld } from "./world.js";
75
+
76
+ const breakGame = defineSwimmerGame({
77
+ auth: { allowGuestInLocal: true, fallbackDisplayName: "Runner" },
78
+ createWorld: () => createBreakWorld(),
79
+ gameId: "break",
80
+ maxClients: 2,
81
+ roomName: "break_room",
82
+ tickRate: 30
83
+ });
84
+
85
+ const config = resolveGameServerConfig({
86
+ envPrefix: "BREAK",
87
+ serviceName: "break-game-server"
88
+ });
89
+
90
+ const app = createSwimmerGameServerApp({
91
+ config,
92
+ rooms: [{ name: breakGame.roomName, room: createSwimmerColyseusRoom(breakGame) }]
93
+ });
94
+
95
+ await listenSwimmerGameServer(app, config);
96
+ ```
97
+
98
+ The game project implements the world adapter. The Kit owns the Colyseus room
99
+ wrapper, handshake, local/cloud server shell, HTTP probes, auth bridge, and smoke
100
+ helpers.
101
+
102
+ ## Client Usage
103
+
104
+ ```ts
105
+ import { connectSwimmerGameClient } from "@pieai/swimmer-game-server-kit/client";
106
+
107
+ const client = await connectSwimmerGameClient({
108
+ endpoint: import.meta.env.VITE_BREAK_COLYSEUS_ENDPOINT,
109
+ joinOptions: { requestedPlayerId: "runner-a" },
110
+ onState: (state) => render(state),
111
+ onWelcome: ({ playerId }) => setLocalPlayer(playerId),
112
+ roomName: "break_room"
113
+ });
114
+
115
+ client.sendInput({ jump: true });
116
+ ```
117
+
118
+ ## Auth Usage
119
+
120
+ ```ts
121
+ import { Room } from "colyseus";
122
+ import { authenticateRoomJoin } from "@pieai/swimmer-game-server-kit/auth";
123
+
124
+ export class BreakRoom extends Room {
125
+ async onAuth(_client, options) {
126
+ return authenticateRoomJoin(options, {
127
+ env: process.env,
128
+ fallbackDisplayName: "Runner"
129
+ });
130
+ }
131
+ }
132
+ ```
133
+
134
+ ## Environment Contract
135
+
136
+ For a game prefix such as `BREAK`, the kit reads:
137
+
138
+ ```text
139
+ BREAK_DEPLOY_TARGET=cloud|local
140
+ BREAK_SERVER_PORT=2567
141
+ BREAK_E2E_SERVER_PORT=...
142
+ BREAK_SERVER_HOST=...
143
+ BREAK_ALLOWED_ORIGINS=https://break.pieaistudio.com
144
+ BREAK_ENABLE_COLYSEUS_MONITOR=0|1
145
+ SWIMMER_CORE_SUPABASE_URL=https://lgoknzuxefecikfyvpzk.supabase.co
146
+ SWIMMER_CORE_JWT_AUDIENCE=authenticated
147
+ ```
148
+
149
+ Client apps should still use a game-owned `VITE_COLYSEUS_ENDPOINT`.
150
+
151
+ ## Template
152
+
153
+ `templates/colyseus-game-server/` is a starter server package. Copy it into a
154
+ game repo as `server/game`, replace the sample room and room name, then wire the
155
+ game's shared protocol and gameplay engine.
156
+
157
+ ## Verification
158
+
159
+ ```bash
160
+ pnpm install
161
+ pnpm verify
162
+ ```
163
+
164
+ ## Upgrade Model
165
+
166
+ Improvements learned by any game should land here first when they are generic:
167
+
168
+ - deployment and environment checks;
169
+ - Colyseus Cloud compatibility;
170
+ - auth verification;
171
+ - local/dev port hygiene;
172
+ - cloud smoke patterns;
173
+ - test helpers;
174
+ - server skeleton changes.
175
+
176
+ Game-specific behavior stays in the game. Shared experience goes back into
177
+ SwimmerGameServerKit, then products upgrade to a reviewed npm version.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { type JWTVerifyGetKey } from "jose";
2
+ export type PlayerAuthErrorCode = "missing_access_token" | "invalid_access_token" | "invalid_swimmer_backend_user";
3
+ export declare class PlayerAuthError extends Error {
4
+ readonly code: PlayerAuthErrorCode;
5
+ readonly statusCode: number;
6
+ constructor(code: PlayerAuthErrorCode, message: string, statusCode?: number);
7
+ }
8
+ export interface SwimmerBackendAuthEnv {
9
+ audience: string;
10
+ issuer: string;
11
+ jwksUrl: string;
12
+ url: string;
13
+ }
14
+ export interface VerifiedPlayerIdentity {
15
+ displayName: string;
16
+ email: string;
17
+ userId: string;
18
+ }
19
+ export interface VerifySwimmerBackendAccessTokenOptions {
20
+ env?: Record<string, string | undefined>;
21
+ fallbackDisplayName?: string;
22
+ jwks?: JWTVerifyGetKey;
23
+ }
24
+ export declare const DEFAULT_SWIMMER_BACKEND_SUPABASE_URL = "https://lgoknzuxefecikfyvpzk.supabase.co";
25
+ export declare function resolveSwimmerBackendAuthEnv(env?: Record<string, string | undefined>): SwimmerBackendAuthEnv;
26
+ export declare function verifySwimmerBackendAccessToken(accessToken: string, options?: VerifySwimmerBackendAccessTokenOptions): Promise<VerifiedPlayerIdentity>;
27
+ export interface RoomAuthOptions {
28
+ accessToken?: string;
29
+ displayName?: string;
30
+ userId?: string;
31
+ }
32
+ export interface RoomAuthContext extends VerifiedPlayerIdentity {
33
+ verified: boolean;
34
+ }
35
+ export interface AuthenticateRoomJoinInput {
36
+ allowGuestInLocal?: boolean;
37
+ env?: Record<string, string | undefined>;
38
+ fallbackDisplayName?: string;
39
+ requireAuth?: boolean;
40
+ verifier?: (accessToken: string) => Promise<VerifiedPlayerIdentity>;
41
+ }
42
+ export declare function authenticateRoomJoin(options: RoomAuthOptions | undefined, input?: AuthenticateRoomJoinInput): Promise<RoomAuthContext>;
package/dist/auth.js ADDED
@@ -0,0 +1,99 @@
1
+ import { createRemoteJWKSet, jwtVerify } from "jose";
2
+ export class PlayerAuthError extends Error {
3
+ code;
4
+ statusCode;
5
+ constructor(code, message, statusCode = 401) {
6
+ super(message);
7
+ this.name = "PlayerAuthError";
8
+ this.code = code;
9
+ this.statusCode = statusCode;
10
+ }
11
+ }
12
+ export const DEFAULT_SWIMMER_BACKEND_SUPABASE_URL = "https://lgoknzuxefecikfyvpzk.supabase.co";
13
+ export function resolveSwimmerBackendAuthEnv(env = process.env) {
14
+ const rawUrl = env.SWIMMER_CORE_SUPABASE_URL ??
15
+ env.VITE_SWIMMER_CORE_SUPABASE_URL ??
16
+ DEFAULT_SWIMMER_BACKEND_SUPABASE_URL;
17
+ const url = rawUrl.replace(/\/+$/, "");
18
+ const issuer = `${url}/auth/v1`;
19
+ return {
20
+ audience: env.SWIMMER_CORE_JWT_AUDIENCE || "authenticated",
21
+ issuer,
22
+ jwksUrl: `${issuer}/.well-known/jwks.json`,
23
+ url
24
+ };
25
+ }
26
+ export async function verifySwimmerBackendAccessToken(accessToken, options = {}) {
27
+ const token = accessToken.trim();
28
+ if (!token) {
29
+ throw new PlayerAuthError("missing_access_token", "Missing SwimmerBackend access token.");
30
+ }
31
+ const authEnv = resolveSwimmerBackendAuthEnv(options.env);
32
+ const jwks = options.jwks ?? createRemoteJWKSet(new URL(authEnv.jwksUrl));
33
+ let payload;
34
+ try {
35
+ const result = await jwtVerify(token, jwks, {
36
+ audience: authEnv.audience,
37
+ issuer: authEnv.issuer
38
+ });
39
+ payload = result.payload;
40
+ }
41
+ catch {
42
+ throw new PlayerAuthError("invalid_access_token", "SwimmerBackend access token is invalid.");
43
+ }
44
+ if (typeof payload.sub !== "string" || !payload.sub) {
45
+ throw new PlayerAuthError("invalid_swimmer_backend_user", "SwimmerBackend user payload is invalid.");
46
+ }
47
+ const metadata = readObjectClaim(payload.user_metadata);
48
+ const email = readStringClaim(payload.email);
49
+ const metadataDisplayName = readStringClaim(metadata.display_name) || readStringClaim(metadata.name);
50
+ const fallbackName = options.fallbackDisplayName || (email ? email.split("@")[0] || "Player" : "Player");
51
+ return {
52
+ displayName: metadataDisplayName.trim() || fallbackName,
53
+ email,
54
+ userId: payload.sub
55
+ };
56
+ }
57
+ export async function authenticateRoomJoin(options, input = {}) {
58
+ const token = options?.accessToken?.trim();
59
+ const requireAuth = resolveRequireAuth(input);
60
+ if (token) {
61
+ try {
62
+ const verifier = input.verifier ?? ((value) => verifySwimmerBackendAccessToken(value, input));
63
+ return {
64
+ ...(await verifier(token)),
65
+ verified: true
66
+ };
67
+ }
68
+ catch (error) {
69
+ if (requireAuth)
70
+ throw error;
71
+ }
72
+ }
73
+ if (requireAuth) {
74
+ throw new PlayerAuthError("missing_access_token", "Missing verified SwimmerBackend room identity.");
75
+ }
76
+ if (input.allowGuestInLocal === false) {
77
+ throw new PlayerAuthError("missing_access_token", "Guest room identity is disabled.");
78
+ }
79
+ return {
80
+ displayName: options?.displayName?.trim() || input.fallbackDisplayName || "Guest",
81
+ email: "",
82
+ userId: options?.userId?.trim() || "",
83
+ verified: false
84
+ };
85
+ }
86
+ function resolveRequireAuth(input) {
87
+ if (input.requireAuth !== undefined)
88
+ return input.requireAuth;
89
+ return input.env?.SWIMMER_GAME_SERVER_REQUIRE_AUTH === "1" || input.env?.NODE_ENV === "production";
90
+ }
91
+ function readObjectClaim(value) {
92
+ return value && typeof value === "object" && !Array.isArray(value)
93
+ ? value
94
+ : {};
95
+ }
96
+ function readStringClaim(value) {
97
+ return typeof value === "string" ? value : "";
98
+ }
99
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAyC,MAAM,MAAM,CAAC;AAO5F,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAC/B,IAAI,CAAsB;IAC1B,UAAU,CAAS;IAE5B,YAAY,IAAyB,EAAE,OAAe,EAAE,UAAU,GAAG,GAAG;QACtE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF;AAqBD,MAAM,CAAC,MAAM,oCAAoC,GAAG,0CAA0C,CAAC;AAE/F,MAAM,UAAU,4BAA4B,CAC1C,MAA0C,OAAO,CAAC,GAAG;IAErD,MAAM,MAAM,GACV,GAAG,CAAC,yBAAyB;QAC7B,GAAG,CAAC,8BAA8B;QAClC,oCAAoC,CAAC;IAEvC,MAAM,GAAG,GAAG,MAAM,CAAC,O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ED,IAAI,KAAK,CAAC,iBAAiB,KAAK,KAAK,EAAE,CAAC;QACtC,MAAM,IAAI,eAAe,CAAC,sBAAsB,EAAE,kCAAkC,CAAC,CAAC;IACxF,CAAC;IAED,OAAO;QACL,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,KAAK,CAAC,mBAAmB,IAAI,OAAO;QACjF,KAAK,EAAE,EAAE;QACT,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE;QACrC,QAAQ,EAAE,KAAK;KAChB,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAgC;IAC1D,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,WAAW,CAAC;IAC9D,OAAO,KAAK,CAAC,GAAG,EAAE,gCAAgC,KAAK,GAAG,IAAI,KAAK,CAAC,GAAG,EAAE,QAAQ,KAAK,YAAY,CAAC;AACrG,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAChE,CAAC,CAAE,KAAiC;QACpC,CAAC,CAAC,EAAE,CAAC;AACT,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AAChD,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { type Room } from "@colyseus/sdk";
2
+ import { type SwimmerGameMessages } from "./definition.js";
3
+ export interface SwimmerGameClient<TInput, TSnapshot, TPlayerId extends string = string> {
4
+ readonly playerId: TPlayerId | null;
5
+ readonly room: Room<any, TSnapshot>;
6
+ leave(): Promise<void>;
7
+ sendInput(input: TInput): void;
8
+ sendRestart(): void;
9
+ }
10
+ export interface ConnectSwimmerGameClientOptions<TSnapshot extends object, TPlayerId extends string = string> {
11
+ endpoint: string;
12
+ joinOptions?: Record<string, unknown>;
13
+ messages?: Partial<SwimmerGameMessages>;
14
+ onError?: (message: string) => void;
15
+ onState?: (state: TSnapshot) => void;
16
+ onWelcome?: (welcome: {
17
+ playerId: TPlayerId;
18
+ state: TSnapshot;
19
+ }) => void;
20
+ roomName: string;
21
+ }
22
+ export declare function connectSwimmerGameClient<TInput, TSnapshot extends object, TPlayerId extends string = string>(options: ConnectSwimmerGameClientOptions<TSnapshot, TPlayerId>): Promise<SwimmerGameClient<TInput, TSnapshot, TPlayerId>>;
package/dist/client.js ADDED
@@ -0,0 +1,36 @@
1
+ import { Client } from "@colyseus/sdk";
2
+ import { resolveSwimmerGameMessages } from "./definition.js";
3
+ export async function connectSwimmerGameClient(options) {
4
+ const messages = resolveSwimmerGameMessages(options.messages);
5
+ const client = new Client(options.endpoint);
6
+ const room = await client.joinOrCreate(options.roomName, options.joinOptions ?? {});
7
+ let playerId = null;
8
+ room.onMessage(messages.welcome, (payload) => {
9
+ playerId = payload.playerId;
10
+ options.onWelcome?.(payload);
11
+ options.onState?.(payload.state);
12
+ });
13
+ room.onMessage(messages.state, (payload) => {
14
+ options.onState?.(payload.state);
15
+ });
16
+ room.onMessage(messages.error, (payload) => {
17
+ options.onError?.(payload.message ?? "Unknown game server error.");
18
+ });
19
+ room.send(messages.identify);
20
+ return {
21
+ get playerId() {
22
+ return playerId;
23
+ },
24
+ room,
25
+ async leave() {
26
+ await room.leave();
27
+ },
28
+ sendInput(input) {
29
+ room.send(messages.input, { input });
30
+ },
31
+ sendRestart() {
32
+ room.send(messages.restart);
33
+ }
34
+ };
35
+ }
36
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,0BAA0B,EAA4B,MAAM,iBAAiB,CAAC;AAoBvF,M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AI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACvC,CAAC;QACD,WAAW;YACT,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAC9B,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,14 @@
1
+ export interface CloudSmokeResult {
2
+ health: unknown;
3
+ httpEndpoint: string;
4
+ roomId: string;
5
+ rooms: unknown;
6
+ }
7
+ export interface RunColyseusCloudSmokeOptions {
8
+ createOptions?: Record<string, unknown>;
9
+ endpoint: string;
10
+ fetchImpl?: typeof fetch;
11
+ roomName: string;
12
+ }
13
+ export declare function runColyseusCloudSmoke(options: RunColyseusCloudSmokeOptions): Promise<CloudSmokeResult>;
14
+ export declare function websocketToHttpEndpoint(endpoint: string): string;
@@ -0,0 +1,40 @@
1
+ import { Client } from "@colyseus/sdk";
2
+ export async function runColyseusCloudSmoke(options) {
3
+ const endpoint = options.endpoint.trim();
4
+ if (!endpoint)
5
+ throw new Error("Missing Colyseus endpoint.");
6
+ const fetchImpl = options.fetchImpl ?? fetch;
7
+ const httpEndpoint = websocketToHttpEndpoint(endpoint).replace(/\/$/, "");
8
+ const health = await fetchJson(fetchImpl, `${httpEndpoint}/health`, "health");
9
+ const rooms = await fetchJson(fetchImpl, `${httpEndpoint}/rooms`, "rooms");
10
+ const client = new Client(endpoint);
11
+ let room;
12
+ try {
13
+ room = await client.create(options.roomName, options.createOptions ?? {});
14
+ return {
15
+ health,
16
+ httpEndpoint,
17
+ roomId: room.roomId,
18
+ rooms
19
+ };
20
+ }
21
+ finally {
22
+ if (room)
23
+ await room.leave();
24
+ }
25
+ }
26
+ export function websocketToHttpEndpoint(endpoint) {
27
+ if (/^wss:\/\//i.test(endpoint))
28
+ return endpoint.replace(/^wss/i, "https");
29
+ if (/^ws:\/\//i.test(endpoint))
30
+ return endpoint.replace(/^ws/i, "http");
31
+ throw new Error(`Invalid Colyseus websocket endpoint: ${endpoint}`);
32
+ }
33
+ async function fetchJson(fetchImpl, url, label) {
34
+ const response = await fetchImpl(url);
35
+ if (!response.ok) {
36
+ throw new Error(`Colyseus cloud smoke ${label} failed: ${response.status} ${response.statusText}`);
37
+ }
38
+ return response.json();
39
+ }
40
+ //# sourceMappingURL=cloud-smoke.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-smoke.js","sourceRoot":"","sources":["../src/cloud-smoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,MAAM,eAAe,CAAC;AAgBlD,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,OAAqC;IAErC,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzC,IAAI,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,KAAK,CAAC;IAC7C,MAAM,YAAY,GAAG,uBAAuB,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAE1E,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,SAAS,EAAE,GAAG,YAAY,SAAS,EAAE,QAAQ,CAAC,CAAC;IAC9E,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,SAAS,EAAE,GAAG,YAAY,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC3E,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC;IACpC,IAAI,IAAsB,CAAC;IAC3B,IAAI,CAAC;QACH,IAAI,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,aAAa,IAAI,EAAE,CAAC,CAAC;QAC1E,OAAO;YACL,MAAM;YACN,YAAY;YACZ,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK;SACN,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,IAAI,IAAI;YAAE,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;AACH,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,QAAgB;IACtD,IAAI,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3E,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxE,MAAM,IAAI,KAAK,CAAC,wCAAwC,QAAQ,EAAE,CAAC,CAAC;AACtE,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,SAAuB,EAAE,GAAW,EAAE,KAAa;IAC1E,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,GAAG,CAAC,CAAC;IACtC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,wBAAwB,KAAK,YAAY,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;IACrG,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,EAAsB,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { Room } from "colyseus";
2
+ import { type RoomAuthOptions } from "./auth.js";
3
+ import { type SwimmerGameDefinition } from "./definition.js";
4
+ export type SwimmerColyseusJoinOptions<TJoinOptions = unknown> = RoomAuthOptions & TJoinOptions & {
5
+ displayName?: string;
6
+ userId?: string;
7
+ };
8
+ export declare function createSwimmerColyseusRoom<TInput, TSnapshot extends object, TPlayerId extends string = string, TJoinOptions = unknown>(definition: SwimmerGameDefinition<TInput, TSnapshot, TPlayerId, TJoinOptions>): new () => Room<{
9
+ state: TSnapshot;
10
+ }>;
@@ -0,0 +1,106 @@
1
+ import { Room } from "colyseus";
2
+ import { authenticateRoomJoin } from "./auth.js";
3
+ import { resolveSwimmerGameMessages } from "./definition.js";
4
+ export function createSwimmerColyseusRoom(definition) {
5
+ const messages = resolveSwimmerGameMessages(definition.messages);
6
+ return class SwimmerGeneratedColyseusRoom extends Room {
7
+ maxClients = definition.maxClients;
8
+ playerBySessionId = new Map();
9
+ world;
10
+ async onAuth(_client, options) {
11
+ return authenticateRoomJoin(options, createAuthInput(definition));
12
+ }
13
+ onCreate(options) {
14
+ this.world = definition.createWorld(options === undefined ? { roomId: this.roomId } : { roomId: this.roomId, createOptions: options });
15
+ this.setState(this.world.snapshot());
16
+ this.onMessage(messages.input, (client, payload) => {
17
+ const playerId = this.playerBySessionId.get(client.sessionId);
18
+ if (!playerId) {
19
+ this.sendError(client, "Join before sending input.");
20
+ return;
21
+ }
22
+ this.world.setInput(playerId, unwrapInputPayload(payload));
23
+ });
24
+ this.onMessage(messages.identify, (client) => {
25
+ this.sendWelcome(client);
26
+ });
27
+ this.onMessage(messages.restart, (client) => {
28
+ const playerId = this.playerBySessionId.get(client.sessionId);
29
+ this.world.restart?.(playerId);
30
+ this.broadcastSnapshot();
31
+ });
32
+ this.setSimulationInterval(() => {
33
+ this.world.step(1 / definition.tickRate);
34
+ this.broadcastSnapshot();
35
+ }, 1000 / definition.tickRate);
36
+ }
37
+ onJoin(client, options, auth) {
38
+ const joinContext = createJoinContext(client, options, auth);
39
+ const playerId = this.world.assignPlayer(joinContext);
40
+ if (!playerId) {
41
+ throw new Error("Room is full.");
42
+ }
43
+ this.playerBySessionId.set(client.sessionId, playerId);
44
+ this.world.connectPlayer(playerId, joinContext);
45
+ this.broadcastSnapshot();
46
+ }
47
+ onLeave(client) {
48
+ const playerId = this.playerBySessionId.get(client.sessionId);
49
+ if (!playerId)
50
+ return;
51
+ this.playerBySessionId.delete(client.sessionId);
52
+ this.world.disconnectPlayer(playerId);
53
+ this.broadcastSnapshot();
54
+ }
55
+ onDispose() {
56
+ this.world?.dispose?.();
57
+ }
58
+ broadcastSnapshot(snapshot = this.world.snapshot()) {
59
+ this.setState(snapshot);
60
+ this.broadcast(messages.state, { state: snapshot });
61
+ }
62
+ sendError(client, message) {
63
+ client.send(messages.error, { message });
64
+ }
65
+ sendWelcome(client) {
66
+ const playerId = this.playerBySessionId.get(client.sessionId);
67
+ if (!playerId) {
68
+ this.sendError(client, "Join before identifying.");
69
+ return;
70
+ }
71
+ client.send(messages.welcome, { playerId, state: this.world.snapshot() });
72
+ }
73
+ };
74
+ }
75
+ function createAuthInput(definition) {
76
+ const input = {
77
+ env: process.env
78
+ };
79
+ if (definition.auth?.allowGuestInLocal !== undefined) {
80
+ input.allowGuestInLocal = definition.auth.allowGuestInLocal;
81
+ }
82
+ if (definition.auth?.fallbackDisplayName !== undefined) {
83
+ input.fallbackDisplayName = definition.auth.fallbackDisplayName;
84
+ }
85
+ if (definition.auth?.requireAuth !== undefined) {
86
+ input.requireAuth = definition.auth.requireAuth;
87
+ }
88
+ return input;
89
+ }
90
+ function createJoinContext(client, options, auth) {
91
+ return {
92
+ displayName: auth?.displayName ?? options?.displayName ?? "Guest",
93
+ email: auth?.email ?? "",
94
+ options: (options ?? {}),
95
+ sessionId: client.sessionId,
96
+ userId: auth?.userId ?? options?.userId ?? "",
97
+ verified: auth?.verified ?? false
98
+ };
99
+ }
100
+ function unwrapInputPayload(payload) {
101
+ if (payload && typeof payload === "object" && "input" in payload) {
102
+ return payload.input;
103
+ }
104
+ return payload;
105
+ }
106
+ //# sourceMappingURL=colyseus-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"colyseus-adapter.js","sourceRoot":"","sources":["../src/colyseus-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,IAAI,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,oBAAoB,EAAwB,MAAM,WAAW,CAAC;AACvE,OAAO,EACL,0BAA0B,EAI3B,MAAM,iBAAiB,CAAC;AAQzB,MAAM,UAAU,yBAAyB,CAMvC,UAA6E;IAE7E,MAAM,QAAQ,GAAG,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iBAAiB,KAAK,SAAS,EAAE,CAAC;QACrD,KAAK,CAAC,iBAAiB,GAAG,UAAU,CAAC,IAAI,CAAC,iBAAiB,CAAC;IAC9D,CAAC;IACD,IAAI,UAAU,CAAC,IAAI,EAAE,mBAAmB,KAAK,SAAS,EAAE,CAAC;QACvD,KAAK,CAAC,mBAAmB,GAAG,UAAU,CAAC,IAAI,CAAC,mBAAmB,CAAC;IAClE,CAAC;IACD,IAAI,UAAU,CAAC,IAAI,EAAE,WAAW,KAAK,SAAS,EAAE,CAAC;QAC/C,KAAK,CAAC,WAAW,GAAG,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC;IAClD,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,iBAAiB,CACxB,MAAc,EACd,OAA6D,EAC7D,IAAkE;IAElE,OAAO;QACL,WAAW,EAAE,IAAI,EAAE,WAAW,IAAI,OAAO,EAAE,WAAW,IAAI,OAAO;QACjE,KAAK,EAAE,IAAI,EAAE,KAAK,IAAI,EAAE;QACxB,OAAO,EAAE,CAAC,OAAO,IAAI,EAAE,CAAiB;QACxC,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,MAAM,EAAE,IAAI,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,IAAI,EAAE;QAC7C,QAAQ,EAAE,IAAI,EAAE,QAAQ,IAAI,KAAK;KAClC,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAS,OAAgB;IAClD,IAAI,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,IAAI,OAAO,EAAE,CAAC;QACjE,OAAQ,OAA6B,CAAC,KAAK,CAAC;IAC9C,CAAC;IACD,OAAO,OAAiB,CAAC;AAC3B,CAAC"}
@@ -0,0 +1,33 @@
1
+ import { type Room } from "colyseus";
2
+ import type { Application } from "express";
3
+ import type { GameServerConfig } from "./config.js";
4
+ type RoomConstructor = new (...args: any[]) => Room;
5
+ export interface GameRoomRegistration {
6
+ name: string;
7
+ room: RoomConstructor;
8
+ /**
9
+ * Matchmaking partition keys forwarded to Colyseus' RegisteredHandler.filterBy.
10
+ * joinOrCreate calls only match rooms whose create options agree on these keys
11
+ * (e.g. ['roomCode'] gives one room per invite code).
12
+ */
13
+ filterBy?: readonly string[];
14
+ }
15
+ export interface SwimmerGameTransportOptions {
16
+ pingInterval?: number;
17
+ pingMaxRetries?: number;
18
+ }
19
+ export interface CreateSwimmerGameServerAppOptions {
20
+ config: GameServerConfig;
21
+ displayLogs?: boolean;
22
+ extraHealth?: Record<string, unknown> | (() => Record<string, unknown>);
23
+ initializeExpress?: (app: Application) => void;
24
+ rooms: readonly GameRoomRegistration[];
25
+ transport?: SwimmerGameTransportOptions;
26
+ }
27
+ export declare function createSwimmerGameServerApp(options: CreateSwimmerGameServerAppOptions): import("colyseus").ConfigOptions<{
28
+ [k: string]: import("colyseus").RegisteredHandler<Room<import("colyseus").RoomOptions>>;
29
+ }, any>;
30
+ export declare function listenSwimmerGameServer(app: ReturnType<typeof createSwimmerGameServerApp>, config: GameServerConfig): Promise<import("colyseus").Server<{
31
+ [k: string]: import("colyseus").RegisteredHandler<Room<import("colyseus").RoomOptions>>;
32
+ }, any>>;
33
+ export {};
@@ -0,0 +1,37 @@
1
+ import defineServer, { listen } from "@colyseus/tools";
2
+ import { WebSocketTransport } from "@colyseus/ws-transport";
3
+ import { defineRoom } from "colyseus";
4
+ import { configureGameServerHttpRoutes } from "./http.js";
5
+ export function createSwimmerGameServerApp(options) {
6
+ const roomDefinitions = Object.fromEntries(options.rooms.map((registration) => {
7
+ const handler = defineRoom(registration.room);
8
+ if (registration.filterBy && registration.filterBy.length > 0) {
9
+ handler.filterBy([...registration.filterBy]);
10
+ }
11
+ return [registration.name, handler];
12
+ }));
13
+ const roomNames = options.rooms.map((registration) => registration.name);
14
+ const transport = options.transport;
15
+ return defineServer({
16
+ displayLogs: options.displayLogs ?? true,
17
+ // Mirror @colyseus/tools' default transport, layering the caller's ping
18
+ // settings on top of the runtime-provided options (http server handle).
19
+ ...(transport === undefined ? {} : {
20
+ initializeTransport: (transportOptions) => new WebSocketTransport({ ...transportOptions, ...transport })
21
+ }),
22
+ rooms: roomDefinitions,
23
+ initializeExpress(app) {
24
+ configureGameServerHttpRoutes(app, options.config, options.extraHealth === undefined
25
+ ? { roomNames }
26
+ : {
27
+ extraHealth: options.extraHealth,
28
+ roomNames
29
+ });
30
+ options.initializeExpress?.(app);
31
+ }
32
+ });
33
+ }
34
+ export function listenSwimmerGameServer(app, config) {
35
+ return listen(app, config.port);
36
+ }
37
+ //# sourceMappingURL=colyseus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"colyseus.js","sourceRoot":"","sources":["../src/colyseus.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,EAAE,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAa,MAAM,UAAU,CAAC;AAEjD,OAAO,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC;AAiC1D,MAAM,UAAU,0BAA0B,CAAC,OAA0C;IACnF,MAAM,eAAe,GAAG,MAAM,CAAC,WAAW,CACxC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE;QACjC,MAAM,OAAO,GAAG,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAC9C,IAAI,YAAY,CAAC,QAAQ,IAAI,YAAY,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9D,OAAO,CAAC,QAAQ,CAAC,CAAC,GAAG,YAAY,CAAC,QAAQ,CAA2C,CAAC,CAAC;QACzF,CAAC;QACD,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC,CAAC,CACH,CAAC;IACF,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAEzE,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;IAEpC,OAAO,YAAY,CAAC;QAClB,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,IAAI;QACxC,wEAAwE;QACxE,wEAAwE;QACxE,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YACjC,mBAAmB,EAAE,CAAC,gBAAyC,EAAE,EAAE,CACjE,IAAI,kBAAkB,CAAC,EAAE,GAAG,gBAAgB,EAAE,GAAG,SAAS,EAAE,CAAC;SAChE,CAAC;QACF,KAAK,EAAE,eAAe;QACtB,iBAAiB,CAAC,GAAG;YACnB,6BAA6B,CAC3B,GAAG,EACH,OAAO,CAAC,MAAM,EACd,OAAO,CAAC,WAAW,KAAK,SAAS;gBAC/B,CAAC,CAAC,EAAE,SAAS,EAAE;gBACf,CAAC,CAAC;oBACE,WAAW,EAAE,OAAO,CAAC,WAAW;oBAChC,SAAS;iBACV,CACN,CAAC;YACF,OAAO,CAAC,iBAAiB,EAAE,CAAC,GAAG,CAAC,CAAC;QACnC,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,GAAkD,EAClD,MAAwB;IAExB,OAAO,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC"}
@@ -0,0 +1,20 @@
1
+ export interface GameServerConfig {
2
+ corsOrigin: string[] | true;
3
+ deployTarget: "cloud" | "local" | "production" | string;
4
+ enableMonitor: boolean;
5
+ host: string;
6
+ isProductionLike: boolean;
7
+ port: number;
8
+ serviceName: string;
9
+ }
10
+ export interface GameServerConfigInput {
11
+ defaultPort?: number;
12
+ envPrefix: string;
13
+ localHost?: string;
14
+ serviceName: string;
15
+ }
16
+ type Env = Record<string, string | undefined>;
17
+ export declare function resolveGameServerConfig(input: GameServerConfigInput, env?: Env): GameServerConfig;
18
+ export declare function readEnv(env: Env, prefix: string, suffix: string): string | undefined;
19
+ export declare function normalizeEnvPrefix(prefix: string): string;
20
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,50 @@
1
+ export function resolveGameServerConfig(input, env = process.env) {
2
+ const defaultPort = input.defaultPort ?? 2567;
3
+ const deployTarget = readEnv(env, input.envPrefix, "DEPLOY_TARGET") ?? "local";
4
+ const isProductionLike = env.NODE_ENV === "production" || deployTarget === "cloud";
5
+ const rawPort = readEnv(env, input.envPrefix, "SERVER_PORT") ??
6
+ (!isProductionLike ? readEnv(env, input.envPrefix, "E2E_SERVER_PORT") : undefined) ??
7
+ env.PORT ??
8
+ String(defaultPort);
9
+ const port = Number(rawPort);
10
+ if (!Number.isInteger(port) || port <= 0) {
11
+ throw new Error(`Invalid ${input.serviceName} game server port: ${rawPort}`);
12
+ }
13
+ const host = readEnv(env, input.envPrefix, "SERVER_HOST") ??
14
+ (isProductionLike ? "0.0.0.0" : input.localHost ?? "127.0.0.1");
15
+ return {
16
+ corsOrigin: readCorsOrigin(input.envPrefix, env),
17
+ deployTarget,
18
+ enableMonitor: readEnableMonitor(input.envPrefix, env, isProductionLike),
19
+ host,
20
+ isProductionLike,
21
+ port,
22
+ serviceName: input.serviceName
23
+ };
24
+ }
25
+ export function readEnv(env, prefix, suffix) {
26
+ return env[`${normalizeEnvPrefix(prefix)}_${suffix}`]?.trim() || undefined;
27
+ }
28
+ export function normalizeEnvPrefix(prefix) {
29
+ const normalized = prefix.trim().toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
30
+ if (!normalized)
31
+ throw new Error("Game server env prefix cannot be empty.");
32
+ return normalized;
33
+ }
34
+ function readCorsOrigin(prefix, env) {
35
+ const rawOrigins = readEnv(env, prefix, "ALLOWED_ORIGINS");
36
+ if (!rawOrigins)
37
+ return true;
38
+ const origins = rawOrigins
39
+ .split(",")
40
+ .map((origin) => origin.trim())
41
+ .filter(Boolean);
42
+ return origins.length ? origins : true;
43
+ }
44
+ function readEnableMonitor(prefix, env, isProductionLike) {
45
+ const rawValue = readEnv(env, prefix, "ENABLE_COLYSEUS_MONITOR")?.toLowerCase();
46
+ if (rawValue)
47
+ return rawValue === "1" || rawValue === "true" || rawValue === "yes";
48
+ return !isProductionLike;
49
+ }
50
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAmBA,MAAM,UAAU,uBAAuB,CACrC,KAA4B,EAC5B,MAAW,OAAO,CAAC,GAAG;IAEtB,MAAM,WAAW,GAAG,KAAK,CAAC,WAAW,IAAI,IAAI,CAAC;IAC9C,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,SAAS,EAAE,eAAe,CAAC,IAAI,OAAO,CAAC;IAC/E,MAAM,gBAAgB,GAAG,GAAG,CAAC,QAAQ,KAAK,YAAY,IAAI,YAAY,KAAK,OAAO,CAAC;IACnF,MAAM,OAAO,GACX,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,SAAS,EAAE,aAAa,CAAC;QAC5C,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAClF,GAAG,CAAC,IAAI;QACR,MAAM,CAAC,WAAW,CAAC,CAAC;IACtB,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAC7B,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,WAAW,KAAK,CAAC,WAAW,sBAAsB,OAAO,EAAE,CAAC,CAAC;IAC/E,CAAC;IAED,MAAM,IAAI,GACR,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,SAAS,EAAE,aA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C;IACnB,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;AACzC,CAAC;AAED,SAAS,iBAAiB,CAAC,MAAc,EAAE,GAAQ,EAAE,gBAAyB;IAC5E,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,yBAAyB,CAAC,EAAE,WAAW,EAAE,CAAC;IAChF,IAAI,QAAQ;QAAE,OAAO,QAAQ,KAAK,GAAG,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KAAK,KAAK,CAAC;IACnF,OAAO,CAAC,gBAAgB,CAAC;AAC3B,CAAC"}
@@ -0,0 +1,48 @@
1
+ import type { RoomAuthContext } from "./auth.js";
2
+ export interface SwimmerGameContext {
3
+ roomId: string;
4
+ /**
5
+ * Raw options the creating client sent to joinOrCreate/create. Lets a game
6
+ * derive per-room state (e.g. a private room code) from the first joiner.
7
+ */
8
+ createOptions?: Record<string, unknown>;
9
+ }
10
+ export interface SwimmerJoinContext<TJoinOptions = unknown> extends RoomAuthContext {
11
+ options: TJoinOptions;
12
+ sessionId: string;
13
+ }
14
+ export interface SwimmerGameWorld<TInput, TSnapshot extends object, TPlayerId extends string = string, TJoinOptions = unknown> {
15
+ assignPlayer(client: SwimmerJoinContext<TJoinOptions>): TPlayerId | null;
16
+ connectPlayer(playerId: TPlayerId, client: SwimmerJoinContext<TJoinOptions>): void;
17
+ disconnectPlayer(playerId: TPlayerId): void;
18
+ restart?(actor?: TPlayerId): void;
19
+ setInput(playerId: TPlayerId, input: TInput): void;
20
+ snapshot(): TSnapshot;
21
+ step(deltaSeconds: number): void;
22
+ dispose?(): void;
23
+ }
24
+ export interface SwimmerGameMessages {
25
+ error: string;
26
+ identify: string;
27
+ input: string;
28
+ restart: string;
29
+ state: string;
30
+ welcome: string;
31
+ }
32
+ export interface SwimmerGameAuthOptions {
33
+ allowGuestInLocal?: boolean;
34
+ fallbackDisplayName?: string;
35
+ requireAuth?: boolean;
36
+ }
37
+ export interface SwimmerGameDefinition<TInput, TSnapshot extends object, TPlayerId extends string = string, TJoinOptions = unknown> {
38
+ auth?: SwimmerGameAuthOptions;
39
+ createWorld(context: SwimmerGameContext): SwimmerGameWorld<TInput, TSnapshot, TPlayerId, TJoinOptions>;
40
+ gameId: string;
41
+ maxClients: number;
42
+ messages?: Partial<SwimmerGameMessages>;
43
+ roomName: string;
44
+ tickRate: number;
45
+ }
46
+ export declare const defaultSwimmerGameMessages: SwimmerGameMessages;
47
+ export declare function defineSwimmerGame<TInput, TSnapshot extends object, TPlayerId extends string = string, TJoinOptions = unknown>(definition: SwimmerGameDefinition<TInput, TSnapshot, TPlayerId, TJoinOptions>): SwimmerGameDefinition<TInput, TSnapshot, TPlayerId, TJoinOptions>;
48
+ export declare function resolveSwimmerGameMessages(messages: Partial<SwimmerGameMessages> | undefined): SwimmerGameMessages;
@@ -0,0 +1,31 @@
1
+ export const defaultSwimmerGameMessages = {
2
+ error: "error",
3
+ identify: "identify",
4
+ input: "input",
5
+ restart: "restart",
6
+ state: "state",
7
+ welcome: "welcome"
8
+ };
9
+ export function defineSwimmerGame(definition) {
10
+ validateSwimmerGameDefinition(definition);
11
+ return definition;
12
+ }
13
+ export function resolveSwimmerGameMessages(messages) {
14
+ return {
15
+ ...defaultSwimmerGameMessages,
16
+ ...messages
17
+ };
18
+ }
19
+ function validateSwimmerGameDefinition(definition) {
20
+ if (!definition.gameId.trim())
21
+ throw new Error("Swimmer game id cannot be empty.");
22
+ if (!definition.roomName.trim())
23
+ throw new Error("Swimmer game room name cannot be empty.");
24
+ if (!Number.isInteger(definition.maxClients) || definition.maxClients <= 0) {
25
+ throw new Error(`Invalid maxClients for ${definition.gameId}: ${definition.maxClients}`);
26
+ }
27
+ if (!Number.isFinite(definition.tickRate) || definition.tickRate <= 0) {
28
+ throw new Error(`Invalid tickRate for ${definition.gameId}: ${definition.tickRate}`);
29
+ }
30
+ }
31
+ //# sourceMappingURL=definition.js.map
@@ -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ADDED
@@ -0,0 +1,7 @@
1
+ import { type Application } from "express";
2
+ import type { GameServerConfig } from "./config.js";
3
+ export interface ConfigureGameServerHttpRoutesOptions {
4
+ extraHealth?: Record<string, unknown> | (() => Record<string, unknown>);
5
+ roomNames: readonly string[];
6
+ }
7
+ export declare function configureGameServerHttpRoutes(app: Application, config: GameServerConfig, options: ConfigureGameServerHttpRoutesOptions): void;
package/dist/http.js ADDED
@@ -0,0 +1,42 @@
1
+ import cors from "cors";
2
+ import express from "express";
3
+ import { monitor } from "@colyseus/monitor";
4
+ import { matchMaker } from "colyseus";
5
+ export function configureGameServerHttpRoutes(app, config, options) {
6
+ app.use(cors({ origin: config.corsOrigin }));
7
+ app.use(express.json());
8
+ app.get("/health", (_req, res) => {
9
+ res.json({
10
+ ok: true,
11
+ service: config.serviceName,
12
+ ...readExtraHealth(options.extraHealth)
13
+ });
14
+ });
15
+ app.get("/rooms", async (_req, res, next) => {
16
+ try {
17
+ const queried = await Promise.all(options.roomNames.map((name) => matchMaker.query({ name })));
18
+ const seen = new Set();
19
+ const rooms = queried.flat().filter((room) => {
20
+ if (seen.has(room.roomId))
21
+ return false;
22
+ seen.add(room.roomId);
23
+ return true;
24
+ });
25
+ res.json(rooms.map((room) => ({
26
+ clients: room.clients,
27
+ maxClients: room.maxClients,
28
+ roomId: room.roomId
29
+ })));
30
+ }
31
+ catch (error) {
32
+ next(error);
33
+ }
34
+ });
35
+ if (config.enableMonitor) {
36
+ app.use("/colyseus", monitor());
37
+ }
38
+ }
39
+ function readExtraHealth(extraHealth) {
40
+ return typeof extraHealth === "function" ? extraHealth() : extraHealth ?? {};
41
+ }
42
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAA6B,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB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,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;gBACnB,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;aACpB,CAAC,CAAC,CACJ,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,IAAI,MAAM,CAAC,aAAa,EAAE,CAAC;QACzB,GAAG,CAAC,GAAG,CAAC,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC;IAClC,CAAC;AACH,CAAC;AAED,SAAS,eAAe,CAAC,WAAgE;IACvF,OAAO,OAAO,WAAW,KAAK,UAAU,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,WAAW,IAAI,EAAE,CAAC;AAC/E,CAAC"}
@@ -0,0 +1,8 @@
1
+ export * from "./auth.js";
2
+ export * from "./client.js";
3
+ export * from "./cloud-smoke.js";
4
+ export * from "./colyseus.js";
5
+ export * from "./colyseus-adapter.js";
6
+ export * from "./config.js";
7
+ export * from "./definition.js";
8
+ export * from "./http.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export * from "./auth.js";
2
+ export * from "./client.js";
3
+ export * from "./cloud-smoke.js";
4
+ export * from "./colyseus.js";
5
+ export * from "./colyseus-adapter.js";
6
+ export * from "./config.js";
7
+ export * from "./definition.js";
8
+ export * from "./http.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AACtC,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC"}
package/package.json ADDED
@@ -0,0 +1,106 @@
1
+ {
2
+ "name": "@pieai/swimmer-game-server-kit",
3
+ "version": "0.1.0",
4
+ "description": "Shared Colyseus game server kit for PieAI Swimmer-based games.",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=24 <25"
8
+ },
9
+ "license": "SEE LICENSE IN LICENSE",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/PieAIStudio/SwimmerGameServerKit.git"
13
+ },
14
+ "homepage": "https://github.com/PieAIStudio/SwimmerGameServerKit#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/PieAIStudio/SwimmerGameServerKit/issues"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public",
20
+ "registry": "https://registry.npmjs.org/"
21
+ },
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ },
29
+ "./auth": {
30
+ "types": "./dist/auth.d.ts",
31
+ "import": "./dist/auth.js"
32
+ },
33
+ "./client": {
34
+ "types": "./dist/client.d.ts",
35
+ "import": "./dist/client.js"
36
+ },
37
+ "./cloud-smoke": {
38
+ "types": "./dist/cloud-smoke.d.ts",
39
+ "import": "./dist/cloud-smoke.js"
40
+ },
41
+ "./colyseus-adapter": {
42
+ "types": "./dist/colyseus-adapter.d.ts",
43
+ "import": "./dist/colyseus-adapter.js"
44
+ },
45
+ "./colyseus": {
46
+ "types": "./dist/colyseus.d.ts",
47
+ "import": "./dist/colyseus.js"
48
+ },
49
+ "./config": {
50
+ "types": "./dist/config.d.ts",
51
+ "import": "./dist/config.js"
52
+ },
53
+ "./definition": {
54
+ "types": "./dist/definition.d.ts",
55
+ "import": "./dist/definition.js"
56
+ },
57
+ "./http": {
58
+ "types": "./dist/http.d.ts",
59
+ "import": "./dist/http.js"
60
+ },
61
+ "./package.json": "./package.json"
62
+ },
63
+ "files": [
64
+ "dist",
65
+ "templates",
66
+ "README.md",
67
+ "LICENSE"
68
+ ],
69
+ "keywords": [
70
+ "pieai",
71
+ "swimmer",
72
+ "colyseus",
73
+ "game-server",
74
+ "typescript"
75
+ ],
76
+ "dependencies": {
77
+ "@colyseus/monitor": "^0.17.0",
78
+ "@colyseus/sdk": "^0.17.42",
79
+ "@colyseus/tools": "^0.17.5",
80
+ "@colyseus/ws-transport": "^0.17.13",
81
+ "colyseus": "^0.17.10",
82
+ "cors": "^2.8.5",
83
+ "express": "^5.1.0",
84
+ "jose": "^6.1.2",
85
+ "zod": "^4.1.13"
86
+ },
87
+ "devDependencies": {
88
+ "@pieai/doc-gov": "0.4.9",
89
+ "@pieai/pro-gov": "0.4.9",
90
+ "@types/cors": "^2.8.19",
91
+ "@types/express": "^5.0.6",
92
+ "@types/node": "^24.13.2",
93
+ "lefthook": "^2.1.9",
94
+ "typescript": "^5.9.3",
95
+ "vitest": "^3.2.6"
96
+ },
97
+ "scripts": {
98
+ "build": "tsc -p tsconfig.build.json",
99
+ "typecheck": "tsc -p tsconfig.json --noEmit",
100
+ "test": "vitest run --pool threads",
101
+ "verify": "pnpm typecheck && pnpm test && pnpm build",
102
+ "doc-gov": "doc-gov",
103
+ "pro-gov": "pro-gov",
104
+ "docs:check": "pnpm pro-gov doctor --strict-hooks && pnpm doc-gov router-check && pnpm doc-gov check && pnpm doc-gov scan --check && pnpm doc-gov links && pnpm doc-gov audit && pnpm doc-gov doctor"
105
+ }
106
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@example/game-server",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "dev": "tsx watch src/index.ts",
7
+ "start": "tsx src/index.ts",
8
+ "typecheck": "tsc -p tsconfig.json --noEmit"
9
+ },
10
+ "dependencies": {
11
+ "@colyseus/tools": "^0.17.5",
12
+ "@pieai/swimmer-game-server-kit": "0.1.0",
13
+ "colyseus": "^0.17.10"
14
+ },
15
+ "devDependencies": {
16
+ "@types/node": "^24.13.2",
17
+ "tsx": "^4.21.0",
18
+ "typescript": "^5.9.3"
19
+ }
20
+ }
@@ -0,0 +1,17 @@
1
+ import {
2
+ createSwimmerGameServerApp,
3
+ resolveGameServerConfig
4
+ } from "@pieai/swimmer-game-server-kit";
5
+ import { SampleRoom } from "./rooms/SampleRoom.js";
6
+
7
+ export const SAMPLE_ROOM_NAME = "sample_room";
8
+
9
+ export const serverConfig = resolveGameServerConfig({
10
+ envPrefix: "SAMPLE",
11
+ serviceName: "sample-game-server"
12
+ });
13
+
14
+ export default createSwimmerGameServerApp({
15
+ config: serverConfig,
16
+ rooms: [{ name: SAMPLE_ROOM_NAME, room: SampleRoom }]
17
+ });
@@ -0,0 +1,5 @@
1
+ import { listen } from "@colyseus/tools";
2
+ import app, { serverConfig } from "./app.config.js";
3
+
4
+ await listen(app, serverConfig.port);
5
+ console.log(`[${serverConfig.serviceName}] listening on port ${serverConfig.port}`);
@@ -0,0 +1,29 @@
1
+ import { Client, Room } from "colyseus";
2
+ import { authenticateRoomJoin, type RoomAuthOptions } from "@pieai/swimmer-game-server-kit/auth";
3
+
4
+ interface SampleRoomState {
5
+ joined: number;
6
+ }
7
+
8
+ export class SampleRoom extends Room<SampleRoomState> {
9
+ maxClients = 2;
10
+
11
+ onCreate() {
12
+ this.setState({ joined: 0 });
13
+ }
14
+
15
+ async onAuth(_client: Client, options?: RoomAuthOptions) {
16
+ return authenticateRoomJoin(options, {
17
+ env: process.env,
18
+ fallbackDisplayName: "Player"
19
+ });
20
+ }
21
+
22
+ onJoin() {
23
+ this.state.joined += 1;
24
+ }
25
+
26
+ onLeave() {
27
+ this.state.joined = Math.max(0, this.state.joined - 1);
28
+ }
29
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "NodeNext",
4
+ "moduleResolution": "NodeNext",
5
+ "noEmit": true,
6
+ "skipLibCheck": true,
7
+ "strict": true,
8
+ "target": "ES2022"
9
+ },
10
+ "include": ["src/**/*.ts"]
11
+ }