bevy-react 0.1.1

Drive bevy_ui from a React app over an embedded V8 runtime.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! TypeScript code generation for the typed app-messaging surface.
//!
//! The Rust binding structs (`#[react_message]` / `#[react_request]` /
//! `#[react_event]`) are the single source of truth. This module walks the three
//! registries ([`ReactRegistry`], [`ReactRequestRegistry`], [`ReactEventRegistry`])
//! in one pass and renders a self-contained `bevy.ts`: per-payload type
//! declarations, the `ReactMessages` / `ReactRequests` / `ReactEvents` maps, typed
//! `emit` / `request` / `on` wrappers, and a structured `bevy` proxy object.
//!
//! [`export`] writes that module to disk; it backs
//! [`ReactAppExt::export_react_typescript`](crate::ReactAppExt::export_react_typescript).
//!
//! Output is deterministic (sorted) so a `git diff --exit-code` after regeneration
//! is the sync guarantee between Rust and TypeScript.

use std::any::TypeId;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Write as _;
use std::path::Path;

use bevy::ecs::world::World;
use ts_rs::{TS, TypeVisitor};

use crate::event::ReactEventRegistry;
use crate::message::ReactRegistry;
use crate::request::ReactRequestRegistry;

/// Render the three registries as one self-contained TypeScript module: every
/// payload/request/response/event type declaration (plus transitive dependencies),
/// the `ReactMessages` / `ReactRequests` / `ReactEvents` maps, typed
/// `emit`/`request`/`on` wrappers, and the structured `bevy` proxy object. See
/// [`ReactAppExt::export_react_typescript`](crate::ReactAppExt::export_react_typescript).
///
/// Output is deterministic (sorted) so a `git diff --exit-code` after regeneration
/// is the sync guarantee between Rust and TypeScript.
pub(crate) fn render_typescript(
    messages: &ReactRegistry,
    requests: &ReactRequestRegistry,
    events: &ReactEventRegistry,
) -> String {
    // One shared collector across all three registries: a type referenced by more
    // than one (e.g. a struct used as both a message and a response) is declared once.
    let mut collector = TsCollector::default();
    for reg in messages.handlers.values() {
        (reg.ts_collect)(&mut collector);
    }
    for reg in requests.handlers.values() {
        (reg.ts_collect)(&mut collector);
    }
    for reg in events.handlers.values() {
        (reg.ts_collect)(&mut collector);
    }
    // Built-in framework events: always seeded so `bevy.on("keyDown", …)` is typed
    // in every app with no per-app registration (see `crate::keyboard`).
    collector.add::<crate::keyboard::KeyDown>();
    collector.add::<crate::keyboard::KeyUp>();

    // Sorted name lists keep the maps and proxy stable across runs.
    let mut message_names: Vec<(&str, String)> = messages
        .handlers
        .iter()
        .map(|(name, reg)| (*name, (reg.ts_name)()))
        .collect();
    message_names.sort();

    let mut request_rows: Vec<RequestRow> = requests
        .handlers
        .iter()
        .map(|(name, reg)| RequestRow {
            name,
            request_ts: (reg.ts_request_name)(),
            response_ts: (reg.ts_response_name)(),
            void: (reg.request_is_void)(),
        })
        .collect();
    request_rows.sort_by(|a, b| a.name.cmp(b.name));

    // `keyDown`/`keyUp` are reserved for the built-in keyboard events; drop any
    // app event that collides so the generated interface can't get a duplicate key,
    // then append the built-ins (always present).
    const BUILTIN_EVENTS: [&str; 2] = ["keyDown", "keyUp"];
    let mut event_names: Vec<(&str, String)> = events
        .handlers
        .iter()
        .map(|(name, reg)| (*name, (reg.ts_name)()))
        .filter(|(name, _)| !BUILTIN_EVENTS.contains(name))
        .collect();
    event_names.push(("keyDown", <crate::keyboard::KeyDown as TS>::name()));
    event_names.push(("keyUp", <crate::keyboard::KeyUp as TS>::name()));
    event_names.sort();

    let mut out = String::new();
    out.push_str(
        "// @generated by bevy-react — do not edit by hand.\n\
         // Mirrors the Rust `#[react_message]` / `#[react_request]` / `#[react_event]`\n\
         // types. Regenerate via your app's `App::export_react_typescript` exporter.\n\n\
         import {\n\
         \x20 emit as rawEmit,\n\
         \x20 request as rawRequest,\n\
         \x20 addEventListener as rawAddEventListener,\n\
         \x20 removeEventListener as rawRemoveEventListener,\n\
         } from \"bevy-react\";\n\n",
    );

    // Type declarations.
    for decl in collector.decls.values() {
        writeln!(out, "export {decl}").unwrap();
    }

    // Maps.
    out.push_str("\n/** Every `emit` name and the payload type it carries. */\n");
    out.push_str("export interface ReactMessages {\n");
    for (name, ts_name) in &message_names {
        writeln!(out, "  {}: {ts_name};", json_key(name)).unwrap();
    }
    out.push_str("}\n\n");

    out.push_str("/** Every `request` name and its request/response types. */\n");
    out.push_str("export interface ReactRequests {\n");
    for row in &request_rows {
        let request_ts = if row.void { "null" } else { &row.request_ts };
        writeln!(
            out,
            "  {}: {{ request: {request_ts}; response: {} }};",
            json_key(row.name),
            row.response_ts,
        )
        .unwrap();
    }
    out.push_str("}\n\n");

    out.push_str("/** Every Bevy → React event name and the payload it carries. */\n");
    out.push_str("export interface ReactEvents {\n");
    for (name, ts_name) in &event_names {
        writeln!(out, "  {}: {ts_name};", json_key(name)).unwrap();
    }
    out.push_str("}\n\n");

    // Typed standalone wrappers.
    out.push_str(
        "/** Send a typed app message to the Bevy side. */\n\
         export function emit<K extends keyof ReactMessages>(name: K, value: ReactMessages[K]): void {\n\
         \x20 rawEmit(name, value);\n\
         }\n\n\
         /** Send a typed request and await its typed response. */\n\
         export function request<K extends keyof ReactRequests>(\n\
         \x20 name: K,\n\
         \x20 value: ReactRequests[K][\"request\"],\n\
         ): Promise<ReactRequests[K][\"response\"]> {\n\
         \x20 return rawRequest(name, value) as Promise<ReactRequests[K][\"response\"]>;\n\
         }\n\n\
         /** Subscribe to a typed Bevy → React event. Returns an unsubscribe fn. */\n\
         export function on<K extends keyof ReactEvents>(\n\
         \x20 name: K,\n\
         \x20 cb: (value: ReactEvents[K]) => void,\n\
         ): () => void {\n\
         \x20 rawAddEventListener(name, cb as (value: unknown) => void);\n\
         \x20 return () => rawRemoveEventListener(name, cb as (value: unknown) => void);\n\
         }\n\n\
         /** Unsubscribe a listener previously passed to `on`/`addEventListener`. */\n\
         export function removeEventListener<K extends keyof ReactEvents>(\n\
         \x20 name: K,\n\
         \x20 cb: (value: ReactEvents[K]) => void,\n\
         ): void {\n\
         \x20 rawRemoveEventListener(name, cb as (value: unknown) => void);\n\
         }\n\n",
    );

    // The structured `bevy` proxy object.
    out.push_str(&render_bevy_object(&request_rows, &message_names));
    out
}

/// One request's exporter metadata.
struct RequestRow<'a> {
    name: &'a str,
    request_ts: String,
    response_ts: String,
    void: bool,
}

/// A node in the nested proxy tree built from dotted request/message names.
enum ProxyNode<'a> {
    Namespace(BTreeMap<String, ProxyNode<'a>>),
    Leaf(ProxyLeaf<'a>),
}

/// A leaf method in the proxy: a request (awaits a typed response) or a
/// fire-and-forget message (returns `void`).
enum ProxyLeaf<'a> {
    Request(&'a RequestRow<'a>),
    Message { name: &'a str, ts_name: &'a str },
}

/// Build the `bevy` object literal: the typed wrappers plus a nested proxy where a
/// request `"board.get"` becomes `bevy.board.get(...)` and a message
/// `"basicDemo.setCount"` becomes `bevy.basicDemo.setCount(...)`.
fn render_bevy_object(requests: &[RequestRow], messages: &[(&str, String)]) -> String {
    // Reserved top-level keys the wrappers occupy; a binding must not collide.
    const RESERVED: [&str; 5] = [
        "emit",
        "request",
        "on",
        "addEventListener",
        "removeEventListener",
    ];

    let mut root: BTreeMap<String, ProxyNode> = BTreeMap::new();
    for row in requests {
        let segments: Vec<&str> = row.name.split('.').collect();
        insert_proxy(&mut root, &segments, ProxyLeaf::Request(row), row.name);
    }
    for &(name, ref ts_name) in messages {
        let segments: Vec<&str> = name.split('.').collect();
        insert_proxy(
            &mut root,
            &segments,
            ProxyLeaf::Message {
                name,
                ts_name: ts_name.as_str(),
            },
            name,
        );
    }
    for key in root.keys() {
        if RESERVED.contains(&key.as_str()) {
            panic!(
                "react binding {key:?} collides with a reserved `bevy` method; rename it (e.g. give it a dotted namespace)"
            );
        }
    }

    let mut out = String::new();
    out.push_str(
        "/** Structured, fully typed proxy over every message, request, and event. */\n\
         export const bevy = {\n\
         \x20 emit,\n\
         \x20 request,\n\
         \x20 on,\n\
         \x20 addEventListener: on,\n\
         \x20 removeEventListener,\n",
    );
    for (key, node) in &root {
        render_proxy_node(&mut out, key, node, 1);
    }
    out.push_str("} as const;\n");
    out
}

/// Insert a request/message leaf at its dotted path, panicking on a
/// namespace/leaf clash (a name used as both a method and a namespace, or claimed
/// by two bindings).
fn insert_proxy<'a>(
    tree: &mut BTreeMap<String, ProxyNode<'a>>,
    segments: &[&str],
    leaf: ProxyLeaf<'a>,
    full_name: &str,
) {
    let (head, rest) = segments.split_first().expect("binding name is non-empty");
    if rest.is_empty() {
        if tree
            .insert((*head).to_string(), ProxyNode::Leaf(leaf))
            .is_some()
        {
            panic!(
                "react binding name {full_name:?} is ambiguous (used as both a method and a namespace, or claimed by two bindings)"
            );
        }
        return;
    }
    let child = tree
        .entry((*head).to_string())
        .or_insert_with(|| ProxyNode::Namespace(BTreeMap::new()));
    match child {
        ProxyNode::Namespace(children) => insert_proxy(children, rest, leaf, full_name),
        ProxyNode::Leaf(_) => panic!(
            "react binding name {full_name:?} is ambiguous (used as both a method and a namespace)"
        ),
    }
}

/// Render one proxy node (a namespace object, a request method, or a message
/// method) at `depth`.
fn render_proxy_node(out: &mut String, key: &str, node: &ProxyNode, depth: usize) {
    let indent = "  ".repeat(depth);
    let method = json_key(key);
    match node {
        ProxyNode::Leaf(ProxyLeaf::Request(row)) => {
            if row.void {
                writeln!(
                    out,
                    "{indent}{method}(): Promise<{}> {{ return request({:?}, null); }},",
                    row.response_ts, row.name,
                )
                .unwrap();
            } else {
                writeln!(
                    out,
                    "{indent}{method}(value: {}): Promise<{}> {{ return request({:?}, value); }},",
                    row.request_ts, row.response_ts, row.name,
                )
                .unwrap();
            }
        }
        ProxyNode::Leaf(ProxyLeaf::Message { name, ts_name }) => {
            writeln!(
                out,
                "{indent}{method}(value: {ts_name}): void {{ emit({name:?}, value); }},",
            )
            .unwrap();
        }
        ProxyNode::Namespace(children) => {
            writeln!(out, "{indent}{method}: {{").unwrap();
            for (child_key, child) in children {
                render_proxy_node(out, child_key, child, depth + 1);
            }
            writeln!(out, "{indent}}},").unwrap();
        }
    }
}

/// Walks a payload type and its dependencies, collecting each one's TypeScript
/// declaration exactly once. `ts-rs` renders references by name (not by import), so
/// concatenating every declaration into one file yields a self-contained module.
///
/// Shared across the message, request, and event registries so a type referenced
/// by more than one of them is declared once (deduped by `TypeId`).
#[derive(Default)]
pub(crate) struct TsCollector {
    seen: HashSet<TypeId>,
    /// type name → its `ts-rs` declaration, ordered for stable output.
    decls: BTreeMap<String, String>,
}

impl TsCollector {
    /// Record `T`'s declaration (if unseen) and recurse into the types it references.
    pub(crate) fn add<T: TS + 'static + ?Sized>(&mut self) {
        if self.seen.insert(TypeId::of::<T>()) {
            // Only types with their own file get a declaration. Transparent newtypes
            // (e.g. `struct Count(usize)` → `number`) and primitives inline into their
            // referent, so `decl()` would panic — skip them and keep their inline name.
            if T::output_path().is_some() {
                self.decls.insert(T::name(), T::decl());
            }
            // `visit_dependencies` surfaces named types referenced by fields; a
            // container's *inner* type (e.g. `Vec<CubeInfo>` → `CubeInfo`) is surfaced
            // by `visit_generics` instead, so we must walk both to be self-contained.
            T::visit_dependencies(self);
            T::visit_generics(self);
        }
    }
}

impl TypeVisitor for TsCollector {
    fn visit<T: TS + 'static + ?Sized>(&mut self) {
        self.add::<T>();
    }
}

/// Quote a TypeScript object key only when it isn't a plain identifier, so common
/// names stay readable (`count:`) while odd ones (`hp-bar:`) are still valid.
fn json_key(name: &str) -> String {
    let is_ident = !name.is_empty()
        && name.chars().enumerate().all(|(i, c)| {
            c == '_' || c == '$' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit())
        });
    if is_ident {
        name.to_string()
    } else {
        format!("{name:?}")
    }
}

/// Render every registered React message/request/event to a self-contained
/// TypeScript module at `path`, creating any missing parent directories.
///
/// Any registry may be absent if nothing of that kind was registered; we fall back
/// to an empty one so the module is still valid. Backs
/// [`ReactAppExt::export_react_typescript`](crate::ReactAppExt::export_react_typescript).
pub(crate) fn export(world: &World, path: &Path) -> std::io::Result<()> {
    let empty_messages = ReactRegistry::default();
    let empty_requests = ReactRequestRegistry::default();
    let empty_events = ReactEventRegistry::default();
    let contents = render_typescript(
        world
            .get_resource::<ReactRegistry>()
            .unwrap_or(&empty_messages),
        world
            .get_resource::<ReactRequestRegistry>()
            .unwrap_or(&empty_requests),
        world
            .get_resource::<ReactEventRegistry>()
            .unwrap_or(&empty_events),
    );
    // Create any missing parent directories so callers can point at a path whose
    // containing dir doesn't exist yet (e.g. `ui/src/bevy.ts`) without a NotFound
    // from `fs::write`.
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, contents)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ReactAppExt, react_message};
    use bevy::prelude::*;

    #[derive(Resource, Default)]
    struct LastCount(usize);

    #[react_message]
    struct Count(usize);

    // A struct payload with a nested type, to exercise object rendering and the
    // transitive-dependency collection.
    #[react_message]
    #[allow(dead_code)]
    struct Move {
        delta: Vec2i,
    }

    #[derive(serde::Deserialize, ts_rs::TS)]
    #[allow(dead_code)]
    struct Vec2i {
        x: i32,
        y: i32,
    }

    // A void request (unit struct) and a request with a payload + response, to
    // exercise the request map, the void special-case, and the nested `bevy` proxy.
    #[crate::react_request(name = "board.get", response = BoardSnapshot)]
    #[allow(dead_code)]
    struct BoardGet;

    #[crate::react_request(name = "pieces.move", response = MoveStatus)]
    #[allow(dead_code)]
    struct PiecesMove {
        to: String,
    }

    #[derive(serde::Serialize, ts_rs::TS)]
    #[allow(dead_code)]
    struct BoardSnapshot {
        fen: String,
    }

    // A request whose response is a `Vec` of a custom struct, to exercise that the
    // collector declares a container's *inner* named type (surfaced via generics).
    #[crate::react_request(name = "pieces.list", response = Vec<PieceInfo>)]
    #[allow(dead_code)]
    struct PiecesList;

    #[derive(serde::Serialize, ts_rs::TS)]
    #[allow(dead_code)]
    struct PieceInfo {
        kind: String,
    }

    #[derive(serde::Serialize, ts_rs::TS)]
    #[allow(dead_code)]
    struct MoveStatus {
        ok: bool,
    }

    #[crate::react_event(name = "user.disconnected")]
    #[allow(dead_code)]
    struct UserDisconnected {
        user_id: String,
    }

    /// The exporter mirrors registered messages, requests, and events (and their
    /// dependencies) into a self-contained, deterministically-ordered module.
    #[test]
    fn exports_typescript() {
        let mut app = App::new();
        app.init_resource::<LastCount>();
        app.add_react_handler(|on: On<Count>, mut last: ResMut<LastCount>| last.0 = on.event().0);
        app.add_react_message::<Move>();
        app.add_react_request::<BoardGet>();
        app.add_react_request::<PiecesMove>();
        app.add_react_request::<PiecesList>();
        app.add_react_event::<UserDisconnected>();

        let world = app.world();
        let render = || {
            render_typescript(
                world.resource::<ReactRegistry>(),
                world.resource::<ReactRequestRegistry>(),
                world.resource::<ReactEventRegistry>(),
            )
        };
        let ts = render();

        // Each payload gets a named alias mirroring its Rust shape; nested types too.
        assert!(ts.contains("export type Count = number;"), "{ts}");
        assert!(ts.contains("export type Vec2i = "), "{ts}");
        assert!(ts.contains("export type Move = "), "{ts}");
        // The three maps key by name.
        assert!(ts.contains("count: Count;"), "{ts}");
        assert!(ts.contains("move: Move;"), "{ts}");
        assert!(
            ts.contains(r#""board.get": { request: null; response: BoardSnapshot };"#),
            "{ts}"
        );
        assert!(
            ts.contains(r#""pieces.move": { request: PiecesMove; response: MoveStatus };"#),
            "{ts}"
        );
        assert!(
            ts.contains(r#""user.disconnected": UserDisconnected;"#),
            "{ts}"
        );
        // Built-in keyboard events are always seeded, even with none registered.
        assert!(
            ts.contains("export type KeyDown = KeyboardEventData;"),
            "{ts}"
        );
        assert!(
            ts.contains("export type KeyUp = KeyboardEventData;"),
            "{ts}"
        );
        assert!(ts.contains("keyDown: KeyDown;"), "{ts}");
        assert!(ts.contains("keyUp: KeyUp;"), "{ts}");
        // A `Vec<PieceInfo>` response declares its inner struct and types as an array.
        assert!(ts.contains("export type PieceInfo = "), "{ts}");
        assert!(
            ts.contains(r#""pieces.list": { request: null; response: Array<PieceInfo> };"#),
            "{ts}"
        );
        // Typed wrappers + the nested proxy (void request → no-arg method).
        assert!(
            ts.contains("export function request<K extends keyof ReactRequests>"),
            "{ts}"
        );
        assert!(
            ts.contains(r#"get(): Promise<BoardSnapshot> { return request("board.get", null); }"#),
            "{ts}"
        );
        assert!(
            ts.contains(
                r#"move(value: PiecesMove): Promise<MoveStatus> { return request("pieces.move", value); }"#
            ),
            "{ts}"
        );
        // Messages fold into the proxy too, as fire-and-forget `void` methods.
        assert!(
            ts.contains(r#"count(value: Count): void { emit("count", value); }"#),
            "{ts}"
        );
        assert!(
            ts.contains(r#"move(value: Move): void { emit("move", value); }"#),
            "{ts}"
        );
        // Output is stable across runs (no HashMap iteration order leaking in).
        assert_eq!(ts, render());
    }
}