@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.
Files changed (66) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1306 -3
  4. package/dist/client.d.ts +167 -0
  5. package/dist/clock.d.ts +29 -0
  6. package/dist/extrapolate.d.ts +42 -0
  7. package/dist/extrapolate.js +25 -0
  8. package/dist/game.d.ts +68 -0
  9. package/dist/generate-rust.d.ts +14 -0
  10. package/dist/generate-rust.js +184 -0
  11. package/dist/generate.d.ts +25 -0
  12. package/dist/generate.js +156 -0
  13. package/dist/hitboxes.d.ts +74 -0
  14. package/dist/hitboxes.js +124 -0
  15. package/dist/index.d.ts +9 -0
  16. package/dist/index.js +457 -0
  17. package/dist/interest.d.ts +101 -0
  18. package/dist/interest.js +166 -0
  19. package/dist/interpolation-delay.d.ts +114 -0
  20. package/dist/interpolation-delay.js +79 -0
  21. package/dist/interpolation-fields.d.ts +117 -0
  22. package/dist/interpolation-fields.js +147 -0
  23. package/dist/interpolation-timeline.d.ts +100 -0
  24. package/dist/interpolation-timeline.js +122 -0
  25. package/dist/interpolation.d.ts +39 -0
  26. package/dist/interpolation.js +61 -0
  27. package/dist/lag.d.ts +62 -0
  28. package/dist/lobby.d.ts +77 -0
  29. package/dist/lobby.js +96 -0
  30. package/dist/loopback.d.ts +92 -0
  31. package/dist/media.d.ts +197 -0
  32. package/dist/media.js +274 -0
  33. package/dist/migrate.d.ts +113 -0
  34. package/dist/migrate.js +289 -0
  35. package/dist/node.d.ts +101 -0
  36. package/dist/node.js +166 -0
  37. package/dist/physics.d.ts +133 -0
  38. package/dist/physics.js +169 -0
  39. package/dist/presence.d.ts +156 -0
  40. package/dist/presence.js +226 -0
  41. package/dist/protocol-asi_qndb.js +122 -0
  42. package/dist/protocol.d.ts +75 -0
  43. package/dist/relay.d.ts +152 -0
  44. package/dist/relay.js +235 -0
  45. package/dist/rollback.d.ts +131 -0
  46. package/dist/rollback.js +194 -0
  47. package/dist/rooms.d.ts +366 -0
  48. package/dist/rooms.js +479 -0
  49. package/dist/schema-CMfqK4Gu.js +616 -0
  50. package/dist/schema.d.ts +263 -0
  51. package/dist/server-DAVzHcWW.js +203 -0
  52. package/dist/server.d.ts +147 -0
  53. package/dist/shared/bytes.d.ts +36 -0
  54. package/dist/signal.d.ts +156 -0
  55. package/dist/signal.js +261 -0
  56. package/dist/smoothing.d.ts +76 -0
  57. package/dist/smoothing.js +155 -0
  58. package/dist/transport-DeQodwyv.js +49 -0
  59. package/dist/transport.d.ts +76 -0
  60. package/dist/webrtc.d.ts +32 -0
  61. package/dist/webrtc.js +64 -0
  62. package/dist/websocket.d.ts +27 -0
  63. package/dist/websocket.js +42 -0
  64. package/dist/webtransport.d.ts +83 -0
  65. package/dist/webtransport.js +120 -0
  66. package/package.json +140 -6
@@ -0,0 +1,167 @@
1
+ import type { Game } from './game.js';
2
+ import { type Connection } from './transport.js';
3
+ /** The part of `AdaptiveDelay` the client uses: fed each snapshot's server time and arrival in seconds. */
4
+ export interface ViewClock {
5
+ /** Records one snapshot. */
6
+ observe(sent: number, received: number): boolean;
7
+ /** The server time to show at local time `now`, NaN before the first snapshot. */
8
+ renderTime(now: number): number;
9
+ /** Forgets the link. */
10
+ reset(): void;
11
+ }
12
+ /** Options of {@link GameClient.join}. */
13
+ export interface GameClientOptions<Input> {
14
+ /** This player's input for tick `tick`, called once per predicted tick. */
15
+ input(tick: number): Input;
16
+ /** The clock in milliseconds (default `performance.now`); a test passes the loopback network's time. */
17
+ now?: () => number;
18
+ /** Extra ticks of input lead over the measured delay, to absorb jitter (default 1). */
19
+ inputBuffer?: number;
20
+ /**
21
+ * Ticks the interpolated view stays behind the newest snapshot (default 2 snapshot intervals), or an `AdaptiveDelay`
22
+ * from `@margoengine/netcode/interpolation-delay` to pick the delay from what the link does. Passing one is what loads it.
23
+ */
24
+ interpolationDelay?: number | ViewClock;
25
+ /** How many of the newest unconfirmed inputs each input message repeats, 1 to 32 (default 8). */
26
+ redundancy?: number;
27
+ /** Ticks of inputs, predictions and snapshots kept (default 128). */
28
+ history?: number;
29
+ /** Milliseconds between clock pings (default 500). */
30
+ pingInterval?: number;
31
+ /** Called with each game message the server sends. */
32
+ onmessage?(type: string, value: unknown): void;
33
+ /** Called once when the connection closes. */
34
+ onclose?(code: number, reason: string): void;
35
+ /** Aborts {@link GameClient.join} (it rejects with the signal's reason and closes the connection). */
36
+ signal?: AbortSignal;
37
+ }
38
+ /** Counts and measures since the client joined. */
39
+ export interface GameClientStats {
40
+ /** Snapshots applied. */
41
+ snapshots: number;
42
+ /** Snapshots that matched the prediction for their tick. */
43
+ confirmed: number;
44
+ /** Snapshots that did not: the client went back to the server's state and replayed its inputs. */
45
+ mispredictions: number;
46
+ /** Ticks replayed after mispredictions. */
47
+ replayed: number;
48
+ /** Snapshots ignored: older than one already applied, or against a baseline no longer held. */
49
+ ignored: number;
50
+ /** Round trip in milliseconds (smallest of the recent pings). */
51
+ rtt: number;
52
+ /** Ticks the server ran without this client's input (from the server). */
53
+ missed: number;
54
+ }
55
+ /**
56
+ * A client of a {@link GameServer}. `GameClient.join` resolves once the server welcomed it, the clock is synced and
57
+ * the first snapshot arrived; then call {@link GameClient.update} every frame and draw `predicted` (your player) and
58
+ * `interpolated()` (everyone else).
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * const client = await GameClient.join(game, connection, { input: () => ({ x: keys.right - keys.left, jump: keys.space }) });
63
+ * engine.onFrame(() => {
64
+ * client.update();
65
+ * drawMe(client.predicted.boxes.get(client.player));
66
+ * for (const [id, box] of client.interpolated().boxes) if (id !== client.player) drawOther(box);
67
+ * });
68
+ * ```
69
+ */
70
+ export declare class GameClient<State, Input> {
71
+ readonly game: Game<State, Input>;
72
+ readonly connection: Connection;
73
+ private readonly options;
74
+ /** Counts and measures since joining. */
75
+ readonly stats: GameClientStats;
76
+ /** This client's player id (0 until welcomed). */
77
+ player: number;
78
+ /**
79
+ * Called when a snapshot changes the prediction, with the predicted state just before and just after, at the same
80
+ * tick. `CorrectionSmoother` from `@margoengine/netcode/smoothing` uses it; both states are for reading only.
81
+ */
82
+ oncorrection: ((before: State, after: State) => void) | null;
83
+ private readonly clock;
84
+ private readonly now;
85
+ private readonly keep;
86
+ private readonly redundancy;
87
+ private readonly buffer;
88
+ private readonly pingEvery;
89
+ private delay;
90
+ private snapshotEvery;
91
+ private predictedState;
92
+ private predictedTick;
93
+ private clockTick;
94
+ private lastUpdate;
95
+ private lastPing;
96
+ private renderTick;
97
+ private lastRender;
98
+ private extra;
99
+ private extraSince;
100
+ private serverMissed;
101
+ private inputAck;
102
+ private newest;
103
+ private closed;
104
+ private readonly inputs;
105
+ private readonly predictions;
106
+ private readonly snapshots;
107
+ private readonly viewClock;
108
+ private readonly pings;
109
+ private ready;
110
+ private constructor();
111
+ /**
112
+ * Joins the server on `connection`: sends hello, then resolves once the server welcomed this client, the clock is
113
+ * synced and the first snapshot arrived.
114
+ * @throws MargoError `failed` (as a rejection) when the connection closes first, with the server's reason; the
115
+ * signal's reason when `options.signal` aborts.
116
+ */
117
+ static join<State, Input>(game: Game<State, Input>, connection: Connection, options: GameClientOptions<Input>): Promise<GameClient<State, Input>>;
118
+ /** The predicted tick: the newest tick this client simulated. */
119
+ get tick(): number;
120
+ /** The predicted state at {@link GameClient.tick}: draw your own player from this. Replaced as ticks run. */
121
+ get predicted(): State;
122
+ /** The newest snapshot's tick. */
123
+ get serverTick(): number;
124
+ /** The newest snapshot: the server's state at {@link GameClient.serverTick}. */
125
+ get authoritative(): State;
126
+ /** The snapshot before the newest, with its tick; undefined with fewer than two. For reading only. */
127
+ get previousSnapshot(): {
128
+ tick: number;
129
+ state: State;
130
+ } | undefined;
131
+ /** Whether the connection is open. */
132
+ get open(): boolean;
133
+ /**
134
+ * The fractional server tick that the last {@link GameClient.interpolated} call showed (NaN before the first): send
135
+ * it with a shot so the server can check the shot against that moment (`LagCompensation`).
136
+ */
137
+ get viewTick(): number;
138
+ private ping;
139
+ private receive;
140
+ private snapshot;
141
+ private reconcile;
142
+ private simulate;
143
+ /** The tick the client should be predicting now: the server's tick plus the one-way delay plus a jitter margin. */
144
+ private target;
145
+ /**
146
+ * Advances the client to the clock's time: runs every predicted tick that is due (sampling `input` for each),
147
+ * sends the newest inputs and pings. Call it every frame.
148
+ * @throws MargoError `state` before `join` resolved.
149
+ */
150
+ update(): void;
151
+ private sendInputs;
152
+ /**
153
+ * The state the server had `interpolationDelay` ticks before the newest snapshot should have arrived, blended
154
+ * between the two snapshots around that time: draw other players and objects from this. Holds the newest snapshot
155
+ * when the next is late; `Extrapolator` from `@margoengine/netcode/extrapolate` moves on instead.
156
+ */
157
+ interpolated(): State;
158
+ /**
159
+ * Sends game message `value` of schema struct `type` to the server, reliably.
160
+ * @throws TypeError or RangeError when `value` does not fit `type`.
161
+ */
162
+ send(type: string, value: unknown): void;
163
+ /** Leaves the game and closes the connection. */
164
+ close(): void;
165
+ /** Same as {@link GameClient.close}, for `using`. */
166
+ [Symbol.dispose](): void;
167
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Estimates the server's tick from ping and pong times. Add each pong with {@link ClockSync.add}; read
3
+ * {@link ClockSync.serverTick} for the server's fractional tick at any local time.
4
+ */
5
+ export declare class ClockSync {
6
+ readonly tickMs: number;
7
+ readonly window: number;
8
+ private readonly samples;
9
+ /**
10
+ * @param tickMs Milliseconds per server tick.
11
+ * @param window How many recent samples to keep (default 8).
12
+ * @throws RangeError for a non-positive `tickMs` or a window under 1.
13
+ */
14
+ constructor(tickMs: number, window?: number);
15
+ /** Whether at least one sample arrived. */
16
+ get synced(): boolean;
17
+ /**
18
+ * Adds a pong: the local time its ping left, the local time it arrived, the server's last tick and how far (0 to
19
+ * 1) the server was into the next one when it answered. Samples with a negative round trip are ignored.
20
+ */
21
+ add(sentAt: number, receivedAt: number, tick: number, fraction: number): void;
22
+ private best;
23
+ /** The smallest round trip in the window, in milliseconds (0 before any sample). */
24
+ get rtt(): number;
25
+ /** Half the spread of round trips in the window, in milliseconds: how much one-way delay varies. */
26
+ get jitter(): number;
27
+ /** The server's fractional tick at local time `now` (NaN before any sample). */
28
+ serverTick(now: number): number;
29
+ }
@@ -0,0 +1,42 @@
1
+ import type { GameClient } from './client.js';
2
+ /** Options of {@link Extrapolator}. */
3
+ export interface ExtrapolatorOptions {
4
+ /** Ticks past the newest snapshot to keep moving, then it holds there (default 6). */
5
+ maxTicks?: number;
6
+ /** Milliseconds to blend from what was drawn to the truth once a snapshot arrives (default 100; 0 jumps). */
7
+ blend?: number;
8
+ /** The clock in milliseconds (default `performance.now`). */
9
+ now?: () => number;
10
+ }
11
+ /**
12
+ * Draws `client.interpolated()`, carried on past the newest snapshot when the next one is late. Every field the schema
13
+ * interpolates moves on in a line (`'angle'` the short way) at the speed of the last two snapshots; the others keep
14
+ * their newest value.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const view = new Extrapolator(client, { maxTicks: 6 });
19
+ * engine.onFrame(() => {
20
+ * client.update();
21
+ * for (const [id, box] of view.state().boxes) if (id !== client.player) drawOther(box);
22
+ * });
23
+ * ```
24
+ */
25
+ export declare class Extrapolator<State, Input = unknown> {
26
+ private readonly client;
27
+ private readonly maxTicks;
28
+ private readonly blend;
29
+ private readonly now;
30
+ private shown;
31
+ private from;
32
+ private since;
33
+ /** The newest snapshot's tick while running past it. */
34
+ private base;
35
+ private behind;
36
+ /** @throws RangeError for an option out of range; TypeError when `client` is not a GameClient. */
37
+ constructor(client: GameClient<State, Input>, options?: ExtrapolatorOptions);
38
+ /** Ticks the newest {@link Extrapolator.state} was past the newest snapshot, 0 when the snapshots kept up. */
39
+ get late(): number;
40
+ /** What to draw now, in place of `client.interpolated()`. Call it once per frame. Do not write to the result. */
41
+ state(): State;
42
+ }
@@ -0,0 +1,25 @@
1
+ //#region src/extrapolate.ts
2
+ var e = class {
3
+ constructor(e, t = {}) {
4
+ if (this.client = e, this.since = 0, this.base = NaN, this.behind = 0, !e?.game) throw TypeError("Extrapolator needs a GameClient; pass what GameClient.join gave you");
5
+ if (this.maxTicks = t.maxTicks ?? 6, this.blend = t.blend ?? 100, this.now = t.now ?? (() => performance.now()), !(this.maxTicks >= 0)) throw RangeError(`Extrapolator maxTicks is ${this.maxTicks}; pass 0 or more`);
6
+ if (!(this.blend >= 0)) throw RangeError(`Extrapolator blend is ${this.blend}; pass ms of 0 or more`);
7
+ }
8
+ get late() {
9
+ return this.behind;
10
+ }
11
+ state() {
12
+ let e = this.client, { schema: t, stateType: n } = e.game, r = this.now(), i = e.interpolated(), a = e.serverTick, o = e.viewTick - a, s = e.previousSnapshot, c = o > 0 && s !== void 0, l = i;
13
+ if (c) {
14
+ let r = 1 + Math.min(o, this.maxTicks) / (a - s.tick);
15
+ l = t.interpolate(n, s.state, e.authoritative, r);
16
+ }
17
+ if (!Number.isNaN(this.base) && !(c && this.base === a) && this.blend > 0 && (this.from = this.shown, this.since = r), this.base = c ? a : NaN, this.behind = c ? o : 0, this.from !== void 0) {
18
+ let e = (r - this.since) / this.blend;
19
+ e >= 1 ? this.from = void 0 : l = t.interpolate(n, this.from, l, Math.max(0, e));
20
+ }
21
+ return this.shown = l, l;
22
+ }
23
+ };
24
+ //#endregion
25
+ export { e as Extrapolator };
package/dist/game.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { Infer, SchemaShape, TypeName, UntypedSchema } from './schema.js';
2
+ /** What `defineGame` takes. */
3
+ export interface GameDefinition<S extends SchemaShape, SN extends TypeName<S>, IN extends TypeName<S>> {
4
+ /** The compiled schema both ends share. */
5
+ schema: {
6
+ readonly definition: S;
7
+ readonly names: readonly string[];
8
+ };
9
+ /** The struct that holds the whole simulated state. */
10
+ state: SN;
11
+ /** The struct of one player's input for one tick. */
12
+ input: IN;
13
+ /** Fixed simulation ticks per second, an integer from 1 to 240 (default 30). */
14
+ tickRate?: number;
15
+ /** The state at tick 0. Called once by the server. */
16
+ initial(): Infer<S, SN>;
17
+ /**
18
+ * Advances `state` in place by one tick of `dt` seconds (`1 / tickRate`). `inputs` holds one input per player; a
19
+ * player with no input this tick is absent (treat it as idle). Must be deterministic: the same state and inputs
20
+ * give the same result on every machine, so use only `+ - * /`, `Math.sqrt`, `Math.round`, `Math.floor`, `Math.abs`,
21
+ * `Math.min` and `Math.max` on numbers, and iterate maps (always sorted by id) rather than objects of your own.
22
+ */
23
+ step(state: Infer<S, SN>, inputs: ReadonlyMap<number, Infer<S, IN>>, tick: number, dt: number): void;
24
+ /** Adds player `player` to `state` (server only, at the start of a tick). */
25
+ join?(state: Infer<S, SN>, player: number): void;
26
+ /** Removes player `player` from `state` (server only, at the start of a tick). */
27
+ leave?(state: Infer<S, SN>, player: number): void;
28
+ }
29
+ /** A checked game definition: give it to `GameServer` and `GameClient`. */
30
+ export interface Game<State = unknown, Input = unknown> {
31
+ /** The schema. */
32
+ readonly schema: UntypedSchema;
33
+ /** Name of the state struct. */
34
+ readonly stateType: string;
35
+ /** Name of the input struct. */
36
+ readonly inputType: string;
37
+ /** Ticks per second. */
38
+ readonly tickRate: number;
39
+ /** Milliseconds per tick. */
40
+ readonly tickMs: number;
41
+ /** The state at tick 0. */
42
+ initial(): State;
43
+ /** The deterministic step. */
44
+ step(state: State, inputs: ReadonlyMap<number, Input>, tick: number, dt: number): void;
45
+ /** Adds a player. */
46
+ join(state: State, player: number): void;
47
+ /** Removes a player. */
48
+ leave(state: State, player: number): void;
49
+ }
50
+ /**
51
+ * Checks a game definition.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * const game = defineGame({
56
+ * schema, state: 'State', input: 'Input', tickRate: 30,
57
+ * initial: () => ({ boxes: new Map() }),
58
+ * join: (state, id) => void state.boxes.set(id, { x: 0, y: 0, owner: id }),
59
+ * leave: (state, id) => void state.boxes.delete(id),
60
+ * step(state, inputs, _tick, dt) {
61
+ * for (const [id, input] of inputs) { const box = state.boxes.get(id); if (box) box.x += input.x * 5 * dt; }
62
+ * },
63
+ * });
64
+ * ```
65
+ * @throws TypeError when `state` or `input` names no struct of the schema, or `initial` or `step` is missing;
66
+ * RangeError for a tick rate that is not an integer from 1 to 240.
67
+ */
68
+ export declare function defineGame<const S extends SchemaShape, const SN extends TypeName<S>, const IN extends TypeName<S>>(definition: GameDefinition<S, SN, IN>): Game<Infer<S, SN>, Infer<S, IN>>;
@@ -0,0 +1,14 @@
1
+ import { type NormalizedSchema } from './schema.js';
2
+ /** Options for standalone Rust generation. */
3
+ export interface GenerateRustOptions {
4
+ /** Optional source label, sanitized to one comment line. */
5
+ source?: string;
6
+ }
7
+ /**
8
+ * Generate standalone Rust 2021 structs and full/delta codecs from schema.json or a compiled schema.
9
+ * Types are Msg<Name>, fields f_<name>, enums their u32 wire indices and optionals boxed.
10
+ * @throws TypeError for invalid schema input; schema validation errors retain their original type and field context.
11
+ */
12
+ export declare function generateRust(input: NormalizedSchema | {
13
+ json: NormalizedSchema;
14
+ }, options?: GenerateRustOptions): string;
@@ -0,0 +1,184 @@
1
+ import { r as e } from "./schema-CMfqK4Gu.js";
2
+ //#region src/generate-rust.ts
3
+ var t = String.raw`
4
+ /// Checked codec support. Generated types use only Rust's standard library.
5
+ #[allow(dead_code)]
6
+ pub mod margo_wire {
7
+ use std::collections::BTreeMap;
8
+ /// Invalid value, malformed bytes or unsupported nesting. Never a partial decode.
9
+ #[derive(Debug, Clone, PartialEq)] pub struct Error(pub &'static str);
10
+ impl std::fmt::Display for Error { fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result { write!(f,"Schema codec: {}; use validated values and matching schema bytes (https://margoengine.com/errors)",self.0) } }
11
+ impl std::error::Error for Error {}
12
+ pub type Result<T> = std::result::Result<T,Error>;
13
+ #[derive(Clone,Debug)] pub(super) enum V { U(u32), I(i32), N(f64), B(bool), S(String), Bytes(Vec<u8>), E(u32), A(Vec<V>), O(Option<Box<V>>), M(BTreeMap<u32,V>), T(Vec<V>) }
14
+ pub(super) enum F { U(usize), I(usize), Uint, Int, Float(usize), Bool, Quant(f64,f64,u32), Text(usize), Bytes(usize), Enum(u32), Array(&'static F,usize), Optional(&'static F), Map(&'static F,usize), Struct(usize) }
15
+ fn err<T>(s:&'static str)->Result<T> { Err(Error(s)) }
16
+ fn var(w:&mut Vec<u8>,mut n:u32) { while n>127 { w.push((n as u8 & 127)|128); n>>=7; } w.push(n as u8); }
17
+ fn count_write(w:&mut Vec<u8>,n:usize,max:usize)->Result<()> { if n>max || n>u32::MAX as usize {return err("count exceeds schema limit");} var(w,n as u32); Ok(()) }
18
+ struct R<'a> { b:&'a [u8], at:usize }
19
+ impl<'a> R<'a> {
20
+ fn raw(&mut self,n:usize)->Result<&'a [u8]> { if n>self.b.len()-self.at {return err("truncated input");} let at=self.at;self.at+=n;Ok(&self.b[at..self.at]) }
21
+ fn byte(&mut self)->Result<u8> {Ok(self.raw(1)?[0])}
22
+ fn uint(&mut self,n:usize)->Result<u32> { let mut v=0u32; for (i,b) in self.raw(n)?.iter().enumerate() {v|=(*b as u32)<<(8*i);} Ok(v) }
23
+ fn var(&mut self)->Result<u32> { let mut n=0; for i in 0..5 {let b=self.byte()?; if i==4 && b>15 {return err("varint exceeds 32 bits");} n|=((b&127) as u32)<<(7*i);if b<128 {return Ok(n);}} err("invalid varint") }
24
+ fn count(&mut self,max:usize)->Result<usize> {let n=self.var()? as usize;if n>max || n>self.b.len()-self.at {return err("count exceeds schema or remaining input");}Ok(n)}
25
+ fn ids(&mut self,max:usize)->Result<Vec<u32>> {let n=self.count(max)?;let mut out=Vec::new();let mut next=0u64;for _ in 0..n {let id=next+self.var()? as u64;if id>u32::MAX as u64 {return err("entity id overflow");}out.push(id as u32);next=id+1;}Ok(out)}
26
+ }
27
+ fn ids(w:&mut Vec<u8>,keys:&[u32]) {var(w,keys.len() as u32);let mut next=0u64;for key in keys {var(w,(*key as u64-next) as u32);next=*key as u64+1;}}
28
+ fn q(v:f64,min:f64,max:f64,bits:u32)->u32 {((v-min)*(((1u64<<bits)-2) as f64/(max-min))).round() as u32}
29
+ pub(super) fn same(f:&F,a:&V,b:&V)->bool { match (f,a,b) {
30
+ (F::Float(4),V::N(a),V::N(b))=>(*a as f32)==(*b as f32),
31
+ (F::Quant(min,max,bits),V::N(a),V::N(b))=>q(*a,*min,*max,*bits)==q(*b,*min,*max,*bits),
32
+ (_,V::U(a),V::U(b))=>a==b,(_,V::I(a),V::I(b))=>a==b,(_,V::N(a),V::N(b))=>a==b,(_,V::B(a),V::B(b))=>a==b,(_,V::S(a),V::S(b))=>a==b,(_,V::Bytes(a),V::Bytes(b))=>a==b,(_,V::E(a),V::E(b))=>a==b,
33
+ (F::Array(f,_),V::A(a),V::A(b))=>a.len()==b.len()&&a.iter().zip(b).all(|(a,b)|same(f,a,b)),
34
+ (F::Optional(f),V::O(a),V::O(b))=>match(a,b){(Some(a),Some(b))=>same(f,a,b),(None,None)=>true,_=>false},
35
+ (F::Map(f,_),V::M(a),V::M(b))=>a.len()==b.len()&&a.iter().all(|(id,a)|b.get(id).is_some_and(|b|same(f,a,b))),
36
+ (F::Struct(i),V::T(a),V::T(b))=>a.len()==b.len()&&super::__TYPES[*i].iter().zip(a.iter().zip(b)).all(|(f,(a,b))|same(f,a,b)),_=>false } }
37
+ fn write(f:&F,v:&V,w:&mut Vec<u8>,depth:usize)->Result<()> {if depth>256{return err("nesting exceeds 256");}match(f,v){
38
+ (F::U(n),V::U(v))=>{if *n<4 && *v>=(1u32<<(8*n)){return err("unsigned integer out of range");}w.extend_from_slice(&v.to_le_bytes()[..*n]);},
39
+ (F::I(n),V::I(v))=>{if *n<4 {let top=1i32<<(8*n-1);if *v< -top || *v>=top{return err("signed integer out of range");}}w.extend_from_slice(&v.to_le_bytes()[..*n]);},
40
+ (F::Uint,V::U(v))=>var(w,*v),(F::Int,V::I(v))=>var(w,((*v as u32)<<1)^((*v>>31) as u32)),
41
+ (F::Float(n),V::N(v))=>{if !v.is_finite() || (*n==4 && !(*v as f32).is_finite()){return err("non-finite float");}if *n==4{w.extend_from_slice(&(*v as f32).to_le_bytes());}else{w.extend_from_slice(&v.to_le_bytes());}},
42
+ (F::Bool,V::B(v))=>w.push(u8::from(*v)),
43
+ (F::Quant(min,max,bits),V::N(v))=>{if !(*v>=*min && *v<=*max){return err("quantized value outside range");}let n=q(*v,*min,*max,*bits);w.extend_from_slice(&n.to_le_bytes()[..(*bits as usize).div_ceil(8)]);},
44
+ (F::Text(max),V::S(v))=>{count_write(w,v.len(),*max)?;w.extend_from_slice(v.as_bytes());},
45
+ (F::Bytes(max),V::Bytes(v))=>{count_write(w,v.len(),*max)?;w.extend_from_slice(v);},
46
+ (F::Enum(max),V::E(v))=>{if v>=max{return err("enum index outside schema");}var(w,*v);},
47
+ (F::Array(f,max),V::A(v))=>{count_write(w,v.len(),*max)?;for v in v{write(f,v,w,depth+1)?;}},
48
+ (F::Optional(f),V::O(v))=>{w.push(u8::from(v.is_some()));if let Some(v)=v{write(f,v,w,depth+1)?;}},
49
+ (F::Map(f,max),V::M(v))=>{if v.len()>*max{return err("map exceeds limit");}ids(w,&v.keys().copied().collect::<Vec<_>>());for v in v.values(){write(f,v,w,depth+1)?;}},
50
+ (F::Struct(i),V::T(v))=>{let fields=super::__TYPES[*i];if fields.len()!=v.len(){return err("struct shape differs");}for(f,v) in fields.iter().zip(v){write(f,v,w,depth+1)?;}},_=>return err("value does not match schema")};Ok(())}
51
+ fn read(f:&F,r:&mut R<'_>,depth:usize)->Result<V>{if depth>256{return err("nesting exceeds 256");}Ok(match f{
52
+ F::U(n)=>V::U(r.uint(*n)?),F::I(n)=>{let u=r.uint(*n)?;let shift=32-8*n;V::I(((u<<shift) as i32)>>shift)},F::Uint=>V::U(r.var()?),F::Int=>{let u=r.var()?;V::I(((u>>1) as i32)^-((u&1) as i32))},
53
+ F::Float(n)=>{let v=if *n==4 {f32::from_le_bytes(r.raw(4)?.try_into().map_err(|_|Error("truncated float"))?) as f64}else{f64::from_le_bytes(r.raw(8)?.try_into().map_err(|_|Error("truncated float"))?)};if !v.is_finite(){return err("non-finite float");}V::N(v)},
54
+ F::Bool=>{let b=r.byte()?;if b>1{return err("invalid bool");}V::B(b==1)},
55
+ F::Quant(min,max,bits)=>{let v=r.uint((*bits as usize).div_ceil(8))?;let top=(1u64<<bits)-2;if v as u64>top{return err("quantized step outside range");}V::N(min+(max-min)*(v as f64/top as f64))},
56
+ F::Text(max)=>{let n=r.count(*max)?;V::S(std::str::from_utf8(r.raw(n)?).map_err(|_|Error("invalid UTF-8"))?.to_owned())},
57
+ F::Bytes(max)=>{let n=r.count(*max)?;V::Bytes(r.raw(n)?.to_vec())},F::Enum(max)=>{let n=r.var()?;if n>=*max{return err("invalid enum index");}V::E(n)},
58
+ F::Array(f,max)=>{let n=r.count(*max)?;let mut v=Vec::new();for _ in 0..n{v.push(read(f,r,depth+1)?);}V::A(v)},
59
+ F::Optional(f)=>{let b=r.byte()?;if b>1{return err("invalid optional flag");}V::O(if b==1{Some(Box::new(read(f,r,depth+1)?))}else{None})},
60
+ F::Map(f,max)=>{let keys=r.ids(*max)?;let mut v=BTreeMap::new();for id in keys{v.insert(id,read(f,r,depth+1)?);}V::M(v)},
61
+ F::Struct(i)=>V::T(super::__TYPES[*i].iter().map(|f|read(f,r,depth+1)).collect::<Result<_>>()?)})}
62
+ fn delta_write(f:&F,v:&V,base:&V,w:&mut Vec<u8>,depth:usize)->Result<()> {if depth>256{return err("nesting exceeds 256");}match(f,v,base){
63
+ (F::Struct(i),V::T(v),V::T(base))=>{let fields=super::__TYPES[*i];let mut mask=vec![0u8;fields.len().div_ceil(8)];for(i,((f,v),b))in fields.iter().zip(v).zip(base).enumerate(){if !same(f,v,b){mask[i/8]|=1<<(i%8);}}w.extend_from_slice(&mask);for(i,((f,v),b))in fields.iter().zip(v).zip(base).enumerate(){if mask[i/8]&(1<<(i%8))!=0{delta_write(f,v,b,w,depth+1)?;}}},
64
+ (F::Map(f,max),V::M(v),V::M(base))=>{if v.len()>*max{return err("map exceeds limit");}let removed=base.keys().filter(|id|!v.contains_key(id)).copied().collect::<Vec<_>>();let changed=v.iter().filter(|(id,v)|base.get(id).is_none_or(|b|!same(f,v,b))).map(|(id,_)|*id).collect::<Vec<_>>();ids(w,&removed);ids(w,&changed);for id in changed{let value=&v[&id];if let Some(b)=base.get(&id){delta_write(f,value,b,w,depth+1)?;}else{write(f,value,w,depth+1)?;}}},
65
+ _=>write(f,v,w,depth+1)?};Ok(())}
66
+ fn delta_read(f:&F,r:&mut R<'_>,base:&V,depth:usize)->Result<V>{if depth>256{return err("nesting exceeds 256");}match(f,base){
67
+ (F::Struct(i),V::T(base))=>{let fields=super::__TYPES[*i];let mask=r.raw(fields.len().div_ceil(8))?.to_vec();if fields.len()%8!=0 && mask[mask.len()-1]>>(fields.len()%8)!=0{return err("change mask past struct fields");}let mut out=Vec::new();for(i,(f,b))in fields.iter().zip(base).enumerate(){out.push(if mask[i/8]&(1<<(i%8))!=0{delta_read(f,r,b,depth+1)?}else{b.clone()});}Ok(V::T(out))},
68
+ (F::Map(f,max),V::M(base))=>{let removed=r.ids(base.len())?;for id in &removed{if !base.contains_key(id){return err("removed entity absent in baseline");}}let changed=r.ids(*max)?;let mut out=base.clone();for id in &removed{out.remove(id);}for id in changed{if removed.binary_search(&id).is_ok(){return err("entity removed and changed");}let v=if let Some(b)=out.get(&id){delta_read(f,r,b,depth+1)?}else{read(f,r,depth+1)?};out.insert(id,v);}if out.len()>*max{return err("delta map exceeds limit");}Ok(V::M(out))},_=>read(f,r,depth+1)}}
69
+ pub(super) fn encode(i:usize,v:&V,base:Option<&V>)->Result<Vec<u8>>{let mut w=Vec::new();if let Some(b)=base{delta_write(&F::Struct(i),v,b,&mut w,0)?;}else{write(&F::Struct(i),v,&mut w,0)?;}Ok(w)}
70
+ pub(super) fn decode(i:usize,b:&[u8],base:Option<&V>)->Result<V>{let mut r=R{b,at:0};let v=if let Some(base)=base{delta_read(&F::Struct(i),&mut r,base,0)?}else{read(&F::Struct(i),&mut r,0)?};if r.at!=b.len(){return err("trailing bytes");}Ok(v)}
71
+ }
72
+ `;
73
+ function n(n, r = {}) {
74
+ let i = n && "json" in n ? n.json : n;
75
+ if (!i?.types || typeof i.types != "object") throw TypeError("generateRust needs schema.json; pass a normalized schema or defineSchema result");
76
+ let a = (e) => e.type === "bool" ? "bool" : e.type === "struct" ? e.name : e.type === "array" || e.type === "map" || e.type === "optional" ? {
77
+ ...e,
78
+ of: a(e.of)
79
+ } : e, o = {};
80
+ for (let [e, t] of Object.entries(i.types)) o[e] = Object.fromEntries(Object.entries(t).map(([e, t]) => [e, a(t)]));
81
+ let s = e({
82
+ version: i.version,
83
+ types: o
84
+ }), c = Object.keys(s.json.types), l = (e) => {
85
+ switch (e.type) {
86
+ case "struct": return `Msg${e.name}`;
87
+ case "array": return `Vec<${l(e.of)}>`;
88
+ case "map": return `std::collections::BTreeMap<u32,${l(e.of)}>`;
89
+ case "optional": return `Option<Box<${l(e.of)}>>`;
90
+ case "enum":
91
+ case "uint": return "u32";
92
+ case "int": return "i32";
93
+ case "string": return "String";
94
+ case "bytes": return "Vec<u8>";
95
+ case "quantized": return "f64";
96
+ default: return e.type;
97
+ }
98
+ }, u = (e) => `${JSON.stringify(e)}f64`, d = (e) => {
99
+ switch (e.type) {
100
+ case "struct": return `margo_wire::F::Struct(${c.indexOf(e.name)})`;
101
+ case "array": return `margo_wire::F::Array(&${d(e.of)},${e.maxLength})`;
102
+ case "map": return `margo_wire::F::Map(&${d(e.of)},${e.maxSize})`;
103
+ case "optional": return `margo_wire::F::Optional(&${d(e.of)})`;
104
+ case "enum": return `margo_wire::F::Enum(${e.values.length})`;
105
+ case "string": return `margo_wire::F::Text(${e.maxLength})`;
106
+ case "bytes": return `margo_wire::F::Bytes(${e.maxLength})`;
107
+ case "quantized": return `margo_wire::F::Quant(${u(e.min)},${u(e.max)},${e.bits})`;
108
+ case "bool": return "margo_wire::F::Bool";
109
+ case "uint": return "margo_wire::F::Uint";
110
+ case "int": return "margo_wire::F::Int";
111
+ default: return `margo_wire::F::${e.type[0] === "f" ? "Float" : e.type[0].toUpperCase()}(${Number(e.type.slice(1)) / 8})`;
112
+ }
113
+ }, f = (e, t) => {
114
+ switch (e.type) {
115
+ case "struct": return `margo_wire::V::from(${t})`;
116
+ case "array": return `margo_wire::V::A((${t}).iter().map(|v|${f(e.of, "v")}).collect())`;
117
+ case "map": return `margo_wire::V::M((${t}).iter().map(|(id,v)|(*id,${f(e.of, "v")})).collect())`;
118
+ case "optional": return `margo_wire::V::O((${t}).as_ref().map(|v|Box::new(${f(e.of, "v.as_ref()")})))`;
119
+ case "enum": return `margo_wire::V::E(*(${t}))`;
120
+ case "string": return `margo_wire::V::S((${t}).clone())`;
121
+ case "bytes": return `margo_wire::V::Bytes((${t}).clone())`;
122
+ case "bool": return `margo_wire::V::B(*(${t}))`;
123
+ case "f32":
124
+ case "f64":
125
+ case "quantized": return `margo_wire::V::N(*(${t}) as f64)`;
126
+ default: return `margo_wire::V::${e.type[0] === "u" ? "U" : "I"}(*(${t}) as ${e.type[0] === "u" ? "u32" : "i32"})`;
127
+ }
128
+ }, p = [], m = (e) => {
129
+ let t = `__from_${p.length}`;
130
+ p.push("");
131
+ let n = p.length - 1, r;
132
+ switch (e.type) {
133
+ case "struct":
134
+ r = `Msg${e.name}::__from(v)`;
135
+ break;
136
+ case "array":
137
+ r = `if let margo_wire::V::A(v)=v{return v.into_iter().map(${m(e.of)}).collect();}`;
138
+ break;
139
+ case "map":
140
+ r = `if let margo_wire::V::M(v)=v{return v.into_iter().map(|(id,v)|Ok((id,${m(e.of)}(v)?))).collect();}`;
141
+ break;
142
+ case "optional":
143
+ r = `if let margo_wire::V::O(v)=v{return v.map(|v|${m(e.of)}(*v).map(Box::new)).transpose();}`;
144
+ break;
145
+ default: {
146
+ let t = e.type === "bool" ? "B" : e.type === "string" ? "S" : e.type === "bytes" ? "Bytes" : e.type === "enum" ? "E" : [
147
+ "f32",
148
+ "f64",
149
+ "quantized"
150
+ ].includes(e.type) ? "N" : e.type[0] === "u" ? "U" : "I";
151
+ r = `if let margo_wire::V::${t}(v)=v{return Ok(v${[
152
+ "B",
153
+ "S",
154
+ "Bytes"
155
+ ].includes(t) ? "" : ` as ${l(e)}`});}`;
156
+ }
157
+ }
158
+ return p[n] = `fn ${t}(v:margo_wire::V)->margo_wire::Result<${l(e)}>{${r}${e.type === "struct" ? "" : "Err(margo_wire::Error(\"decoded field shape differs\"))"}}`, t;
159
+ }, h = [
160
+ `// Generated from ${String(r.source ?? "schema.json").replace(/[\r\n]/g, " ")} by @margoengine/netcode/generate-rust.`,
161
+ t,
162
+ `/// FNV-1a hash of normalized schema JSON.\npub const SCHEMA_HASH:u32=${s.hash};`,
163
+ `const __TYPES:&[&[margo_wire::F]]=&[${c.map((e) => `&[${Object.values(s.json.types[e]).map(d).join(",")}]`).join(",")}];`
164
+ ];
165
+ for (let [e, t] of c.entries()) {
166
+ let n = Object.entries(s.json.types[t]);
167
+ h.push(`#[derive(Clone,Debug,PartialEq)]\npub struct Msg${t}{${n.map(([e, t]) => `pub f_${e}:${l(t)}`).join(",")}}`, `impl From<&Msg${t}> for margo_wire::V{fn from(v:&Msg${t})->Self{Self::T(vec![${n.map(([e, t]) => f(t, `&v.f_${e}`)).join(",")}])}}`, `impl Msg${t}{
168
+ fn __from(v:margo_wire::V)->margo_wire::Result<Self>{if let margo_wire::V::T(v)=v{let mut fields=v.into_iter();Ok(Self{${n.map(([e, t]) => `f_${e}:${m(t)}(fields.next().ok_or(margo_wire::Error("missing field"))?)?`).join(",")}})}else{Err(margo_wire::Error("not a struct"))}}
169
+ /// Encode this complete value, validating bounds.
170
+ pub fn encode(&self)->margo_wire::Result<Vec<u8>>{margo_wire::encode(${e},&self.into(),None)}
171
+ /// Decode all bytes, refusing malformed/truncated input.
172
+ pub fn decode(bytes:&[u8])->margo_wire::Result<Self>{Self::__from(margo_wire::decode(${e},bytes,None)?)}
173
+ /// Encode the change from a matching decoded baseline.
174
+ pub fn encode_delta(&self,base:&Self)->margo_wire::Result<Vec<u8>>{margo_wire::encode(${e},&self.into(),Some(&base.into()))}
175
+ /// Apply a change without mutating the baseline.
176
+ pub fn decode_delta(bytes:&[u8],base:&Self)->margo_wire::Result<Self>{Self::__from(margo_wire::decode(${e},bytes,Some(&base.into()))?)}
177
+ /// Schema equality, including float/quantized wire precision.
178
+ pub fn same(&self,other:&Self)->bool{margo_wire::same(&margo_wire::F::Struct(${e}),&self.into(),&other.into())}
179
+ }`);
180
+ }
181
+ return `${h.join("\n")}\n${p.join("\n")}\n`;
182
+ }
183
+ //#endregion
184
+ export { n as generateRust };
@@ -0,0 +1,25 @@
1
+ import type { NormalizedSchema, SchemaCodec, SchemaDefinition, SchemaShape } from './schema.js';
2
+ /** Options of {@link generateTypeScript}. */
3
+ export interface GenerateOptions {
4
+ /** A line naming where the schema came from, put in the header comment (default none). */
5
+ source?: string;
6
+ }
7
+ /**
8
+ * The TypeScript source of a standalone module (no imports, erasable syntax only, so Node runs it as it is) with an
9
+ * interface per struct and `encode<Name>`, `decode<Name>`, `encode<Name>Delta`, `decode<Name>Delta` and `same<Name>`
10
+ * per struct, writing and checking exactly what `schema.encode` and `schema.decode` do, plus `SCHEMA_HASH`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { writeFileSync } from 'node:fs';
15
+ * import { generateTypeScript } from '@margoengine/netcode/generate';
16
+ * import { defineSchema } from '@margoengine/netcode';
17
+ * const schema = defineSchema({ types: { Ping: { at: 'f64' } } });
18
+ * writeFileSync('ping.protocol.ts', generateTypeScript(schema, { source: 'schema.ts' }));
19
+ * ```
20
+ * @throws TypeError when `schema` is neither a compiled schema nor its normalized JSON.
21
+ */
22
+ export declare function generateTypeScript(schema: SchemaCodec<SchemaShape> | SchemaCodec<SchemaDefinition> | {
23
+ json: NormalizedSchema;
24
+ hash: number;
25
+ }, options?: GenerateOptions): string;