@funforge/game-sdk 0.0.0-stage → 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,12 @@
1
- # Temporary Holding Version
1
+ # @funforge/game-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Multiplayer SDK for FunForge games. Import `@funforge/game-sdk/multiplayer` for
4
+ the WebRTC transport with room tickets and host-authoritative state.
5
+
6
+ - `MultiplayerTransport`: join via a platform-minted room ticket, send inputs,
7
+ receive host state, diagnostics for RTT and the selected ICE path.
8
+ - Games run unchanged in the workbench (the platform bridges the transport via
9
+ MessagePort) and on standalone static pages (the SDK connects directly).
10
+
11
+ See the repository plan `docs/superpowers/plans/2026-11-29-funforge-multiplayer.md`
12
+ for the protocol and phases. Pre-release; the API may change before 1.0.
@@ -0,0 +1 @@
1
+ export * from './multiplayer/index.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './multiplayer/index.js';
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Core multiplayer transport for the FunForge game SDK: room signaling over
3
+ * WebSocket, WebRTC data channels for game traffic, host-authoritative state.
4
+ * The workbench bridge runs this in the trusted parent context; standalone
5
+ * game pages run it directly (Phase 108).
6
+ */
7
+ export type MultiplayerRole = 'host' | 'guest';
8
+ export type MultiplayerEvents = {
9
+ onRole?: (role: MultiplayerRole) => void;
10
+ onReady?: () => void;
11
+ onPeerLeft?: (leftRole?: 'host' | 'guest') => void;
12
+ /** Our own connection is gone after exhausting reconnect attempts. */
13
+ onDisconnected?: () => void;
14
+ onInput?: (input: Record<string, unknown>) => void;
15
+ onState?: (state: Record<string, unknown>) => void;
16
+ /** The host seat migrated to this member with the recovered snapshot. */
17
+ onMigrated?: (info: {
18
+ epoch: number;
19
+ snapshot?: unknown;
20
+ }) => void;
21
+ onError?: (message: string) => void;
22
+ };
23
+ export type MultiplayerJoinOptions = {
24
+ /** Absolute or same-origin path of the signaling endpoint. */
25
+ signalUrl: string;
26
+ /** Short-lived room ticket minted by the platform; kept in memory only. */
27
+ ticket: string;
28
+ events: MultiplayerEvents;
29
+ iceServers?: RTCIceServer[];
30
+ };
31
+ /** Host-authoritative transport for one room seat. */
32
+ export declare class MultiplayerTransport {
33
+ /** Handlers are mutable so hosts of the transport can attach them after construction. */
34
+ readonly events: MultiplayerEvents;
35
+ private socket;
36
+ private pc;
37
+ private readonly channels;
38
+ private negotiation;
39
+ private queuedCandidates;
40
+ private role;
41
+ private inputSeq;
42
+ /** Dedup streams: own inputs use the local counter, relayed ones use the game's player sequence. */
43
+ private memberId;
44
+ private epoch;
45
+ private seenInputs;
46
+ private closedByUs;
47
+ private reconnectsLeft;
48
+ constructor(options: MultiplayerJoinOptions);
49
+ private options;
50
+ private dial;
51
+ /** Leaves the room and stops reconnect attempts. */
52
+ leave(): void;
53
+ get currentRole(): MultiplayerRole | undefined;
54
+ /** Marks a relayed input as seen; returns false for replays and stale duplicates. */
55
+ private claimInput;
56
+ private handleSignal;
57
+ private attach;
58
+ /**
59
+ * Sends one discrete input. Per the protocol the game owns the player
60
+ * sequence: resending the same input is deduplicated by the host. The host's
61
+ * own inputs echo back through onInput with the local stream's sequence.
62
+ */
63
+ sendInput(input: Record<string, unknown>): boolean;
64
+ /** Publishes authoritative state stamped with the current epoch; guests cannot publish. */
65
+ publishState(state: Record<string, unknown>): boolean;
66
+ /** Host checkpoint for host-migration recovery; sent over signaling, size-capped. */
67
+ syncSnapshot(state: Record<string, unknown>): boolean;
68
+ get currentEpoch(): number;
69
+ /** Reports the current round-trip time in milliseconds when available. */
70
+ rttMs(): Promise<number | undefined>;
71
+ /** Reports the selected candidate type for diagnostics (host | relay | …). */
72
+ selectedCandidateType(): Promise<string | undefined>;
73
+ }
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Core multiplayer transport for the FunForge game SDK: room signaling over
3
+ * WebSocket, WebRTC data channels for game traffic, host-authoritative state.
4
+ * The workbench bridge runs this in the trusted parent context; standalone
5
+ * game pages run it directly (Phase 108).
6
+ */
7
+ const INPUT_CHANNEL = 'input';
8
+ const CONTROL_CHANNEL = 'control';
9
+ /** Host-authoritative transport for one room seat. */
10
+ export class MultiplayerTransport {
11
+ constructor(options) {
12
+ this.channels = new Map();
13
+ this.negotiation = Promise.resolve();
14
+ this.queuedCandidates = [];
15
+ this.inputSeq = 0;
16
+ this.epoch = 0;
17
+ this.seenInputs = new Set();
18
+ this.closedByUs = false;
19
+ this.reconnectsLeft = 10;
20
+ this.events = options.events;
21
+ // Relative endpoints resolve against the current origin, then switch to ws(s)://.
22
+ this.options = options;
23
+ this.dial();
24
+ }
25
+ dial() {
26
+ const options = this.options;
27
+ // Relative endpoints resolve against the current origin, then switch to ws(s)://.
28
+ const resolved = new URL(options.signalUrl, window.location.origin);
29
+ this.socket = new WebSocket(resolved.toString().replace(/^http/, 'ws'));
30
+ this.socket.onopen = () => {
31
+ this.socket.send(JSON.stringify({ type: 'auth', candidate: options.ticket }));
32
+ };
33
+ this.socket.onmessage = ({ data }) => {
34
+ try {
35
+ this.handleSignal(JSON.parse(String(data)), options);
36
+ }
37
+ catch (error) {
38
+ this.events.onError?.(error instanceof Error ? error.message : 'Signaling failed');
39
+ }
40
+ };
41
+ this.socket.onclose = () => {
42
+ if (this.closedByUs)
43
+ return;
44
+ // The seat is grace-held server-side: retry the same ticket to restore it.
45
+ // (A full room keeps rejecting until a seat frees — the caller may re-mint.)
46
+ if (this.reconnectsLeft > 0) {
47
+ this.reconnectsLeft -= 1;
48
+ setTimeout(() => this.dial(), 2000);
49
+ return;
50
+ }
51
+ this.events.onDisconnected?.();
52
+ };
53
+ this.pc = new RTCPeerConnection({ iceServers: options.iceServers ?? [] });
54
+ this.pc.onicecandidate = ({ candidate }) => {
55
+ if (candidate)
56
+ this.socket.send(JSON.stringify({ type: 'ice', candidate }));
57
+ };
58
+ this.pc.ondatachannel = ({ channel }) => this.attach(channel);
59
+ }
60
+ /** Leaves the room and stops reconnect attempts. */
61
+ leave() {
62
+ this.closedByUs = true;
63
+ for (const channel of this.channels.values())
64
+ channel.close();
65
+ this.channels.clear();
66
+ this.pc.close();
67
+ this.socket.close();
68
+ }
69
+ get currentRole() {
70
+ return this.role;
71
+ }
72
+ /** Marks a relayed input as seen; returns false for replays and stale duplicates. */
73
+ claimInput(message) {
74
+ const key = `${String(message.from ?? 'remote')}:${String(message.seq)}`;
75
+ if (this.seenInputs.has(key))
76
+ return false;
77
+ this.seenInputs.add(key);
78
+ return true;
79
+ }
80
+ handleSignal(message, options) {
81
+ this.negotiation = this.negotiation.then(async () => {
82
+ if (message.type === 'role') {
83
+ this.role = message.host === true ? 'host' : 'guest';
84
+ this.memberId = typeof message.memberId === 'string' ? message.memberId : undefined;
85
+ if (typeof message.epoch === 'number')
86
+ this.epoch = Math.max(this.epoch, message.epoch);
87
+ this.events.onRole?.(this.role);
88
+ }
89
+ if (message.type === 'ready')
90
+ this.events.onReady?.();
91
+ if (message.type === 'peer-left') {
92
+ const leftRole = typeof message.role === 'string' && message.role !== '' ? message.role : undefined;
93
+ this.events.onPeerLeft?.(leftRole);
94
+ }
95
+ if (message.type === 'host-migrated') {
96
+ // The departed host's seat is gone: this member now owns the authority at the new epoch.
97
+ this.role = 'host';
98
+ this.epoch = typeof message.epoch === 'number' ? message.epoch : this.epoch + 1;
99
+ this.memberId = typeof message.memberId === 'string' ? message.memberId : this.memberId;
100
+ const snapshot = message.snapshot && typeof message.snapshot === 'object' ? message.snapshot : undefined;
101
+ this.events.onRole?.('host');
102
+ if (snapshot)
103
+ this.events.onState?.({ ...snapshot, epoch: this.epoch });
104
+ this.events.onMigrated?.({ epoch: this.epoch, snapshot });
105
+ }
106
+ if (message.type === 'state-sync' && typeof message.snapshot === 'string') {
107
+ try {
108
+ const snapshot = JSON.parse(message.snapshot);
109
+ this.events.onState?.({ ...snapshot, epoch: this.epoch });
110
+ }
111
+ catch { /* ignore malformed checkpoints */ }
112
+ }
113
+ if (message.type === 'offer-needed') {
114
+ this.attach(this.pc.createDataChannel(CONTROL_CHANNEL));
115
+ this.attach(this.pc.createDataChannel(INPUT_CHANNEL, { ordered: false, maxRetransmits: 0 }));
116
+ await this.pc.setLocalDescription(await this.pc.createOffer());
117
+ this.socket.send(JSON.stringify({ type: 'description', description: this.pc.localDescription }));
118
+ }
119
+ if (message.type === 'ice' && typeof message.candidate === 'object' && message.candidate !== null) {
120
+ const candidate = message.candidate;
121
+ if (this.pc.remoteDescription)
122
+ await this.pc.addIceCandidate(candidate);
123
+ else
124
+ this.queuedCandidates.push(candidate);
125
+ }
126
+ if (message.type === 'description' && typeof message.description === 'object' && message.description !== null) {
127
+ await this.pc.setRemoteDescription(message.description);
128
+ for (const candidate of this.queuedCandidates.splice(0))
129
+ await this.pc.addIceCandidate(candidate);
130
+ if (message.description.type === 'offer') {
131
+ await this.pc.setLocalDescription(await this.pc.createAnswer());
132
+ this.socket.send(JSON.stringify({ type: 'description', description: this.pc.localDescription }));
133
+ }
134
+ }
135
+ }).catch((error) => {
136
+ this.events.onError?.(error instanceof Error ? error.message : 'Negotiation failed');
137
+ });
138
+ }
139
+ attach(channel) {
140
+ this.channels.set(channel.label, channel);
141
+ channel.onopen = () => {
142
+ if (this.channels.get(CONTROL_CHANNEL)?.readyState === 'open' && this.channels.get(INPUT_CHANNEL)?.readyState === 'open') {
143
+ this.events.onReady?.();
144
+ }
145
+ };
146
+ channel.onmessage = ({ data }) => {
147
+ let message;
148
+ try {
149
+ message = JSON.parse(String(data));
150
+ }
151
+ catch {
152
+ return;
153
+ }
154
+ if (message.type === 'state') {
155
+ // Guests only adopt host-published state at the current or newer epoch;
156
+ // a returning old host cannot roll the room back.
157
+ if (this.role === 'host')
158
+ return;
159
+ const epoch = typeof message.epoch === 'number' ? message.epoch : 0;
160
+ if (epoch < this.epoch)
161
+ return;
162
+ this.epoch = epoch;
163
+ this.events.onState?.(message);
164
+ return;
165
+ }
166
+ if (message.type === 'input' && typeof message.seq === 'number') {
167
+ // The host executes relayed inputs idempotently: replays and stale duplicates
168
+ // are dropped per sender before the game ever sees them.
169
+ if (this.role === 'host' && !this.claimInput(message))
170
+ return;
171
+ this.events.onInput?.(message);
172
+ }
173
+ };
174
+ }
175
+ /**
176
+ * Sends one discrete input. Per the protocol the game owns the player
177
+ * sequence: resending the same input is deduplicated by the host. The host's
178
+ * own inputs echo back through onInput with the local stream's sequence.
179
+ */
180
+ sendInput(input) {
181
+ const channel = this.channels.get(INPUT_CHANNEL);
182
+ if (!channel || channel.readyState !== 'open')
183
+ return false;
184
+ const message = { type: 'input', seq: ++this.inputSeq, ...input };
185
+ if (typeof input.seq === 'number')
186
+ message.seq = input.seq;
187
+ message.from = this.memberId;
188
+ message.epoch = this.epoch;
189
+ channel.send(JSON.stringify(message));
190
+ // The authoritative side applies its own inputs through the same deduplicated path.
191
+ if (this.role === 'host' && this.claimInput(message))
192
+ this.events.onInput?.(message);
193
+ return true;
194
+ }
195
+ /** Publishes authoritative state stamped with the current epoch; guests cannot publish. */
196
+ publishState(state) {
197
+ const channel = this.channels.get(CONTROL_CHANNEL);
198
+ if (this.role !== 'host' || !channel || channel.readyState !== 'open')
199
+ return false;
200
+ channel.send(JSON.stringify({ type: 'state', epoch: this.epoch, ...state }));
201
+ return true;
202
+ }
203
+ /** Host checkpoint for host-migration recovery; sent over signaling, size-capped. */
204
+ syncSnapshot(state) {
205
+ if (this.role !== 'host' || this.socket.readyState !== WebSocket.OPEN)
206
+ return false;
207
+ this.socket.send(JSON.stringify({ type: 'state-sync', snapshot: JSON.stringify({ ...state, epoch: this.epoch }) }));
208
+ return true;
209
+ }
210
+ get currentEpoch() {
211
+ return this.epoch;
212
+ }
213
+ /** Reports the current round-trip time in milliseconds when available. */
214
+ async rttMs() {
215
+ const report = await this.pc.getStats();
216
+ const stats = report;
217
+ for (const entry of stats.values()) {
218
+ if (entry.type === 'candidate-pair' && typeof entry.currentRoundTripTime === 'number') {
219
+ return entry.currentRoundTripTime * 1000;
220
+ }
221
+ }
222
+ return undefined;
223
+ }
224
+ /** Reports the selected candidate type for diagnostics (host | relay | …). */
225
+ async selectedCandidateType() {
226
+ const report = await this.pc.getStats();
227
+ // RTCStatsReport indexing is not declared in every DOM lib revision.
228
+ const stats = report;
229
+ const transport = [...stats.values()].find((entry) => entry.type === 'transport' && typeof entry.selectedCandidatePairId === 'string');
230
+ const pair = transport ? stats.get(transport.selectedCandidatePairId) : undefined;
231
+ const localId = pair ? pair.localCandidateId : undefined;
232
+ const local = typeof localId === 'string' ? stats.get(localId) : undefined;
233
+ return local && typeof local.candidateType === 'string' ? local.candidateType : undefined;
234
+ }
235
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@funforge/game-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "FunForge multiplayer SDK for browser games: room tickets, WebRTC transport, host-authoritative state.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./multiplayer": {
15
+ "types": "./dist/multiplayer/index.d.ts",
16
+ "import": "./dist/multiplayer/index.js"
17
+ }
18
+ },
19
+ "publishConfig": {
20
+ "main": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ },
27
+ "./multiplayer": {
28
+ "types": "./dist/multiplayer/index.d.ts",
29
+ "import": "./dist/multiplayer/index.js"
30
+ }
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "README.md"
36
+ ],
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.json",
39
+ "prepack": "npm run build"
40
+ },
41
+ "sideEffects": false,
42
+ "dependencies": {
43
+ "@funforge/game-sdk": "file:../../../../../../tmp/funforge-game-sdk-0.1.0-alpha.1.tgz"
44
+ }
45
+ }