Skip to content

Commit

Permalink
Fix TypeScript codegen
Browse files Browse the repository at this point in the history
  • Loading branch information
aumetra committed Nov 27, 2024
1 parent 126b2b7 commit dcbc887
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 32 deletions.
2 changes: 1 addition & 1 deletion packages/cw-schema-codegen/src/typescript/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn expand_node_name<'a>(
cw_schema::NodeType::Double => "z.number()".into(),
cw_schema::NodeType::Boolean => "z.boolean()".into(),
cw_schema::NodeType::String => "z.string()".into(),
cw_schema::NodeType::Integer { .. } => "z.string()".into(),
cw_schema::NodeType::Integer { .. } => "z.string().or(z.number())".into(),
cw_schema::NodeType::Binary => "z.instanceof(Uint8Array)".into(),
cw_schema::NodeType::Optional { inner } => {
let inner = &schema.definitions[inner];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const {{ name }}Schema = z.union([

{% match variant.ty %}
{% when TypeTemplate::Unit %}
z.object({ "{{ variant.name }}": z.void() }),
z.object({ "{{ variant.name }}": z.null() }).or(z.literal("{{ variant.name }}")),
{% when TypeTemplate::Tuple with (types) %}
z.object({ "{{ variant.name }}": z.tuple([{{ types|join(", ") }}]) }),
{% when TypeTemplate::Named with { fields } %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { z } from 'zod';
const {{ name }}Schema =
{% match ty %}
{% when TypeTemplate::Unit %}
z.void()
z.null()
{% when TypeTemplate::Tuple with (types) %}
z.tuple([{{ types|join(", ") }}])
{% when TypeTemplate::Named with { fields } %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { z } from 'zod';

const UwuSchema =

z.tuple([z.string(), z.string()])
z.tuple([z.string(), z.string().or(z.number())])

;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { z } from 'zod';

const ÒwóSchema =

z.void()
z.null()

;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ const HeheheSchema = z.union([
*/


z.object({ "A": z.void() }),
z.object({ "A": z.null() }).or(z.literal("A")),


/**
*/


z.object({ "B": z.tuple([z.string()]) }),
z.object({ "B": z.tuple([z.string().or(z.number())]) }),


/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const OwoSchema =
*/

field_1: z.string(),
field_1: z.string().or(z.number()),

/**
Expand Down
3 changes: 3 additions & 0 deletions packages/cw-schema-codegen/tests/ts-e2e/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ const typeName = process.argv[2];
const deserialized = JSON.parse(stdinString);

let validated = gen[typeName].parse(deserialized);
console.error(stdinString);
console.error(deserialized);
console.error(validated);

const outputStream = process.stdout;
outputStream.write(JSON.stringify(validated));
56 changes: 32 additions & 24 deletions packages/cw-schema-codegen/tests/typescript.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use arbitrary::Arbitrary;
use core::str;
use cw_schema::Schemaifier;
use serde::{Deserialize, Serialize};
use std::{
Expand All @@ -19,15 +20,8 @@ struct Uwu(String, u32);
#[derive(Arbitrary, Schemaifier, Debug, Deserialize, PartialEq, Serialize)]
struct Òwó;

mod empty {
#![allow(unreachable_code)]
use super::*;

#[derive(Arbitrary, Schemaifier, Debug, Deserialize, PartialEq, Serialize)]
pub enum Empty {}
}

use self::empty::Empty;
#[derive(Schemaifier, Debug, Deserialize, PartialEq, Serialize)]
pub enum Empty {}

#[derive(Arbitrary, Schemaifier, Debug, Deserialize, PartialEq, Serialize)]
enum Hehehe {
Expand Down Expand Up @@ -84,8 +78,7 @@ fn codegen_snap() {
.iter()
.map(|node| {
let mut buf = Vec::new();
cw_schema_codegen::typescript::process_node(&mut buf, &schema, node, true)
.unwrap();
cw_schema_codegen::typescript::process_node(&mut buf, &schema, node, true).unwrap();
String::from_utf8(buf).unwrap()
})
.collect::<String>();
Expand Down Expand Up @@ -124,18 +117,30 @@ fn assert_validity() {
wrap::<Òwó>,
type_name::<Òwó>(),
),
(
// `Empty` is a non-constructable type
/*(
cw_schema::schema_of::<Empty>(),
wrap::<Empty>,
type_name::<Empty>(),
),
),*/
(
cw_schema::schema_of::<Hehehe>(),
wrap::<Hehehe>,
type_name::<Hehehe>(),
),
];

let e2e_dir = format!("{}/tests/ts-e2e", env!("CARGO_MANIFEST_DIR"));
let gen_file_path = format!("{}/src/gen.ts", e2e_dir);

// make sure the dependencies are installed
let install_status = Command::new("npm")
.arg("i")
.current_dir(&e2e_dir)
.status()
.unwrap();
assert!(install_status.success());

let random_data: [u8; 255] = rand::random();
let mut unstructured = arbitrary::Unstructured::new(&random_data);
for (schema, arbitrary_gen, type_name) in schemas {
Expand All @@ -148,26 +153,20 @@ fn assert_validity() {
.iter()
.map(|node| {
let mut buf = Vec::new();
cw_schema_codegen::typescript::process_node(&mut buf, schema, node, true)
.unwrap();
cw_schema_codegen::typescript::process_node(&mut buf, schema, node, true).unwrap();
String::from_utf8(buf).unwrap()
})
.collect::<String>();

let e2e_dir = format!("{}/tests/ts-e2e", env!("CARGO_MANIFEST_DIR"));
let gen_file_path = format!("{}/src/gen.ts", e2e_dir);
let mut gen_file = File::create(gen_file_path).unwrap();
let mut gen_file = File::create(&gen_file_path).unwrap();
gen_file.write_all(output.as_bytes()).unwrap();

let data = arbitrary_gen(&mut unstructured);
let serialized = serde_json::to_string(&data).unwrap();

let install_status = Command::new("npm").arg("i").current_dir(&e2e_dir).status().unwrap();
assert!(install_status.success());

let mut child = Command::new("npm")
.args(["test", type_name])
.current_dir(e2e_dir)
.current_dir(&e2e_dir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
Expand All @@ -178,8 +177,17 @@ fn assert_validity() {
stdin.write_all(serialized.as_bytes()).unwrap();
}

let output = child.wait_with_output().unwrap();
let deserialized: Combined = serde_json::from_slice(&output.stdout).unwrap();
let proc_output = child.wait_with_output().unwrap();
assert!(
proc_output.status.success(),
"failed with object: {data:#?}; json: {serialized}; schema: {output}"
);

let stdout = str::from_utf8(&proc_output.stdout).unwrap();
let stdout = stdout.lines().last().unwrap();
let deserialized: Combined = serde_json::from_str(stdout).unwrap_or_else(|err| {
panic!("{err:?}; input: {serialized}, output: {stdout}");
});

assert_eq!(data, deserialized);
}
Expand Down

0 comments on commit dcbc887

Please sign in to comment.