@margoengine/netcode 0.0.0-stage → 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 +201 -0
- package/NOTICE +4 -0
- package/README.md +1306 -3
- package/dist/client.d.ts +167 -0
- package/dist/clock.d.ts +29 -0
- package/dist/extrapolate.d.ts +42 -0
- package/dist/extrapolate.js +25 -0
- package/dist/game.d.ts +68 -0
- package/dist/generate-rust.d.ts +14 -0
- package/dist/generate-rust.js +184 -0
- package/dist/generate.d.ts +25 -0
- package/dist/generate.js +156 -0
- package/dist/hitboxes.d.ts +74 -0
- package/dist/hitboxes.js +124 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +457 -0
- package/dist/interest.d.ts +101 -0
- package/dist/interest.js +166 -0
- package/dist/interpolation-delay.d.ts +114 -0
- package/dist/interpolation-delay.js +79 -0
- package/dist/interpolation-fields.d.ts +117 -0
- package/dist/interpolation-fields.js +147 -0
- package/dist/interpolation-timeline.d.ts +100 -0
- package/dist/interpolation-timeline.js +122 -0
- package/dist/interpolation.d.ts +39 -0
- package/dist/interpolation.js +61 -0
- package/dist/lag.d.ts +62 -0
- package/dist/lobby.d.ts +77 -0
- package/dist/lobby.js +96 -0
- package/dist/loopback.d.ts +92 -0
- package/dist/media.d.ts +197 -0
- package/dist/media.js +274 -0
- package/dist/migrate.d.ts +113 -0
- package/dist/migrate.js +289 -0
- package/dist/node.d.ts +101 -0
- package/dist/node.js +166 -0
- package/dist/physics.d.ts +133 -0
- package/dist/physics.js +169 -0
- package/dist/presence.d.ts +156 -0
- package/dist/presence.js +226 -0
- package/dist/protocol-asi_qndb.js +122 -0
- package/dist/protocol.d.ts +75 -0
- package/dist/relay.d.ts +152 -0
- package/dist/relay.js +235 -0
- package/dist/rollback.d.ts +131 -0
- package/dist/rollback.js +194 -0
- package/dist/rooms.d.ts +366 -0
- package/dist/rooms.js +479 -0
- package/dist/schema-CMfqK4Gu.js +616 -0
- package/dist/schema.d.ts +263 -0
- package/dist/server-DAVzHcWW.js +203 -0
- package/dist/server.d.ts +147 -0
- package/dist/shared/bytes.d.ts +36 -0
- package/dist/signal.d.ts +156 -0
- package/dist/signal.js +261 -0
- package/dist/smoothing.d.ts +76 -0
- package/dist/smoothing.js +155 -0
- package/dist/transport-DeQodwyv.js +49 -0
- package/dist/transport.d.ts +76 -0
- package/dist/webrtc.d.ts +32 -0
- package/dist/webrtc.js +64 -0
- package/dist/websocket.d.ts +27 -0
- package/dist/websocket.js +42 -0
- package/dist/webtransport.d.ts +83 -0
- package/dist/webtransport.js +120 -0
- package/package.json +140 -6
package/dist/migrate.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { r as e } from "./schema-CMfqK4Gu.js";
|
|
2
|
+
import { r as t, t as n } from "./transport-DeQodwyv.js";
|
|
3
|
+
//#region src/migrate.ts
|
|
4
|
+
var r = 112, i = e({ types: {
|
|
5
|
+
Snapshot: {
|
|
6
|
+
sequence: "uint",
|
|
7
|
+
frame: "uint",
|
|
8
|
+
bytes: {
|
|
9
|
+
type: "bytes",
|
|
10
|
+
maxLength: 2 ** 24
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
Packet: {
|
|
14
|
+
kind: "u8",
|
|
15
|
+
epoch: "uint",
|
|
16
|
+
hash: "u32",
|
|
17
|
+
host: "uint",
|
|
18
|
+
snapshot: "Snapshot",
|
|
19
|
+
previous: {
|
|
20
|
+
type: "optional",
|
|
21
|
+
of: "Snapshot"
|
|
22
|
+
},
|
|
23
|
+
members: {
|
|
24
|
+
type: "array",
|
|
25
|
+
of: "uint",
|
|
26
|
+
maxLength: 64
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
} }), a = 1, o = 2, s = 3, c = 4, l = 5, u = 6, d = 7, f = 8, p = 9, m = 10, h = (e, t = 2 ** 32 - 1) => Number.isInteger(e) && e >= 0 && e <= t, g = (e, t) => e.sequence === t.sequence && e.frame === t.frame && e.bytes.length === t.bytes.length && e.bytes.every((e, n) => e === t.bytes[n]), _ = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]), v = class {
|
|
30
|
+
constructor(e) {
|
|
31
|
+
this.options = e, this.links = /* @__PURE__ */ new Map(), this.epochNumber = 0, this.ready = !0, this.closed = !1, this.reports = /* @__PURE__ */ new Map(), this.future = /* @__PURE__ */ new Map(), this.waiters = /* @__PURE__ */ new Set();
|
|
32
|
+
let t = [e.local, ...e.peers.keys()].sort((e, t) => e - t);
|
|
33
|
+
if (t.length > 64 || new Set(t).size !== t.length || t.some((e) => !h(e)) || [...e.peers.values()].some((e) => !e.open)) throw TypeError("Migration needs 1..64 unique unsigned ids and open full-mesh links; pass the same roster to every peer");
|
|
34
|
+
if (this.hostId = e.host ?? t[0], !t.includes(this.hostId)) throw TypeError("Migration host is outside the roster; choose an existing peer");
|
|
35
|
+
if (this.timeout = e.timeout ?? 1e4, this.maxBytes = e.maxSnapshotBytes ?? 1048576, !h(this.timeout, 2147483647) || this.timeout < 1 || !h(this.maxBytes, 2 ** 24) || this.maxBytes < 1) throw RangeError("Migration timeout/byte limit is outside range; use positive integers within the documented limits");
|
|
36
|
+
let a = e.frame ?? 0;
|
|
37
|
+
if (!h(a)) throw RangeError("Migration frame must be an unsigned integer; pass a simulation frame");
|
|
38
|
+
this.schema = e.schema, this.history = [{
|
|
39
|
+
sequence: 0,
|
|
40
|
+
frame: a,
|
|
41
|
+
bytes: this.encode(e.initial)
|
|
42
|
+
}];
|
|
43
|
+
for (let [t, a] of e.peers) {
|
|
44
|
+
let e = {
|
|
45
|
+
connection: a,
|
|
46
|
+
beforeMessage: a.onmessage,
|
|
47
|
+
beforeClose: a.onclose,
|
|
48
|
+
message: (o, s) => {
|
|
49
|
+
if (o[0] !== r) return e.beforeMessage?.(o, s);
|
|
50
|
+
try {
|
|
51
|
+
if (o.length > 2 * this.maxBytes + 1024) throw RangeError("Migration packet exceeds limit; reduce snapshot bytes");
|
|
52
|
+
this.receive(t, i.decode("Packet", o.subarray(1)));
|
|
53
|
+
} catch (e) {
|
|
54
|
+
if (!(e instanceof RangeError || e instanceof TypeError)) throw e;
|
|
55
|
+
a.close(n.protocol, "invalid migration packet");
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
close: (n, r) => {
|
|
59
|
+
try {
|
|
60
|
+
e.beforeClose?.(n, r);
|
|
61
|
+
} finally {
|
|
62
|
+
this.lost(t);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
this.links.set(t, e), a.onmessage = e.message, a.onclose = e.close;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
get host() {
|
|
70
|
+
return this.hostId;
|
|
71
|
+
}
|
|
72
|
+
get isHost() {
|
|
73
|
+
return !this.closed && this.ready && this.hostId === this.options.local;
|
|
74
|
+
}
|
|
75
|
+
get epoch() {
|
|
76
|
+
return this.epochNumber;
|
|
77
|
+
}
|
|
78
|
+
get confirmed() {
|
|
79
|
+
let e = this.current;
|
|
80
|
+
return {
|
|
81
|
+
frame: e.frame,
|
|
82
|
+
state: this.schema.decode(this.options.stateType, e.bytes)
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
get current() {
|
|
86
|
+
return this.history[this.history.length - 1];
|
|
87
|
+
}
|
|
88
|
+
members() {
|
|
89
|
+
return [this.options.local, ...[...this.links].filter(([, e]) => e.connection.open).map(([e]) => e)].sort((e, t) => e - t);
|
|
90
|
+
}
|
|
91
|
+
encode(e) {
|
|
92
|
+
let t = this.schema.encode(this.options.stateType, e);
|
|
93
|
+
if (t.length > this.maxBytes) throw RangeError("Migration checkpoint exceeds maxSnapshotBytes; reduce state or raise the limit");
|
|
94
|
+
return t;
|
|
95
|
+
}
|
|
96
|
+
packet(e, t = this.current, n = this.hostId ?? this.members()[0]) {
|
|
97
|
+
return {
|
|
98
|
+
kind: e,
|
|
99
|
+
epoch: this.epochNumber,
|
|
100
|
+
hash: this.schema.hash,
|
|
101
|
+
host: n,
|
|
102
|
+
snapshot: t,
|
|
103
|
+
previous: this.history.at(-2),
|
|
104
|
+
members: this.members()
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
send(e, t) {
|
|
108
|
+
let n = i.encode("Packet", t), a = new Uint8Array(n.length + 1);
|
|
109
|
+
a[0] = r, a.set(n, 1), this.links.get(e)?.connection.send(a, "reliable");
|
|
110
|
+
}
|
|
111
|
+
broadcast(e) {
|
|
112
|
+
for (let [t, n] of this.links) n.connection.open && this.send(t, e);
|
|
113
|
+
}
|
|
114
|
+
save(e) {
|
|
115
|
+
this.history = [...this.history.filter((t) => t.sequence < e.sequence), e].slice(-2);
|
|
116
|
+
}
|
|
117
|
+
authority() {
|
|
118
|
+
if (!this.isHost) throw t("failed", "Only a ready host may publish or transfer authority; await waitForHost and check isHost");
|
|
119
|
+
if (this.pending) throw t("failed", "A migration operation is pending; await it before starting another");
|
|
120
|
+
}
|
|
121
|
+
confirm(e, t, n = {}) {
|
|
122
|
+
if (n.signal?.throwIfAborted(), this.authority(), !h(t) || t <= this.current.frame || this.current.sequence === 2 ** 32 - 1) throw RangeError("Confirmation must advance an unsigned frame/sequence; start a new session before overflow");
|
|
123
|
+
let r = {
|
|
124
|
+
sequence: this.current.sequence + 1,
|
|
125
|
+
frame: t,
|
|
126
|
+
bytes: this.encode(e)
|
|
127
|
+
};
|
|
128
|
+
return this.operation(this.packet(a, r), a, n.signal);
|
|
129
|
+
}
|
|
130
|
+
handoff(e, t = {}) {
|
|
131
|
+
if (t.signal?.throwIfAborted(), this.authority(), e === this.options.local || !this.links.get(e)?.connection.open) throw RangeError("Handoff target must be another connected peer; choose an id from the mesh");
|
|
132
|
+
if (this.epochNumber === 2 ** 32 - 1) throw RangeError("Migration epoch exhausted; create a new session");
|
|
133
|
+
return this.epochNumber++, this.ready = !1, this.operation(this.packet(f, this.current, e), f, t.signal);
|
|
134
|
+
}
|
|
135
|
+
operation(e, n, r) {
|
|
136
|
+
return new Promise((i, a) => {
|
|
137
|
+
let o = () => {
|
|
138
|
+
clearTimeout(c), r?.removeEventListener("abort", s);
|
|
139
|
+
}, s = () => {
|
|
140
|
+
let e = r?.reason ?? t("failed", "Migration operation timed out; reconnect a fresh session");
|
|
141
|
+
this.pending = void 0, o(), a(e), this.close();
|
|
142
|
+
}, c = setTimeout(s, this.timeout);
|
|
143
|
+
r?.addEventListener("abort", s, { once: !0 }), this.pending = {
|
|
144
|
+
packet: e,
|
|
145
|
+
stage: n,
|
|
146
|
+
acks: /* @__PURE__ */ new Set([this.options.local]),
|
|
147
|
+
resolve: () => {
|
|
148
|
+
o(), i();
|
|
149
|
+
},
|
|
150
|
+
reject: (e) => {
|
|
151
|
+
o(), a(e);
|
|
152
|
+
}
|
|
153
|
+
}, this.broadcast(e), this.progress();
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
progress() {
|
|
157
|
+
let e = this.pending;
|
|
158
|
+
e && this.members().every((t) => e.acks.has(t)) && (e.stage === a ? (this.save(e.packet.snapshot), e.stage = s, e.acks = /* @__PURE__ */ new Set([this.options.local]), this.broadcast({
|
|
159
|
+
...e.packet,
|
|
160
|
+
kind: s
|
|
161
|
+
}), this.progress()) : (this.pending = void 0, e.stage === f && (this.hostId = e.packet.host, this.ready = !0, this.broadcast({
|
|
162
|
+
...e.packet,
|
|
163
|
+
kind: m
|
|
164
|
+
}), this.notify()), e.resolve()));
|
|
165
|
+
}
|
|
166
|
+
validate(e) {
|
|
167
|
+
if (e.hash !== this.schema.hash || e.kind < a || e.kind > m) throw RangeError("Migration protocol/schema mismatch; use matching peers");
|
|
168
|
+
for (let t of [e.snapshot, e.previous]) if (t) {
|
|
169
|
+
if (t.bytes.length > this.maxBytes) throw RangeError("Migration snapshot too large; respect maxSnapshotBytes");
|
|
170
|
+
this.schema.decode(this.options.stateType, t.bytes);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
receive(e, t) {
|
|
174
|
+
if (this.closed || !this.links.get(e)?.connection.open) return;
|
|
175
|
+
if (this.validate(t), t.kind === l && t.epoch > this.epochNumber && this.hostId !== void 0) {
|
|
176
|
+
this.future.set(e, t), e === this.hostId && this.beginRecovery(t.epoch);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (t.kind === f && e === this.hostId && t.epoch === this.epochNumber + 1 && t.members.includes(t.host) && _(t.members, this.members())) {
|
|
180
|
+
if (!g(this.current, t.snapshot)) throw RangeError("Handoff checkpoint differs; finish confirmation before transferring");
|
|
181
|
+
this.epochNumber = t.epoch, this.transferFrom = e, this.hostId = t.host, this.ready = !1, this.send(e, {
|
|
182
|
+
...t,
|
|
183
|
+
kind: p
|
|
184
|
+
});
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (t.kind === l && this.hostId === void 0 && t.epoch > this.epochNumber) {
|
|
188
|
+
this.future.set(e, t), this.beginRecovery(t.epoch);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (t.epoch !== this.epochNumber) return;
|
|
192
|
+
let n = this.pending;
|
|
193
|
+
if (n && g(t.snapshot, n.packet.snapshot) && (n.stage === a && t.kind === o || n.stage === s && t.kind === c || n.stage === f && t.kind === p)) n.acks.add(e), this.progress();
|
|
194
|
+
else if (t.kind === m && e === this.transferFrom && t.host === this.hostId) this.transferFrom = void 0, this.ready = !0, this.notify();
|
|
195
|
+
else if (t.kind === a && e === this.hostId && t.snapshot.sequence === this.current.sequence + 1 && t.snapshot.frame > this.current.frame) this.transferFrom !== void 0 && (this.transferFrom = void 0, this.ready = !0, this.notify()), this.prepared = t.snapshot, this.send(e, {
|
|
196
|
+
...t,
|
|
197
|
+
kind: o
|
|
198
|
+
});
|
|
199
|
+
else if (t.kind === s && e === this.hostId && this.prepared && g(this.prepared, t.snapshot)) this.save(t.snapshot), this.prepared = void 0, this.send(e, {
|
|
200
|
+
...t,
|
|
201
|
+
kind: c
|
|
202
|
+
});
|
|
203
|
+
else if (t.kind === l && this.hostId === void 0 && _(t.members, this.members())) this.reports.set(e, t), this.recover();
|
|
204
|
+
else if (t.kind === u && e === this.members()[0] && this.hostId === void 0 && _(t.members, this.members())) {
|
|
205
|
+
if (!this.history.some((e) => g(e, t.snapshot))) throw RangeError("Recovery checkpoint is not locally confirmed; reconnect a matching session");
|
|
206
|
+
this.save(t.snapshot), this.hostId = e, this.ready = !0, this.clearRecovery(), this.send(e, {
|
|
207
|
+
...t,
|
|
208
|
+
kind: d
|
|
209
|
+
}), this.notify();
|
|
210
|
+
} else t.kind === d && this.resuming && g(t.snapshot, this.current) && (this.resuming.add(e), this.completeRecovery());
|
|
211
|
+
}
|
|
212
|
+
lost(e) {
|
|
213
|
+
this.closed || (this.pending?.stage === f && this.pending.packet.host === e ? (this.pending.reject(t("failed", "Handoff target left; await the recovered host")), this.pending = void 0, this.beginRecovery()) : e === this.hostId || e === this.transferFrom || this.hostId === void 0 ? this.beginRecovery() : (this.progress(), this.completeRecovery()));
|
|
214
|
+
}
|
|
215
|
+
beginRecovery(e) {
|
|
216
|
+
if (e !== void 0) this.epochNumber = e;
|
|
217
|
+
else if (this.hostId !== void 0 || this.resuming) {
|
|
218
|
+
if (this.epochNumber === 2 ** 32 - 1) return this.close();
|
|
219
|
+
this.epochNumber++;
|
|
220
|
+
}
|
|
221
|
+
this.hostId = void 0, this.ready = !1, this.prepared = void 0, this.transferFrom = void 0, this.resuming = void 0, this.reports.clear();
|
|
222
|
+
let n = this.packet(l);
|
|
223
|
+
this.reports.set(this.options.local, n);
|
|
224
|
+
for (let [e, t] of this.future) t.epoch === this.epochNumber && _(t.members, n.members) && this.reports.set(e, t);
|
|
225
|
+
this.future.clear(), this.clearRecovery(), this.recoveryTimer = setTimeout(() => {
|
|
226
|
+
let e = t("failed", "Host recovery timed out; reconnect the full peer mesh");
|
|
227
|
+
this.close(), (this.options.onerror ?? console.error)(e);
|
|
228
|
+
}, this.timeout), this.broadcast(n), this.recover();
|
|
229
|
+
}
|
|
230
|
+
recover() {
|
|
231
|
+
let e = this.members();
|
|
232
|
+
if (this.ready || this.hostId !== void 0 || this.resuming || e[0] !== this.options.local || !e.every((e) => this.reports.has(e))) return;
|
|
233
|
+
let n = e.map((e) => this.reports.get(e)), r = Math.min(...n.map((e) => e.snapshot.sequence)), i = [n[0].snapshot, n[0].previous].find((e) => e?.sequence === r);
|
|
234
|
+
if (!i || n.some((e) => ![e.snapshot, e.previous].some((e) => e && g(e, i)))) {
|
|
235
|
+
let e = t("failed", "Survivors have no common confirmed checkpoint; reconnect a matching session");
|
|
236
|
+
this.close(), (this.options.onerror ?? console.error)(e);
|
|
237
|
+
} else this.save(i), this.resuming = /* @__PURE__ */ new Set([this.options.local]), this.broadcast(this.packet(u)), this.completeRecovery();
|
|
238
|
+
}
|
|
239
|
+
completeRecovery() {
|
|
240
|
+
this.resuming && this.members().every((e) => this.resuming?.has(e)) && (this.hostId = this.options.local, this.ready = !0, this.resuming = void 0, this.clearRecovery(), this.notify());
|
|
241
|
+
}
|
|
242
|
+
clearRecovery() {
|
|
243
|
+
this.recoveryTimer !== void 0 && clearTimeout(this.recoveryTimer), this.recoveryTimer = void 0;
|
|
244
|
+
}
|
|
245
|
+
result() {
|
|
246
|
+
return {
|
|
247
|
+
host: this.hostId,
|
|
248
|
+
epoch: this.epochNumber,
|
|
249
|
+
...this.confirmed
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
notify() {
|
|
253
|
+
if (this.ready && this.hostId !== void 0) {
|
|
254
|
+
for (let e of this.waiters) e.resolve(this.result());
|
|
255
|
+
this.waiters.clear();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
waitForHost(e = {}) {
|
|
259
|
+
return e.signal?.throwIfAborted(), this.closed ? Promise.reject(t("disposed", "Migration session is closed; create a new session")) : this.ready && this.hostId !== void 0 ? Promise.resolve(this.result()) : new Promise((n, r) => {
|
|
260
|
+
let i = () => {
|
|
261
|
+
clearTimeout(o), e.signal?.removeEventListener("abort", a), this.waiters.delete(s);
|
|
262
|
+
}, a = () => {
|
|
263
|
+
i(), r(e.signal?.reason ?? t("failed", "Waiting for host timed out; reconnect the peer mesh"));
|
|
264
|
+
}, o = setTimeout(a, this.timeout), s = {
|
|
265
|
+
resolve: (e) => {
|
|
266
|
+
i(), n(e);
|
|
267
|
+
},
|
|
268
|
+
reject: (e) => {
|
|
269
|
+
i(), r(e);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
this.waiters.add(s), e.signal?.addEventListener("abort", a, { once: !0 });
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
close() {
|
|
276
|
+
if (this.closed) return;
|
|
277
|
+
this.closed = !0, this.ready = !1, this.clearRecovery();
|
|
278
|
+
let e = t("disposed", "Migration session closed; resume on the elected peer or create a new session");
|
|
279
|
+
this.pending?.reject(e), this.pending = void 0;
|
|
280
|
+
for (let t of [...this.waiters]) t.reject(e);
|
|
281
|
+
this.waiters.clear();
|
|
282
|
+
for (let e of this.links.values()) e.connection.onmessage === e.message && (e.connection.onmessage = e.beforeMessage), e.connection.onclose === e.close && (e.connection.onclose = e.beforeClose), e.connection.close(n.normal, "peer left migration session");
|
|
283
|
+
}
|
|
284
|
+
[Symbol.dispose]() {
|
|
285
|
+
this.close();
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
//#endregion
|
|
289
|
+
export { v as HostMigration };
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type Server } from 'node:http';
|
|
2
|
+
import type { Game } from './game.js';
|
|
3
|
+
import { GameServer, type GameServerOptions } from './server.js';
|
|
4
|
+
import { type Listener } from './transport.js';
|
|
5
|
+
/** Options of {@link listenWebSocket}. */
|
|
6
|
+
export interface WebSocketServerOptions {
|
|
7
|
+
/** TCP port; 0 picks a free one (default 0). */
|
|
8
|
+
port?: number;
|
|
9
|
+
/** Interface to bind (default '127.0.0.1'; pass '0.0.0.0' to accept other machines). */
|
|
10
|
+
host?: string;
|
|
11
|
+
/** The URL path that accepts WebSocket upgrades (default any path). */
|
|
12
|
+
path?: string;
|
|
13
|
+
/**
|
|
14
|
+
* Which web pages may connect, by their `Origin` header; others get 403 (default: only pages served from this
|
|
15
|
+
* server's own host, that is an Origin of `http://` or `https://` plus the request's `Host` header). `'*'` allows any
|
|
16
|
+
* page; a list allows exactly those origins (and then a request with no Origin is refused too). Without a list, a
|
|
17
|
+
* client that sends no Origin (Node, bots, native clients; browsers always send one) connects.
|
|
18
|
+
*/
|
|
19
|
+
origins?: readonly string[] | '*';
|
|
20
|
+
/**
|
|
21
|
+
* Connections at once, still waiting for their first message included (default 1,024). The next upgrade is answered
|
|
22
|
+
* with HTTP 503 before any connection object exists.
|
|
23
|
+
*/
|
|
24
|
+
maxConnections?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Milliseconds a new connection has to send its first message; then it is closed with `CloseCode.timeout` (default
|
|
27
|
+
* 10,000). Pings do not count: a client that only connects and idles cannot hold a slot.
|
|
28
|
+
*/
|
|
29
|
+
firstMessageTimeout?: number;
|
|
30
|
+
/** Largest message accepted from a client, in bytes (default 64 KiB); a bigger one closes with 1009. */
|
|
31
|
+
maxPayload?: number;
|
|
32
|
+
/** Bytes queued in a socket above which 'unreliable' messages are dropped (default 64 KiB). */
|
|
33
|
+
dropUnreliableAbove?: number;
|
|
34
|
+
/** Bytes queued in a socket above which the client is closed as too slow (default 8 MiB). */
|
|
35
|
+
maxBuffered?: number;
|
|
36
|
+
/** An existing HTTP server to attach to instead of creating one (`port` and `host` are then ignored). */
|
|
37
|
+
server?: Server;
|
|
38
|
+
}
|
|
39
|
+
/** A listening WebSocket server. */
|
|
40
|
+
export interface WebSocketListener extends Listener {
|
|
41
|
+
/** The port it listens on. */
|
|
42
|
+
readonly port: number;
|
|
43
|
+
/** The HTTP server underneath. */
|
|
44
|
+
readonly http: Server;
|
|
45
|
+
/** Stops accepting, closes every connection with 1001 and resolves when the HTTP server has closed. */
|
|
46
|
+
close(): void;
|
|
47
|
+
/** Resolves when the HTTP server has closed. */
|
|
48
|
+
readonly closed: Promise<void>;
|
|
49
|
+
/** Same as close, for `await using`. */
|
|
50
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Starts a WebSocket server and resolves once it listens. Each accepted socket arrives through `onconnection` as a
|
|
54
|
+
* {@link Connection}; pass it to `GameServer.accept`.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* const listener = await listenWebSocket({ port: 8080, host: '0.0.0.0', origins: ['https://game.example.com'] });
|
|
59
|
+
* listener.onconnection = (connection) => server.accept(connection);
|
|
60
|
+
* ```
|
|
61
|
+
* Safe defaults, each with an option: only pages from this server's own host may connect (`origins`; `'*'` opts out),
|
|
62
|
+
* at most 1,024 connections (`maxConnections`), and a connection that sends nothing within 10 s is closed
|
|
63
|
+
* (`firstMessageTimeout`).
|
|
64
|
+
*
|
|
65
|
+
* @throws TypeError (as a rejection) for `origins` that is not `'*'` or a list of strings; RangeError (as a rejection)
|
|
66
|
+
* for a port or limit out of range; the server's error when it cannot listen.
|
|
67
|
+
*/
|
|
68
|
+
export declare function listenWebSocket(options?: WebSocketServerOptions): Promise<WebSocketListener>;
|
|
69
|
+
/** Options of {@link serve}: the WebSocket server's and the GameServer's. */
|
|
70
|
+
export interface ServeOptions<State, Input> extends WebSocketServerOptions, GameServerOptions<State, Input> {
|
|
71
|
+
/** Stops the server: ticks end, connections close, the HTTP server closes. */
|
|
72
|
+
signal?: AbortSignal;
|
|
73
|
+
}
|
|
74
|
+
/** A running game server from {@link serve}. */
|
|
75
|
+
export interface Served<State, Input> {
|
|
76
|
+
/** The game server. */
|
|
77
|
+
server: GameServer<State, Input>;
|
|
78
|
+
/** The WebSocket listener. */
|
|
79
|
+
listener: WebSocketListener;
|
|
80
|
+
/** The port it listens on. */
|
|
81
|
+
port: number;
|
|
82
|
+
/** Resolves when the server stopped (after `close` or the signal). */
|
|
83
|
+
done: Promise<void>;
|
|
84
|
+
/** Stops ticking and closes everything. */
|
|
85
|
+
close(): Promise<void>;
|
|
86
|
+
/** Same as close, for `await using`. */
|
|
87
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Runs `game` on a WebSocket server in real time: the self-hosted server in one call.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* // server.mjs: node server.mjs
|
|
95
|
+
* import { serve } from '@margoengine/netcode/node';
|
|
96
|
+
* import { game } from './game.js';
|
|
97
|
+
* const { port } = await serve(game, { port: 8080, host: '0.0.0.0' });
|
|
98
|
+
* console.log(`listening on ${port}`);
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
export declare function serve<State, Input>(game: Game<State, Input>, options?: ServeOptions<State, Input>): Promise<Served<State, Input>>;
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { n as e, t } from "./transport-DeQodwyv.js";
|
|
2
|
+
import { t as n } from "./server-DAVzHcWW.js";
|
|
3
|
+
import { isUtf8 as r } from "node:buffer";
|
|
4
|
+
import { createHash as i } from "node:crypto";
|
|
5
|
+
import { createServer as a } from "node:http";
|
|
6
|
+
//#region src/node.ts
|
|
7
|
+
var o = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", s = (e) => e >= 1e3 && e <= 1003 || e >= 1007 && e <= 1014 || e >= 3e3 && e <= 4999, c = class {
|
|
8
|
+
constructor(e, t, n, r = () => {}) {
|
|
9
|
+
this.socket = e, this.options = t, this.forget = n, this.firstMessage = r, this.onmessage = null, this.onclose = null, this.closed = !1, this.buffer = Buffer.alloc(0), this.fragments = [], this.fragmentBytes = 0, this.fragmentKind = 0, this.heard = !1, e.on("data", (e) => this.data(e)), e.on("close", () => this.finish(1006, "connection lost")), e.on("error", () => this.finish(1006, "connection error"));
|
|
10
|
+
}
|
|
11
|
+
get open() {
|
|
12
|
+
return !this.closed;
|
|
13
|
+
}
|
|
14
|
+
frame(e, t) {
|
|
15
|
+
let n = t.length, r = n < 126 ? 2 : n < 65536 ? 4 : 10, i = Buffer.allocUnsafe(r + n);
|
|
16
|
+
return i[0] = 128 | e, n < 126 ? i[1] = n : n < 65536 ? (i[1] = 126, i.writeUInt16BE(n, 2)) : (i[1] = 127, i.writeUInt32BE(Math.floor(n / 2 ** 32), 2), i.writeUInt32BE(n >>> 0, 6)), i.set(t, r), i;
|
|
17
|
+
}
|
|
18
|
+
send(e, t = "reliable") {
|
|
19
|
+
if (this.closed) return;
|
|
20
|
+
let n = this.socket.writableLength;
|
|
21
|
+
if (!(t === "unreliable" && n > this.options.dropUnreliableAbove)) {
|
|
22
|
+
if (n > this.options.maxBuffered) return this.close(1008, "client too slow");
|
|
23
|
+
this.socket.write(this.frame(2, e));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
close(n = t.normal, r = "") {
|
|
27
|
+
if (this.closed) return;
|
|
28
|
+
let i = Buffer.from(e(r)), a = Buffer.allocUnsafe(2 + i.length);
|
|
29
|
+
a.writeUInt16BE(s(n) ? n : 1e3, 0), i.copy(a, 2), this.socket.end(this.frame(8, a)), this.finish(n, r);
|
|
30
|
+
}
|
|
31
|
+
deliver(e) {
|
|
32
|
+
this.heard || (this.heard = !0, this.firstMessage()), this.onmessage?.(e, "reliable");
|
|
33
|
+
}
|
|
34
|
+
finish(e, t) {
|
|
35
|
+
this.closed || (this.closed = !0, this.forget(this), this.onclose?.(e, t));
|
|
36
|
+
}
|
|
37
|
+
data(e) {
|
|
38
|
+
for (this.buffer = this.buffer.length ? Buffer.concat([this.buffer, e]) : e; !this.closed;) {
|
|
39
|
+
let e = this.buffer;
|
|
40
|
+
if (e.length < 2) return;
|
|
41
|
+
let t = !!(e[0] & 128), n = e[0] & 15, i = !!(e[1] & 128);
|
|
42
|
+
if (e[0] & 112) return this.close(1002, "reserved bits set");
|
|
43
|
+
if (!i) return this.close(1002, "client frames must be masked");
|
|
44
|
+
let a = e[1] & 127, o = 2;
|
|
45
|
+
if (a === 126) {
|
|
46
|
+
if (e.length < 4) return;
|
|
47
|
+
a = e.readUInt16BE(2), o = 4;
|
|
48
|
+
} else if (a === 127) {
|
|
49
|
+
if (e.length < 10) return;
|
|
50
|
+
if (e.readUInt32BE(2)) return this.close(1009, "message too big");
|
|
51
|
+
a = e.readUInt32BE(6), o = 10;
|
|
52
|
+
}
|
|
53
|
+
let c = n >= 8;
|
|
54
|
+
if (c && (a > 125 || !t)) return this.close(1002, "bad control frame");
|
|
55
|
+
if (!c && (a > this.options.maxPayload || this.fragmentBytes + a > this.options.maxPayload)) return this.close(1009, "message too big");
|
|
56
|
+
if (e.length < o + 4 + a) return;
|
|
57
|
+
let l = e.subarray(o, o + 4), u = Buffer.from(e.subarray(o + 4, o + 4 + a));
|
|
58
|
+
for (let e = 0; e < a; e++) u[e] ^= l[e & 3];
|
|
59
|
+
if (this.buffer = e.subarray(o + 4 + a), n === 8) {
|
|
60
|
+
if (u.length === 1) return this.close(1002, "close frame of one byte");
|
|
61
|
+
let e = u.length ? u.readUInt16BE(0) : 1005, t = u.subarray(2);
|
|
62
|
+
return u.length && !s(e) ? this.close(1002, `close code ${e} may not be sent`) : r(t) ? this.close(e === 1005 ? 1e3 : e, t.toString("utf8")) : this.close(1007, "close reason is not UTF-8");
|
|
63
|
+
}
|
|
64
|
+
if (n === 9) this.socket.write(this.frame(10, u));
|
|
65
|
+
else if (n !== 10) {
|
|
66
|
+
if (n === 1) return this.close(1003, "binary messages only");
|
|
67
|
+
if (n === 2) {
|
|
68
|
+
if (this.fragments.length) return this.close(1002, "new message inside a fragmented one");
|
|
69
|
+
t ? this.deliver(u) : (this.fragmentKind = 2, this.fragments.push(u), this.fragmentBytes = a);
|
|
70
|
+
} else if (n === 0) {
|
|
71
|
+
if (!this.fragments.length && this.fragmentKind !== 2) return this.close(1002, "continuation without a start");
|
|
72
|
+
if (this.fragments.push(u), this.fragmentBytes += a, t) {
|
|
73
|
+
let e = Buffer.concat(this.fragments);
|
|
74
|
+
this.fragments = [], this.fragmentBytes = 0, this.fragmentKind = 0, this.deliver(e);
|
|
75
|
+
}
|
|
76
|
+
} else return this.close(1002, `unknown opcode ${n}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
function l(e, t) {
|
|
82
|
+
let n = e.headers.origin;
|
|
83
|
+
if (t === "*") return !0;
|
|
84
|
+
if (t) return t.includes(String(n ?? ""));
|
|
85
|
+
if (n === void 0) return !0;
|
|
86
|
+
let r = String(e.headers.host ?? "").toLowerCase(), i = n.toLowerCase();
|
|
87
|
+
return r !== "" && (i === `http://${r}` || i === `https://${r}`);
|
|
88
|
+
}
|
|
89
|
+
async function u(e = {}) {
|
|
90
|
+
let n = e.port ?? 0, r = e.maxPayload ?? 65536, s = {
|
|
91
|
+
maxPayload: r,
|
|
92
|
+
dropUnreliableAbove: e.dropUnreliableAbove ?? 65536,
|
|
93
|
+
maxBuffered: e.maxBuffered ?? 8388608
|
|
94
|
+
};
|
|
95
|
+
if (!Number.isInteger(n) || n < 0 || n > 65535) throw RangeError(`WebSocket port is ${n}; pass an integer from 0 to 65535`);
|
|
96
|
+
if (!Number.isInteger(r) || r < 1 || r > 2 ** 31) throw RangeError(`WebSocket maxPayload is ${r}; pass bytes from 1 to 2^31`);
|
|
97
|
+
let u = e.maxConnections ?? 1024, d = e.firstMessageTimeout ?? 1e4;
|
|
98
|
+
if (!Number.isInteger(u) || u < 1) throw RangeError(`WebSocket maxConnections is ${String(u)}; pass an integer >= 1`);
|
|
99
|
+
if (typeof d != "number" || !(d >= 1 && d <= 2 ** 31 - 1)) throw RangeError(`WebSocket firstMessageTimeout is ${String(d)}; pass milliseconds from 1 to 2147483647`);
|
|
100
|
+
let { origins: f } = e;
|
|
101
|
+
if (f !== void 0 && f !== "*" && !(Array.isArray(f) && f.every((e) => typeof e == "string"))) throw TypeError("WebSocket origins must be a list of origins such as ['https://game.example.com'], or '*'");
|
|
102
|
+
let p = e.server ?? a((e, t) => t.writeHead(426).end("Upgrade required")), m = /* @__PURE__ */ new Set(), h = !0, g = (e, t, n = "") => {
|
|
103
|
+
e.end(`HTTP/1.1 ${t}\r\n${n}Connection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
104
|
+
}, _ = (n, r, a) => {
|
|
105
|
+
let p = n.headers["sec-websocket-key"], _ = new URL(n.url ?? "/", "http://localhost").pathname;
|
|
106
|
+
if (!h) return g(r, "503 Service Unavailable");
|
|
107
|
+
if (e.path !== void 0 && _ !== e.path) return g(r, "404 Not Found");
|
|
108
|
+
if (!l(n, f)) return g(r, "403 Forbidden");
|
|
109
|
+
if (m.size >= u) return g(r, "503 Service Unavailable");
|
|
110
|
+
let v = n.headers["sec-websocket-version"];
|
|
111
|
+
if (v !== void 0 && v !== "13") return g(r, "426 Upgrade Required", "Sec-WebSocket-Version: 13\r\n");
|
|
112
|
+
if (n.method !== "GET" || String(n.headers.upgrade).toLowerCase() !== "websocket" || v !== "13" || typeof p != "string" || Buffer.from(p, "base64").length !== 16) return g(r, "400 Bad Request");
|
|
113
|
+
let y = i("sha1").update(p + o).digest("base64");
|
|
114
|
+
r.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${y}\r\n\r\n`), r.setNoDelay?.(!0);
|
|
115
|
+
let x = setTimeout(() => S.close(t.timeout, `no message within ${d} ms (firstMessageTimeout)`), d), S = new c(r, s, (e) => {
|
|
116
|
+
clearTimeout(x), m.delete(e);
|
|
117
|
+
}, () => clearTimeout(x));
|
|
118
|
+
m.add(S), b.onconnection?.(S), a.length && r.unshift(a);
|
|
119
|
+
};
|
|
120
|
+
p.on("upgrade", _), e.server || await new Promise((t, r) => {
|
|
121
|
+
p.once("error", r), p.listen(n, e.host ?? "127.0.0.1", () => {
|
|
122
|
+
p.off("error", r), t();
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
let v = () => {}, y = new Promise((e) => v = e), b = {
|
|
126
|
+
onconnection: null,
|
|
127
|
+
get port() {
|
|
128
|
+
let e = p.address();
|
|
129
|
+
return typeof e == "object" && e ? e.port : n;
|
|
130
|
+
},
|
|
131
|
+
http: p,
|
|
132
|
+
closed: y,
|
|
133
|
+
close() {
|
|
134
|
+
if (h) {
|
|
135
|
+
h = !1, p.off("upgrade", _);
|
|
136
|
+
for (let e of [...m]) e.close(1001, "server closing");
|
|
137
|
+
e.server ? v() : p.close(() => v());
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
async [Symbol.asyncDispose]() {
|
|
141
|
+
b.close(), await y;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
return b;
|
|
145
|
+
}
|
|
146
|
+
async function d(e, t = {}) {
|
|
147
|
+
let r = await u(t), i = new n(e, t), a = new AbortController(), o = t.signal;
|
|
148
|
+
r.onconnection = (e) => i.accept(e);
|
|
149
|
+
let s = async () => {
|
|
150
|
+
a.abort(), await c;
|
|
151
|
+
};
|
|
152
|
+
o?.addEventListener("abort", () => void s(), { once: !0 }), o?.aborted && a.abort();
|
|
153
|
+
let c = i.run({ signal: a.signal }).then(async () => {
|
|
154
|
+
i.close(), r.close(), await r.closed;
|
|
155
|
+
});
|
|
156
|
+
return {
|
|
157
|
+
server: i,
|
|
158
|
+
listener: r,
|
|
159
|
+
port: r.port,
|
|
160
|
+
done: c,
|
|
161
|
+
close: s,
|
|
162
|
+
[Symbol.asyncDispose]: s
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
export { u as listenWebSocket, d as serve };
|