pub struct CodeGenerator { /* private fields */ }Expand description
Collects type definitions — from Rust sources or programmatically — and
generates TypeScript codec bindings for the rkyv-js runtime.
§Example
use rkyv_js_codegen::{CodeGenerator, codec};
let mut generator = CodeGenerator::new();
generator.add_struct("Point", [("x", codec::f64()), ("y", codec::f64())]);
let code = generator.generate().unwrap();
assert!(code.contains("export const ArchivedPoint = r.struct({"));
assert!(code.contains("export type Point = r.Infer<typeof ArchivedPoint>;"));Implementations§
Source§impl CodeGenerator
impl CodeGenerator
Sourcepub fn add_source_file(
&mut self,
path: impl AsRef<Path>,
) -> Result<&mut Self, Error>
pub fn add_source_file( &mut self, path: impl AsRef<Path>, ) -> Result<&mut Self, Error>
Parse a Rust source file and extract every type with a marker derive.
§Example
use rkyv_js_codegen::CodeGenerator;
fn main() -> Result<(), rkyv_js_codegen::Error> {
CodeGenerator::new()
.add_source_file("src/lib.rs")?
.write_to_file("generated/bindings.ts")?;
Ok(())
}Sourcepub fn add_source_str(&mut self, source: &str) -> Result<&mut Self, Error>
pub fn add_source_str(&mut self, source: &str) -> Result<&mut Self, Error>
Parse Rust source from a string and extract every type with a marker derive.
Source§impl CodeGenerator
impl CodeGenerator
Sourcepub fn set_header(&mut self, header: impl Into<String>) -> &mut Self
pub fn set_header(&mut self, header: impl Into<String>) -> &mut Self
Replace the header comment of the generated file.
Sourcepub fn set_direction(&mut self, direction: Direction) -> &mut Self
pub fn set_direction(&mut self, direction: Direction) -> &mut Self
Emit unidirectional bindings: Direction::Decode rewrites every rkyv-js import specifier
to its decode counterpart (rkyv-js becomes rkyv-js/decode, rkyv-js/lib/X becomes
rkyv-js/lib/X.decode), Direction::Encode symmetrically.
Factory names and type exports are unchanged;
imports of user modules registered via register_external are not rewritten.
Sourcepub fn set_jit(&mut self, enabled: bool) -> &mut Self
pub fn set_jit(&mut self, enabled: bool) -> &mut Self
Wrap every exported codec in the direction-matched JIT compile function: compileCodec from rkyv-js/jit for Direction::Full,
compileDecoder from rkyv-js/jit.decode resp. compileEncoder from rkyv-js/jit.encode for unidirectional bindings.
Each type is emitted as a non-exported interpreter codec (const {Name}$ = ...)
plus a compiled export (export const {Name} = compileCodec({Name}$);),
and cross-references between generated types resolve to the $ codecs:
a compiled codec is opaque to the JIT, so compiling each export over the
raw graph is what lets nested types inline instead of degrading to
per-element dispatch calls. The compiled exports stay drop-in
(encode/decode/access/… and r.Infer are unchanged),
and fall back to the interpreter codec where new Function is blocked (CSP).
Every export compiles eagerly at module load.
Defaults to false.
Sourcepub fn set_field_casing(&mut self, casing: Casing) -> &mut Self
pub fn set_field_casing(&mut self, casing: Casing) -> &mut Self
Rewrite the casing of emitted struct field names — including the fields
of enum struct variants — so the decoded objects read as idiomatic
JavaScript: Casing::Camel turns Rust’s created_at into createdAt.
rkyv lays a struct out positionally, so the keys of the emitted
r.struct({ ... }) are labels only. Renaming them changes the shape of
the decoded object and the inferred r.Infer type, and does not move a
single wire byte: bindings generated with and without this option stay
interchangeable on the same buffer.
Names that collide after conversion (foo_bar and fooBar both
becoming fooBar) are reported as DiagnosticKind::NameCollision
rather than emitted as a duplicate object key.
Defaults to Casing::Preserve.
use rkyv_js_codegen::{Casing, CodeGenerator, codec};
let mut generator = CodeGenerator::new();
generator.set_field_casing(Casing::Camel);
generator.add_struct("Event", [("created_at", codec::u64())]);
assert!(generator.generate()?.contains("createdAt: r.u64,"));Sourcepub fn set_variant_casing(&mut self, casing: Casing) -> &mut Self
pub fn set_variant_casing(&mut self, casing: Casing) -> &mut Self
Rewrite the casing of emitted enum variant names — the keys of
r.taggedEnum({ ... }), which surface as the tag of every decoded
value.
Rust variants are already PascalCase, which is the conventional
spelling for a discriminated-union tag in TypeScript, so this is
separate from set_field_casing and defaults
to Casing::Preserve.
The discriminant on the wire is the variant’s index, not its name, so
this is a relabelling just like set_field_casing.
Sourcepub fn allow_typescript_syntax(&mut self, enabled: bool) -> &mut Self
pub fn allow_typescript_syntax(&mut self, enabled: bool) -> &mut Self
When false, export type ... = r.Infer<...> lines are dropped so the output is valid plain JavaScript.
Defaults to true.
Sourcepub fn on_unknown_type(&mut self, mode: OnUnknown) -> &mut Self
pub fn on_unknown_type(&mut self, mode: OnUnknown) -> &mut Self
Configure how unmappable field types are handled.
Defaults to OnUnknown::Error.
Sourcepub fn add_marker_path(&mut self, path: impl Into<String>) -> &mut Self
pub fn add_marker_path(&mut self, path: impl Into<String>) -> &mut Self
Register an additional derive path that marks types for extraction,
alongside the default rkyv::Archive.
Sourcepub fn register_external(
&mut self,
path: impl Into<String>,
external: ExternalType,
) -> &mut Self
pub fn register_external( &mut self, path: impl Into<String>, external: ExternalType, ) -> &mut Self
Register (or replace) an external type mapping for a fully-qualified Rust path.
use rkyv_js_codegen::{CodeGenerator, CodecExpr, ExternalType};
let mut generator = CodeGenerator::new();
generator.register_external(
"my_crate::MyVec",
ExternalType::generic1(|t| {
CodecExpr::call(CodecExpr::import_from("my-pkg/codecs", "myVec"), [t])
}),
);Sourcepub fn register_with(
&mut self,
path: impl Into<String>,
wrapper: WithWrapper,
) -> &mut Self
pub fn register_with( &mut self, path: impl Into<String>, wrapper: WithWrapper, ) -> &mut Self
Register (or replace) a #[rkyv(with = ...)] wrapper handler.
Sourcepub fn unregister_external(&mut self, path: &str) -> &mut Self
pub fn unregister_external(&mut self, path: &str) -> &mut Self
Remove an external type mapping (e.g. to disable a builtin).
Sourcepub fn add_struct(
&mut self,
name: impl Into<String>,
fields: impl IntoIterator<Item = (impl Into<String>, CodecExpr)>,
) -> &mut Self
pub fn add_struct( &mut self, name: impl Into<String>, fields: impl IntoIterator<Item = (impl Into<String>, CodecExpr)>, ) -> &mut Self
Add a struct definition.
Sourcepub fn add_enum(
&mut self,
name: impl Into<String>,
variants: impl IntoIterator<Item = EnumVariant>,
) -> &mut Self
pub fn add_enum( &mut self, name: impl Into<String>, variants: impl IntoIterator<Item = EnumVariant>, ) -> &mut Self
Add an enum definition.
Sourcepub fn add_alias(
&mut self,
name: impl Into<String>,
target: CodecExpr,
) -> &mut Self
pub fn add_alias( &mut self, name: impl Into<String>, target: CodecExpr, ) -> &mut Self
Add a type alias: export const Archived{name} = <expr>;.
Sourcepub fn set_archived_name(
&mut self,
type_name: impl Into<String>,
archived_name: impl Into<String>,
) -> &mut Self
pub fn set_archived_name( &mut self, type_name: impl Into<String>, archived_name: impl Into<String>, ) -> &mut Self
Override the archived (exported) name of a type, corresponding to #[rkyv(archived = Name)].
Order-independent: the target type may be added before or after this call.
A target that never materializes is reported as DiagnosticKind::UnknownRenameTarget at generate time.
Sourcepub fn archived_name_of(&self, type_name: &str) -> Option<String>
pub fn archived_name_of(&self, type_name: &str) -> Option<String>
The archived (exported) name a type will be emitted under, or None
if no type with that name has been added.
Sourcepub fn set_format(
&mut self,
endian: &str,
pointer_width: u32,
aligned: bool,
) -> &mut Self
pub fn set_format( &mut self, endian: &str, pointer_width: u32, aligned: bool, ) -> &mut Self
Configure the rkyv wire format of the generated bindings.
When the format differs from the default (little/32/aligned),
the output declares const FORMAT = r.format({ ... }) with the non-default keys
and wraps every exported codec in r.withFormat(<expr>, FORMAT).