vox-codegen 0.8.2

Language bindings codegen for vox
Documentation
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
//! TypeScript code generation for vox services.
//!
//! This module generates TypeScript client and server code from service definitions.
//! The generated code includes:
//! - Type definitions for all named types (structs, enums)
//! - Client interface and implementation for making RPC calls
//! - Handler interface for implementing the service
//! - A Dispatcher class that routes calls to handler methods
//! - A service descriptor for runtime schema-driven encode/decode

pub mod client;
pub mod http_client;
pub mod schema;
pub mod server;
pub mod types;
pub mod wire;

use crate::code_writer::CodeWriter;
use vox_types::{MethodDescriptor, ServiceDescriptor};

pub use client::generate_client;
pub use http_client::generate_http_client;
pub use schema::generate_descriptor;
pub use schema::generate_send_schema_table;
pub use server::generate_server;
pub use types::{collect_named_types, generate_named_types};

/// Generate method IDs as a TypeScript constant record.
pub fn generate_method_ids(methods: &[&MethodDescriptor]) -> String {
    use crate::render::{fq_name, hex_u64};

    let mut items = methods
        .iter()
        .map(|m| (fq_name(m), m.id.0))
        .collect::<Vec<_>>();
    items.sort_by(|a, b| a.0.cmp(&b.0));

    let mut out = String::new();
    out.push_str("// @generated by vox-codegen\n");
    out.push_str("// This file defines canonical vox method IDs.\n\n");
    out.push_str("export const METHOD_ID: Record<string, bigint> = {\n");
    for (name, id) in items {
        out.push_str(&format!("  \"{name}\": {}n,\n", hex_u64(id)));
    }
    out.push_str("} as const;\n");
    out
}

/// Generate a complete TypeScript module for a service.
///
/// This is the main entry point for TypeScript code generation.
pub fn generate_service(service: &ServiceDescriptor) -> String {
    use crate::code_writer::CodeWriter;
    use crate::cw_writeln;

    let mut output = String::new();
    let mut w = CodeWriter::with_indent_spaces(&mut output, 2);

    // Header
    cw_writeln!(w, "// @generated by vox-codegen").unwrap();
    cw_writeln!(
        w,
        "// DO NOT EDIT - regenerate with `cargo xtask codegen --typescript`"
    )
    .unwrap();
    w.blank_line().unwrap();

    generate_imports(service, &mut w);
    w.blank_line().unwrap();

    // Named types (structs and enums)
    let named_types = collect_named_types(service);
    output.push_str(&generate_named_types(&named_types));

    // Request/Response type aliases
    output.push_str(&generate_request_response_types(service, &named_types));

    // Client
    output.push_str(&generate_client(service));

    // Server (handler interface + dispatcher)
    output.push_str(&generate_server(service));

    // Pre-computed CBOR send schema table (must come before descriptor)
    output.push_str(&generate_send_schema_table(service));

    // Service descriptor
    output.push_str(&generate_descriptor(service));

    output
}

/// Generate imports for the service module.
fn generate_imports(service: &ServiceDescriptor, w: &mut CodeWriter<&mut String>) {
    use crate::cw_writeln;
    use vox_types::{ShapeKind, classify_shape, is_rx, is_tx};

    // Check if any method uses channels in args.
    let has_streaming = service
        .methods
        .iter()
        .any(|m| m.args.iter().any(|a| is_tx(a.shape) || is_rx(a.shape)));

    // Check if any method returns Result<T, E> (fallible methods)
    let has_fallible = service
        .methods
        .iter()
        .any(|m| matches!(classify_shape(m.return_shape), ShapeKind::Result { .. }));

    // Core runtime: descriptor types + Caller + session/conduit helpers
    cw_writeln!(
        w,
        "import type {{ Caller, MethodDescriptor, ServiceDescriptor, VoxCall, Dispatcher, RequestContext, SessionTransportOptions }} from \"@bearcove/vox-core\";"
    )
    .unwrap();
    cw_writeln!(
        w,
        "import {{ session, voxServiceMetadata }} from \"@bearcove/vox-core\";"
    )
    .unwrap();

    // WebSocket transport for connect helper
    cw_writeln!(w, "import {{ wsConnector }} from \"@bearcove/vox-ws\";").unwrap();

    // RpcError for fallible client methods
    if has_fallible {
        cw_writeln!(w, "import {{ RpcError }} from \"@bearcove/vox-core\";").unwrap();
    }

    // Tx/Rx and bindChannels for streaming handler args and type aliases
    if has_streaming {
        cw_writeln!(
            w,
            "import {{ Tx, Rx, argElementRefsForMethod, bindChannelsForTypeRefs, finalizeBoundChannelsForTypeRefs }} from \"@bearcove/vox-core\";"
        )
        .unwrap();
    }
}

/// Generate request/response type aliases, skipping any that conflict with named types
fn generate_request_response_types(
    service: &ServiceDescriptor,
    named_types: &[(String, &'static facet_core::Shape)],
) -> String {
    use heck::ToUpperCamelCase;
    use std::collections::HashSet;
    use types::ts_type;

    // Collect just the type names for conflict checking
    let type_names: HashSet<&str> = named_types.iter().map(|(name, _)| name.as_str()).collect();

    let mut out = String::new();
    out.push_str("// Request/Response type aliases\n");

    for method in service.methods {
        let method_name = method.method_name.to_upper_camel_case();
        let request_name = format!("{method_name}Request");
        let response_name = format!("{method_name}Response");

        // Only generate request type alias if it doesn't conflict with a named type
        if !type_names.contains(request_name.as_str()) {
            if method.args.is_empty() {
                out.push_str(&format!("export type {request_name} = [];\n"));
            } else if method.args.len() == 1 {
                let ty = ts_type(method.args[0].shape);
                out.push_str(&format!("export type {request_name} = [{ty}];\n"));
            } else {
                out.push_str(&format!("export type {request_name} = [\n"));
                for arg in method.args {
                    let ty = ts_type(arg.shape);
                    out.push_str(&format!("  {ty}, // {}\n", arg.name));
                }
                out.push_str("];\n");
            }
        }

        // Only generate response type alias if it doesn't conflict with a named type
        if !type_names.contains(response_name.as_str()) {
            let ret_ty = ts_type(method.return_shape);
            out.push_str(&format!("export type {response_name} = {ret_ty};\n"));
        }

        out.push('\n');
    }

    out
}

#[cfg(test)]
mod tests {
    #![allow(dead_code)]

    use super::generate_service;
    use facet::Facet;
    use vox_types::{
        RetryPolicy, Rx, ServiceDescriptor, Tx, method_descriptor, method_descriptor_with_retry,
    };

    #[derive(Facet)]
    struct RecursiveNode {
        next: Option<Box<RecursiveNode>>,
    }

    #[derive(Facet)]
    #[repr(transparent)]
    #[facet(transparent)]
    struct SessionId(pub String);

    #[derive(Facet)]
    struct SessionSummary {
        id: SessionId,
    }

    #[derive(Facet)]
    #[repr(u8)]
    enum ToolCallKind {
        Read,
        Execute,
    }

    #[derive(Facet)]
    #[repr(u8)]
    enum ToolCallStatus {
        Running,
        Success,
        Failure,
    }

    #[derive(Facet)]
    #[repr(u8)]
    enum PermissionResolution {
        Approved,
        Denied,
    }

    #[derive(Facet)]
    #[repr(u8)]
    enum ContentBlock {
        Text {
            text: String,
        },
        ToolCall {
            id: String,
            title: String,
            kind: Option<ToolCallKind>,
            status: ToolCallStatus,
        },
        Permission {
            id: String,
            title: String,
            kind: Option<ToolCallKind>,
            resolution: Option<PermissionResolution>,
        },
    }

    #[derive(Facet)]
    #[repr(u8)]
    enum BlockPatch {
        TextAppend {
            text: String,
        },
        ToolCallUpdate {
            id: String,
            kind: Option<ToolCallKind>,
            status: ToolCallStatus,
        },
    }

    #[derive(Facet)]
    #[repr(u8)]
    enum SessionEvent {
        BlockAppend {
            block_id: String,
            role: String,
            block: ContentBlock,
        },
        BlockPatch {
            block_id: String,
            role: String,
            patch: BlockPatch,
        },
    }

    #[derive(Facet)]
    struct SessionEventEnvelope {
        seq: u64,
        event: SessionEvent,
    }

    #[derive(Facet)]
    #[repr(u8)]
    enum SubscribeMessage {
        Event(SessionEventEnvelope),
        ReplayComplete,
    }

    #[test]
    fn generated_typescript_contains_no_postcard_primitive_usage() {
        let echo = method_descriptor::<(String,), String>("TestSvc", "echo", &["message"], None);
        let divide = method_descriptor::<(u64, u64), Result<u64, String>>(
            "TestSvc",
            "divide",
            &["lhs", "rhs"],
            None,
        );
        let methods = Box::leak(vec![echo, divide].into_boxed_slice());
        let service = ServiceDescriptor {
            service_name: "TestSvc",
            methods,
            doc: None,
        };

        let generated = generate_service(&service);
        assert!(
            !generated.contains("import * as pc from \"@bearcove/vox-postcard\""),
            "generated TypeScript must not import postcard primitive namespace:\n{generated}"
        );
        assert!(
            !generated.contains("pc."),
            "generated TypeScript must not call postcard primitives directly:\n{generated}"
        );
    }

    #[test]
    fn generated_typescript_uses_canonical_service_schemas() {
        let recurse = method_descriptor::<(RecursiveNode,), RecursiveNode>(
            "RecursiveSvc",
            "recurse",
            &["node"],
            None,
        );
        let methods = Box::leak(vec![recurse].into_boxed_slice());
        let service = ServiceDescriptor {
            service_name: "RecursiveSvc",
            methods,
            doc: None,
        };

        let generated = generate_service(&service);
        assert!(
            generated.contains("send_schemas"),
            "generated TypeScript must include canonical service schemas:\n{generated}"
        );
        assert!(
            !generated.contains("schema_registry"),
            "generated TypeScript must not include the legacy schema registry:\n{generated}"
        );
    }

    #[test]
    fn generated_typescript_emits_alias_for_transparent_newtype() {
        let summarize = method_descriptor::<(SessionId,), SessionSummary>(
            "SessionSvc",
            "summarize",
            &["id"],
            None,
        );
        let methods = Box::leak(vec![summarize].into_boxed_slice());
        let service = ServiceDescriptor {
            service_name: "SessionSvc",
            methods,
            doc: None,
        };

        let generated = generate_service(&service);
        assert!(
            generated.contains("export type SessionId = string;"),
            "transparent named newtypes must emit a type alias:\n{generated}"
        );
        assert!(
            generated.contains("id: SessionId;"),
            "uses of transparent named newtypes must keep alias name:\n{generated}"
        );
    }

    #[test]
    fn generated_typescript_emits_channel_schemas() {
        let subscribe = method_descriptor::<(Tx<u32>, Rx<u32>), ()>(
            "StreamSvc",
            "subscribe",
            &["output", "input"],
            None,
        );
        let methods = Box::leak(vec![subscribe].into_boxed_slice());
        let service = ServiceDescriptor {
            service_name: "StreamSvc",
            methods,
            doc: None,
        };

        let generated = generate_service(&service);
        assert!(
            generated.contains("kind: { tag: 'channel', direction: 'tx'"),
            "Tx<T> must be emitted into canonical service schemas:\n{generated}"
        );
        assert!(
            generated.contains("kind: { tag: 'channel', direction: 'rx'"),
            "Rx<T> must be emitted into canonical service schemas:\n{generated}"
        );
    }

    #[test]
    fn generated_typescript_emits_retry_policy_on_method_descriptors() {
        let fetch = method_descriptor_with_retry::<(), u64>(
            "RetrySvc",
            "fetch",
            &[],
            None,
            RetryPolicy::IDEM,
        );
        let effect = method_descriptor_with_retry::<(), Result<u64, String>>(
            "RetrySvc",
            "effect",
            &[],
            None,
            RetryPolicy::PERSIST,
        );
        let methods = Box::leak(vec![fetch, effect].into_boxed_slice());
        let service = ServiceDescriptor {
            service_name: "RetrySvc",
            methods,
            doc: None,
        };

        let generated = generate_service(&service);
        assert!(
            generated.contains("retry: { persist: false, idem: true }"),
            "generated TypeScript must include retry policy for idem methods:\n{generated}"
        );
        assert!(
            generated.contains("retry: { persist: true, idem: false }"),
            "generated TypeScript must include retry policy for persist methods:\n{generated}"
        );
    }

    #[test]
    fn generated_typescript_keeps_struct_variants_with_kind_fields_named() {
        let subscribe =
            method_descriptor::<(), SubscribeMessage>("ShipSvc", "subscribe", &[], None);
        let methods = Box::leak(vec![subscribe].into_boxed_slice());
        let service = ServiceDescriptor {
            service_name: "ShipSvc",
            methods,
            doc: None,
        };

        let generated = generate_service(&service);
        assert!(
            generated.contains(
                "name: 'ToolCall', index: 1, payload: { tag: 'struct', fields: [{ name: 'id'"
            ),
            "struct variants with a field named `kind` must stay struct variants in canonical schemas:\n{generated}"
        );
        assert!(
            generated.contains(
                "name: 'Permission', index: 2, payload: { tag: 'struct', fields: [{ name: 'id'"
            ),
            "similar struct variants must keep their named `kind` field in canonical schemas:\n{generated}"
        );
        assert!(
            generated.contains(
                "name: 'ToolCallUpdate', index: 1, payload: { tag: 'struct', fields: [{ name: 'id'"
            ),
            "patch variants with a field named `kind` must also stay struct variants in canonical schemas:\n{generated}"
        );
        assert!(
            generated.contains("{ name: 'kind', type_ref:"),
            "canonical struct variants must preserve the literal field name `kind`:\n{generated}"
        );
    }

    #[test]
    fn generated_typescript_avoids_parameter_properties_and_types_catch_error() {
        let divide = method_descriptor::<(u64, u64), Result<u64, String>>(
            "StrictSvc",
            "divide",
            &["lhs", "rhs"],
            None,
        );
        let methods = Box::leak(vec![divide].into_boxed_slice());
        let service = ServiceDescriptor {
            service_name: "StrictSvc",
            methods,
            doc: None,
        };

        let generated = generate_service(&service);
        assert!(
            !generated.contains("constructor(private readonly handler"),
            "generated TypeScript must avoid constructor parameter properties:\n{generated}"
        );
        assert!(
            generated.contains("private readonly handler: StrictSvcHandler;"),
            "dispatcher must emit an explicit handler field:\n{generated}"
        );
        assert!(
            generated.contains("constructor(handler: StrictSvcHandler)"),
            "dispatcher constructor must use explicit assignment parameter:\n{generated}"
        );
        assert!(
            generated.contains("catch (e: any)"),
            "fallible client methods must type catch binding for strict TypeScript:\n{generated}"
        );
    }
}