Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ A commandline utility for converting CDDL to various formats.
1. Clone this repo and `cd` into it.
2. `cargo run -- path/to/file.cddl`

The default output format is TypeScript. Zod schemas can be generated for either
major version without changing their runtime schema expressions:

```sh
cargo run -- path/to/file.cddl --format zod # Zod v3 type annotations
cargo run -- path/to/file.cddl --format zod4 # Zod v4 type annotations
```

## Tips

### Formatting output
Expand All @@ -26,4 +34,4 @@ cargo run -- path/to/file.cddl | prettier --stdin-filepath=$outfile > $outfile

## Limitations

1. Only [`TypeScript`](https://www.typescriptlang.org/) and [`Zod v4`](https://zod.dev/) is supported at the moment.
1. Only [`TypeScript`](https://www.typescriptlang.org/) and [`Zod`](https://zod.dev/) (v3 and v4) are supported at the moment.
3 changes: 3 additions & 0 deletions examples/zod4_compat.cddl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Choice = text / int

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All tests in tests/typescript.rs and tests/zod.rs use insta::assert_snapshot! against the shared CDDL fixtures in examples/.

Adding a separate examples/zod4_compat.cddl with manual assert!(stdout.contains(...)) checks has two drawbacks:

  1. Choice = text / int only exercises 1 of the 6 z.ZodUnion code paths (visit_type), leaving the other 5 (visit_array, bounded array occurrences, optional TypeGroupname, optional InlineGroup, and visit_group) untested for zod4.
  2. Every other file in examples/ is snapshot-tested across both tests/typescript.rs and tests/zod.rs.

Could we instead add tests/zod4.rs (mirroring tests/zod.rs with insta::assert_snapshot! over the existing examples/ fixtures) and drop examples/zod4_compat.cddl?

Mode = "decline" / "dedicated-worker" / "-0"
Events = [+ text]
64 changes: 52 additions & 12 deletions src/engines/zod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ struct PostambleOptions {
print_flatten: bool,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Version {
V3,
V4,
}

Comment on lines +49 to +54

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Rather than keeping enum Version private and adding a dedicated with_writers_zod4 method, consider making pub enum Version { V3, V4 } (line 50) and pub fn with_writers_for_version(stdout: Stdout, stderr: Stderr, version: Version) (line 95) public (with with_writers defaulting to Version::V3). That keeps the Engine API extensible without adding a new constructor per version.

pub struct Engine<Stdout, Stderr>
where
Stdout: Write,
Expand All @@ -54,6 +60,7 @@ where
nested_group_choices: Vec<GroupChoiceContext>,
nested_type1: Vec<Type1Context>,
is_type_mode: bool,
version: Version,
cyclic_rules: std::collections::HashSet<String>,
#[allow(dead_code)]
postamble_options: PostambleOptions,
Expand All @@ -78,10 +85,23 @@ fn calculate_occurrence(occur: &Option<cddl::ast::Occurrence<'_>>) -> (usize, us

impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine<Stdout, Stderr> {
pub fn with_writers(stdout: Stdout, stderr: Stderr) -> Engine<Stdout, Stderr> {
Self::with_writers_for_version(stdout, stderr, Version::V3)
}

pub fn with_writers_zod4(stdout: Stdout, stderr: Stderr) -> Engine<Stdout, Stderr> {
Self::with_writers_for_version(stdout, stderr, Version::V4)
}

fn with_writers_for_version(
stdout: Stdout,
stderr: Stderr,
version: Version,
) -> Engine<Stdout, Stderr> {
Engine {
nested_group_choices: Vec::new(),
nested_type1: Vec::new(),
is_type_mode: false,
version,
cyclic_rules: std::collections::HashSet::new(),
postamble_options: PostambleOptions {
#[cfg(feature = "vector_groups")]
Expand All @@ -104,6 +124,13 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine<Stdout, Stderr> {
unimplemented!();
}
}

fn print_union_type_start(&mut self) {
match self.version {
Version::V3 => write!(self.stdout, "z.ZodUnion<["),
Version::V4 => write!(self.stdout, "z.ZodUnion<readonly ["),
};
}
fn visit_maybe_enum_type(&mut self, t: &'b cddl::ast::Type<'a>) -> bool {
// Special case for string enums
if t.type_choices.len() > 1
Expand All @@ -113,13 +140,26 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine<Stdout, Stderr> {
.all(|type2| matches!(type2, cddl::ast::Type2::TextValue { .. }))
{
if self.is_type_mode {
write!(self.stdout, "z.ZodEnum<[");
for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) {
if let cddl::ast::Type2::TextValue { value, .. } = type2 {
write!(self.stdout, "\"{}\",", value);
match self.version {
Version::V3 => {
write!(self.stdout, "z.ZodEnum<[");
for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) {
if let cddl::ast::Type2::TextValue { value, .. } = type2 {
write!(self.stdout, "\"{}\",", value);
}
}
write!(self.stdout, "]>");
}
Version::V4 => {
write!(self.stdout, "z.ZodEnum<{{");
for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) {
if let cddl::ast::Type2::TextValue { value, .. } = type2 {
write!(self.stdout, "\"{}\":\"{}\";", value, value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
write!(self.stdout, "\"{}\":\"{}\";", value, value);
write!(self.stdout, "\"{}\":\"{}\",", value, value);

Nit: Use , rather than ; to stay consistent with z.ZodObject<{...}> member separators elsewhere in src/engines/zod.rs (and with the original output in #90).

}
}
write!(self.stdout, "}}>");
}
}
write!(self.stdout, "]>");
} else {
write!(self.stdout, "z.enum([");
for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) {
Expand All @@ -137,7 +177,7 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine<Stdout, Stderr> {
fn visit_array(&mut self, g: &'b cddl::ast::Group<'a>) -> cddl::visitor::Result<Error> {
if g.group_choices.len() != 1 {
if self.is_type_mode {
write!(self.stdout, "z.ZodUnion<[");
self.print_union_type_start();
} else {
write!(self.stdout, "z.union([");
}
Expand Down Expand Up @@ -369,7 +409,7 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine<Stdout, Stderr> {
}
if upper < MAX_ARRAYS {
if self.is_type_mode {
write!(self.stdout, "z.ZodUnion<[");
self.print_union_type_start();
for bound in lower..upper + 1 {
if bound != 0 {
write!(self.stdout, ",");
Expand Down Expand Up @@ -404,7 +444,7 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine<Stdout, Stderr> {
} else if self.is_type_mode {
write!(self.stdout, "z.ZodArray<");
self.visit_type(&entry.entry_type)?;
if lower == 1 {
if lower == 1 && self.version == Version::V3 {
write!(self.stdout, ", \"atleastone\"");
}
write!(self.stdout, ">");
Expand Down Expand Up @@ -597,7 +637,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine
}
if t.type_choices.len() != 1 {
if self.is_type_mode {
write!(self.stdout, "z.ZodUnion<[");
self.print_union_type_start();
} else {
write!(self.stdout, "z.union([");
}
Expand Down Expand Up @@ -688,7 +728,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine
self.print_group_joiner();
if matches!(calculate_occurrence(&ge.occur), (0, max) if max > 0) {
if self.is_type_mode {
write!(self.stdout, "z.ZodUnion<[");
self.print_union_type_start();
self.visit_type_groupname_entry(ge)?;
write!(self.stdout, ",z.ZodObject<{{}}>]>");
} else {
Expand All @@ -704,7 +744,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine
self.print_group_joiner();
if matches!(calculate_occurrence(&occur), (0, max) if max > 0) {
if self.is_type_mode {
write!(self.stdout, "z.ZodUnion<[");
self.print_union_type_start();
self.visit_group(group)?;
write!(self.stdout, ",z.ZodObject<{{}}>]>");
} else {
Expand Down Expand Up @@ -755,7 +795,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine
fn visit_group(&mut self, g: &'b cddl::ast::Group<'a>) -> cddl::visitor::Result<Error> {
if g.group_choices.len() != 1 {
if self.is_type_mode {
write!(self.stdout, "z.ZodUnion<[");
self.print_union_type_start();
} else {
write!(self.stdout, "z.union([");
}
Expand Down
10 changes: 10 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use std::path::PathBuf;
enum EngineType {
TypeScript,
Zod,
Zod4,
}

/// Simple program to greet a person
Expand Down Expand Up @@ -56,6 +57,15 @@ fn main() -> Result<()> {
engine.visit_cddl(&cddl)?;
engine.print_postamble();
}
EngineType::Zod4 => {
let mut engine = cddlconv::engines::zod::Engine::with_writers_zod4(
std::io::stdout(),
std::io::stderr(),
);
engine.print_preamble();
engine.visit_cddl(&cddl)?;
engine.print_postamble();
}
};

Ok(())
Expand Down
42 changes: 42 additions & 0 deletions tests/zod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,45 @@ test!(
"examples/array_occurences.cddl"
);
test!(it_works_with_enums, "examples/enums.cddl");

#[test]
fn zod4_uses_v4_type_annotations() {
let input = std::fs::read_to_string("examples/zod4_compat.cddl").unwrap();
let cddl = cddl::parser::cddl_from_str(&input, true).unwrap();
let stdout = BufWriter::new(Vec::new());
let stderr = BufWriter::new(Vec::new());
let mut engine = cddlconv::engines::zod::Engine::with_writers_zod4(stdout, stderr);

engine.visit_cddl(&cddl).unwrap();
engine.print_postamble();

let (stdout, stderr) = engine.into_writers();
let stdout = String::from_utf8(stdout.into_inner().unwrap()).unwrap();
let stderr = String::from_utf8(stderr.into_inner().unwrap()).unwrap();

assert!(stderr.is_empty());
assert!(stdout.contains("z.ZodUnion<readonly [z.ZodString,z.ZodNumber]>"));
assert!(stdout.contains(
r#"z.ZodEnum<{"decline":"decline";"dedicated-worker":"dedicated-worker";"-0":"-0";}>"#
));
assert!(stdout.contains("z.ZodArray<z.ZodString>"));
assert!(!stdout.contains(r#""atleastone""#));
}

#[test]
fn default_zod_output_remains_v3_compatible() {
let input = std::fs::read_to_string("examples/zod4_compat.cddl").unwrap();
let cddl = cddl::parser::cddl_from_str(&input, true).unwrap();
let stdout = BufWriter::new(Vec::new());
let stderr = BufWriter::new(Vec::new());
let mut engine = cddlconv::engines::zod::Engine::with_writers(stdout, stderr);

engine.visit_cddl(&cddl).unwrap();

let (stdout, _) = engine.into_writers();
let stdout = String::from_utf8(stdout.into_inner().unwrap()).unwrap();

assert!(stdout.contains("z.ZodUnion<[z.ZodString,z.ZodNumber]>"));
assert!(stdout.contains(r#"z.ZodEnum<["decline","dedicated-worker","-0",]>"#));
assert!(stdout.contains(r#"z.ZodArray<z.ZodString, "atleastone">"#));
}
Loading