From adfbb27e56dd14d8b41d91c75d32a158493bde25 Mon Sep 17 00:00:00 2001 From: Eric Rodrigues Pires Date: Fri, 31 Oct 2025 00:07:04 -0300 Subject: [PATCH] Remake @duper-js/wasm; prepare for releases --- ...-duper-js-wasm.yaml => duper-js-wasm.yaml} | 8 +- ...ld-duper-python.yaml => duper-python.yaml} | 0 .../{build-website.yaml => website.yaml} | 8 +- .github/workflows/zizmor.yaml | 2 +- Cargo.lock | 10 +- axum_duper/Cargo.toml | 4 +- axum_duper/src/lib.rs | 6 +- duper-js-wasm/Cargo.toml | 2 +- duper-js-wasm/examples/vite/index.html | 56 ++- duper-js-wasm/examples/vite/package-lock.json | 13 +- duper-js-wasm/examples/vite/package.json | 2 +- duper-js-wasm/package.json | 2 +- duper-js-wasm/src/de.rs | 176 +++------ duper-js-wasm/src/lib.rs | 23 +- duper-js-wasm/src/repr.rs | 368 ++++++++++++++++++ duper-js-wasm/src/ser.rs | 166 +++----- duper-python/Cargo.toml | 4 +- duper-vs-code/package.json | 2 +- duper/Cargo.toml | 2 +- duper_website/docs/guide-javascript.md | 57 ++- serde_duper/Cargo.toml | 4 +- 21 files changed, 614 insertions(+), 301 deletions(-) rename .github/workflows/{build-duper-js-wasm.yaml => duper-js-wasm.yaml} (88%) rename .github/workflows/{build-duper-python.yaml => duper-python.yaml} (100%) rename .github/workflows/{build-website.yaml => website.yaml} (91%) create mode 100644 duper-js-wasm/src/repr.rs diff --git a/.github/workflows/build-duper-js-wasm.yaml b/.github/workflows/duper-js-wasm.yaml similarity index 88% rename from .github/workflows/build-duper-js-wasm.yaml rename to .github/workflows/duper-js-wasm.yaml index 9133f41..391c2fc 100644 --- a/.github/workflows/build-duper-js-wasm.yaml +++ b/.github/workflows/duper-js-wasm.yaml @@ -12,7 +12,7 @@ permissions: id-token: write env: - RUST_MSRV: "1.88.0" + RUST_VERSION: "1.91.0" NODE_VERSION: "20" BINARYEN_VERSION: "124" @@ -29,10 +29,10 @@ jobs: uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 with: node-version: ${{ env.NODE_VERSION }} - - name: Fetch MSRV and install target + - name: Fetch Rust and install target run: | - rustup toolchain install ${RUST_MSRV}-x86_64-unknown-linux-gnu - rustup override set ${RUST_MSRV}-x86_64-unknown-linux-gnu + rustup toolchain install ${RUST_VERSION}-x86_64-unknown-linux-gnu + rustup override set ${RUST_VERSION}-x86_64-unknown-linux-gnu rustup target add wasm32-unknown-unknown - name: Cache Rust dependencies uses: Swatinem/rust-cache@f13886b937689c021905a6b90929199931d60db1 # v2.8.1 diff --git a/.github/workflows/build-duper-python.yaml b/.github/workflows/duper-python.yaml similarity index 100% rename from .github/workflows/build-duper-python.yaml rename to .github/workflows/duper-python.yaml diff --git a/.github/workflows/build-website.yaml b/.github/workflows/website.yaml similarity index 91% rename from .github/workflows/build-website.yaml rename to .github/workflows/website.yaml index ea10f42..bce3ce9 100644 --- a/.github/workflows/build-website.yaml +++ b/.github/workflows/website.yaml @@ -14,7 +14,7 @@ concurrency: cancel-in-progress: false env: - RUST_MSRV: "1.88.0" + RUST_VERSION: "1.91.0" NODE_VERSION: "20" BINARYEN_VERSION: "124" @@ -31,10 +31,10 @@ jobs: uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 with: node-version: ${{ env.NODE_VERSION }} - - name: Fetch MSRV and install target + - name: Fetch Rust and install target run: | - rustup toolchain install ${RUST_MSRV}-x86_64-unknown-linux-gnu - rustup override set ${RUST_MSRV}-x86_64-unknown-linux-gnu + rustup toolchain install ${RUST_VERSION}-x86_64-unknown-linux-gnu + rustup override set ${RUST_VERSION}-x86_64-unknown-linux-gnu rustup target add wasm32-unknown-unknown - name: Cache Rust dependencies uses: Swatinem/rust-cache@f13886b937689c021905a6b90929199931d60db1 # v2.8.1 diff --git a/.github/workflows/zizmor.yaml b/.github/workflows/zizmor.yaml index c9adde5..b20177a 100644 --- a/.github/workflows/zizmor.yaml +++ b/.github/workflows/zizmor.yaml @@ -1,4 +1,4 @@ -name: GitHub Actions Security Analysis with zizmor +name: Analyze GitHub Actions with zizmor on: push: diff --git a/Cargo.lock b/Cargo.lock index 9a8ecd8..0eccb89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -114,12 +114,12 @@ dependencies = [ [[package]] name = "axum_duper" -version = "0.2.2" +version = "0.3.0" dependencies = [ "axum", + "duper", "serde", "serde_core", - "serde_duper", "uuid", ] @@ -291,7 +291,7 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "duper" -version = "0.2.2" +version = "0.3.0" dependencies = [ "ariadne", "chumsky", @@ -314,7 +314,7 @@ dependencies = [ [[package]] name = "duper-python" -version = "0.2.2" +version = "0.3.0" dependencies = [ "duper", "pyo3", @@ -1000,7 +1000,7 @@ dependencies = [ [[package]] name = "serde_duper" -version = "0.2.2" +version = "0.3.0" dependencies = [ "bytes", "chrono", diff --git a/axum_duper/Cargo.toml b/axum_duper/Cargo.toml index e7e4add..1a991b6 100644 --- a/axum_duper/Cargo.toml +++ b/axum_duper/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "axum_duper" description = "Axum extractor/response for Duper." -version = "0.2.2" +version = "0.3.0" edition = "2024" rust-version = "1.88" license = "MIT" @@ -15,7 +15,7 @@ keywords = ["duper", "serde", "axum"] [dependencies] axum = { version = "0.8", default-features = false } serde_core = "1" -serde_duper = { path = "../serde_duper", version = "0.2.2" } +duper = { path = "../duper", version = "0.3.0", features = ["serde"] } [dev-dependencies] serde = { version = "1.0.228", features = ["derive"] } diff --git a/axum_duper/src/lib.rs b/axum_duper/src/lib.rs index 248bbfe..abd8641 100644 --- a/axum_duper/src/lib.rs +++ b/axum_duper/src/lib.rs @@ -15,8 +15,8 @@ use axum::{ http::{HeaderValue, StatusCode, header::CONTENT_TYPE}, response::{IntoResponse, Response}, }; +use duper::serde::error::ErrorKind; use serde_core::{Serialize, de::DeserializeOwned}; -use serde_duper::ErrorKind; pub static DUPER_CONTENT_TYPE: &str = "application/duper"; pub static DUPER_ALT_CONTENT_TYPE: &str = "application/x-duper"; @@ -143,7 +143,7 @@ where /// extracting a `Request` into `String`, then optionally constructing a /// `Duper`. pub fn from_string(string: &str) -> Result { - match serde_duper::from_string(string) { + match duper::serde::de::from_string(string) { Ok(value) => Ok(Self(value)), Err(err) => match err.inner.kind { ErrorKind::ParseError(_) => Err(DuperRejection::DuperSyntaxError), @@ -209,7 +209,7 @@ where T: Serialize, { fn into_response(self) -> Response { - serde_duper::to_string(&self.0) + duper::serde::ser::to_string(&self.0) .map(|string| { ( [(CONTENT_TYPE, HeaderValue::from_static(DUPER_CONTENT_TYPE))], diff --git a/duper-js-wasm/Cargo.toml b/duper-js-wasm/Cargo.toml index 16dae5b..a800f8a 100644 --- a/duper-js-wasm/Cargo.toml +++ b/duper-js-wasm/Cargo.toml @@ -16,6 +16,6 @@ publish = false crate-type = ["cdylib"] [dependencies] -duper = { path = "../duper", version = "0.2.2" } +duper = { path = "../duper" } js-sys = "0.3.81" wasm-bindgen = "0.2.104" diff --git a/duper-js-wasm/examples/vite/index.html b/duper-js-wasm/examples/vite/index.html index ee7190f..96e9fe5 100644 --- a/duper-js-wasm/examples/vite/index.html +++ b/duper-js-wasm/examples/vite/index.html @@ -2,18 +2,58 @@ - @duper-js/wasm + @duper-js/wasm example diff --git a/duper-js-wasm/examples/vite/package-lock.json b/duper-js-wasm/examples/vite/package-lock.json index 11bdca0..25e0de8 100644 --- a/duper-js-wasm/examples/vite/package-lock.json +++ b/duper-js-wasm/examples/vite/package-lock.json @@ -5,7 +5,7 @@ "packages": { "": { "dependencies": { - "@duper-js/wasm": "^0.1.1" + "@duper-js/wasm": "../.." }, "devDependencies": { "vite": "^7.1.12", @@ -13,12 +13,15 @@ "vite-plugin-wasm": "^3.5.0" } }, - "node_modules/@duper-js/wasm": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/@duper-js/wasm/-/wasm-0.1.1.tgz", - "integrity": "sha512-Xzpo2nQ1/CqZ9WtGEEntn+TXO40vymt5Tw1XlN/oQP3XzVRAeWO3a7jVZPl6QJaQQ2QVaBYVV0LJWaV67iVcUQ==", + "../..": { + "name": "@duper-js/wasm", + "version": "0.2.0", "license": "MIT" }, + "node_modules/@duper-js/wasm": { + "resolved": "../..", + "link": true + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.11", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz", diff --git a/duper-js-wasm/examples/vite/package.json b/duper-js-wasm/examples/vite/package.json index dba9193..142b38e 100644 --- a/duper-js-wasm/examples/vite/package.json +++ b/duper-js-wasm/examples/vite/package.json @@ -3,7 +3,7 @@ "dev": "vite" }, "dependencies": { - "@duper-js/wasm": "^0.1.1" + "@duper-js/wasm": "../.." }, "devDependencies": { "vite": "^7.1.12", diff --git a/duper-js-wasm/package.json b/duper-js-wasm/package.json index 57f6c6d..8804c0d 100644 --- a/duper-js-wasm/package.json +++ b/duper-js-wasm/package.json @@ -1,6 +1,6 @@ { "name": "@duper-js/wasm", - "version": "0.1.3", + "version": "0.2.0", "description": "The format that's super!", "keywords": [ "duper", diff --git a/duper-js-wasm/src/de.rs b/duper-js-wasm/src/de.rs index 236e36e..1a2c269 100644 --- a/duper-js-wasm/src/de.rs +++ b/duper-js-wasm/src/de.rs @@ -1,16 +1,14 @@ use duper::visitor::DuperVisitor; -use js_sys::{Array, Object, Reflect, Symbol}; +use js_sys::{Array, BigInt, Object, Reflect, Uint8Array}; use wasm_bindgen::prelude::*; -use crate::{SYMBOL_DUPER_IDENTIFIER, SYMBOL_DUPER_TYPE, SYMBOL_DUPER_VALUE}; +use crate::repr::{JsDuperValue, JsDuperValueInner}; #[derive(Clone)] -pub(crate) struct Visitor { - pub(crate) json_safe: bool, -} +pub(crate) struct Visitor; impl DuperVisitor for Visitor { - type Value = Result; + type Value = Result; fn visit_object<'a>( &mut self, @@ -21,27 +19,20 @@ impl DuperVisitor for Visitor { for (key, value) in object.iter() { let value_result = value.accept(self)?; - Reflect::set(&js_object, &JsValue::from(key.as_ref()), &value_result).map_err(|e| { - JsError::new(&format!("Failed to set property {}: {:?}", key.as_ref(), e)) - })?; - } - - // Mark as object - let type_symbol = Symbol::for_(SYMBOL_DUPER_TYPE); - Reflect::set(&js_object, &type_symbol, &JsValue::from_str("object")) - .map_err(|e| JsError::new(&format!("Failed to set object symbol: {:?}", e)))?; - - if let Some(identifier) = identifier { - let duper_symbol = Symbol::for_(SYMBOL_DUPER_IDENTIFIER); Reflect::set( &js_object, - &duper_symbol, - &JsValue::from_str(identifier.as_ref()), + &JsValue::from(key.as_ref()), + &value_result.into(), ) - .map_err(|e| JsError::new(&format!("Failed to set Duper identifier: {:?}", e)))?; + .map_err(|e| { + JsError::new(&format!("Failed to set property {}: {:?}", key.as_ref(), e)) + })?; } - Ok(js_object.into()) + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Object(js_object.into()), + }) } fn visit_array<'a>( @@ -53,25 +44,13 @@ impl DuperVisitor for Visitor { for (index, value) in array.iter().enumerate() { let value_result = value.accept(self)?; - js_array.set(index as u32, value_result); + js_array.set(index as u32, value_result.into()); } - // Mark as array - let type_symbol = Symbol::for_(SYMBOL_DUPER_TYPE); - Reflect::set(&js_array, &type_symbol, &JsValue::from_str("array")) - .map_err(|e| JsError::new(&format!("Failed to set array symbol: {:?}", e)))?; - - if let Some(identifier) = identifier { - let duper_symbol = Symbol::for_(SYMBOL_DUPER_IDENTIFIER); - Reflect::set( - &js_array, - &duper_symbol, - &JsValue::from_str(identifier.as_ref()), - ) - .map_err(|e| JsError::new(&format!("Failed to set Duper identifier: {:?}", e)))?; - } - - Ok(js_array.into()) + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Array(js_array.into()), + }) } fn visit_tuple<'a>( @@ -83,25 +62,13 @@ impl DuperVisitor for Visitor { for (index, value) in tuple.iter().enumerate() { let value_result = value.accept(self)?; - js_array.set(index as u32, value_result); + js_array.set(index as u32, value_result.into()); } - // Mark as tuple - let type_symbol = Symbol::for_(SYMBOL_DUPER_TYPE); - Reflect::set(&js_array, &type_symbol, &JsValue::from_str("tuple")) - .map_err(|e| JsError::new(&format!("Failed to set tuple symbol: {:?}", e)))?; - - if let Some(identifier) = identifier { - let duper_symbol = Symbol::for_(SYMBOL_DUPER_IDENTIFIER); - Reflect::set( - &js_array, - &duper_symbol, - &JsValue::from_str(identifier.as_ref()), - ) - .map_err(|e| JsError::new(&format!("Failed to set Duper identifier: {:?}", e)))?; - } - - Ok(js_array.into()) + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Tuple(js_array.into()), + }) } fn visit_string<'a>( @@ -109,12 +76,10 @@ impl DuperVisitor for Visitor { identifier: Option<&duper::DuperIdentifier<'a>>, string: &duper::DuperString<'a>, ) -> Self::Value { - let value = JsValue::from_str(string.as_ref()); - if self.json_safe { - Ok(value) - } else { - attach_identifier(value, identifier, "string") - } + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::String(string.as_ref().into()), + }) } fn visit_bytes<'a>( @@ -122,13 +87,10 @@ impl DuperVisitor for Visitor { identifier: Option<&duper::DuperIdentifier<'a>>, bytes: &duper::DuperBytes<'a>, ) -> Self::Value { - if self.json_safe { - Ok(bytes.as_ref().to_vec().into()) - } else { - let uint8_array = js_sys::Uint8Array::from(bytes.as_ref()); - let value: JsValue = uint8_array.into(); - attach_identifier(value, identifier, "bytes") - } + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Bytes(Uint8Array::from(bytes.as_ref()).into()), + }) } fn visit_integer<'a>( @@ -136,13 +98,10 @@ impl DuperVisitor for Visitor { identifier: Option<&duper::DuperIdentifier<'a>>, integer: i64, ) -> Self::Value { - // TO-DO: Handle big integers - let value = JsValue::from_f64(integer as f64); - if self.json_safe { - Ok(value) - } else { - attach_identifier(value, identifier, "integer") - } + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Integer(BigInt::from(integer).into()), + }) } fn visit_float<'a>( @@ -150,12 +109,10 @@ impl DuperVisitor for Visitor { identifier: Option<&duper::DuperIdentifier<'a>>, float: f64, ) -> Self::Value { - let value = JsValue::from_f64(float); - if self.json_safe { - Ok(value) - } else { - attach_identifier(value, identifier, "float") - } + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Float(JsValue::from_f64(float)), + }) } fn visit_boolean<'a>( @@ -163,55 +120,16 @@ impl DuperVisitor for Visitor { identifier: Option<&duper::DuperIdentifier<'a>>, boolean: bool, ) -> Self::Value { - let value = JsValue::from_bool(boolean); - if self.json_safe { - Ok(value) - } else { - attach_identifier(value, identifier, "boolean") - } + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Boolean(JsValue::from_bool(boolean)), + }) } fn visit_null<'a>(&mut self, identifier: Option<&duper::DuperIdentifier<'a>>) -> Self::Value { - let value = JsValue::NULL; - if self.json_safe { - Ok(value) - } else { - attach_identifier(value, identifier, "null") - } - } -} - -fn attach_identifier( - value: JsValue, - identifier: Option<&duper::DuperIdentifier>, - typ: &'static str, -) -> Result { - if let Some(identifier) = identifier { - let boxed = Object::new(); - let value_key = Symbol::for_(SYMBOL_DUPER_VALUE); - let identifier_symbol = Symbol::for_(SYMBOL_DUPER_IDENTIFIER); - let type_symbol = Symbol::for_(SYMBOL_DUPER_TYPE); - - Reflect::set(&boxed, &value_key, &value) - .map_err(|e| JsError::new(&format!("Failed to set Duper value: {:?}", e)))?; - Reflect::set( - &boxed, - &identifier_symbol, - &JsValue::from_str(identifier.as_ref()), - ) - .map_err(|e| JsError::new(&format!("Failed to set Duper identifier symbol: {:?}", e)))?; - Reflect::set(&boxed, &type_symbol, &JsValue::from_str(typ)) - .map_err(|e| JsError::new(&format!("Failed to set Duper type: {:?}", e)))?; - - let to_json = js_sys::Function::new_with_args( - "", - &format!(r#"return this[Symbol.for("{SYMBOL_DUPER_VALUE}")];"#), - ); - Reflect::set(&boxed, &JsValue::from("toJSON"), &to_json) - .map_err(|e| JsError::new(&format!("Failed to set toJSON function: {:?}", e)))?; - - Ok(boxed.into()) - } else { - Ok(value) + Ok(JsDuperValue { + identifier: identifier.map(|identifier| identifier.static_clone()), + inner: JsDuperValueInner::Null, + }) } } diff --git a/duper-js-wasm/src/lib.rs b/duper-js-wasm/src/lib.rs index 779bb52..d08e995 100644 --- a/duper-js-wasm/src/lib.rs +++ b/duper-js-wasm/src/lib.rs @@ -5,12 +5,9 @@ use wasm_bindgen::prelude::*; use crate::{de::Visitor, ser::serialize_jsvalue}; mod de; +mod repr; mod ser; -pub(crate) static SYMBOL_DUPER_VALUE: &str = "$duper.value"; -pub(crate) static SYMBOL_DUPER_IDENTIFIER: &str = "$duper.identifier"; -pub(crate) static SYMBOL_DUPER_TYPE: &str = "$duper.type"; - struct StringifyOptions { indent: Option, strip_identifiers: bool, @@ -18,6 +15,11 @@ struct StringifyOptions { #[wasm_bindgen(typescript_custom_section)] const I_STRINGIFY_OPTIONS: &'static str = r#" +/** + * @property {string | number} [indent] - Whitespace string to use as indentation, or the number of + * spaces to use as indentation. + * @property {boolean} [stripIdentifiers] - Whether Duper identifiers should be removed from the stringified value. + */ interface IStringifyOptions { indent?: string | number; stripIdentifiers?: boolean; @@ -29,6 +31,7 @@ extern "C" { pub type IStringifyOptions; } +/// Stringifies the provided value into Duper, with the specified options. #[wasm_bindgen] pub fn stringify(value: &JsValue, options: Option) -> Result { let value: DuperValue = serialize_jsvalue(value) @@ -67,6 +70,7 @@ pub fn stringify(value: &JsValue, options: Option) -> Result< } } +/// Parses the provided Duper string into a DuperValue, or a JSON-safe alternative if specified. #[wasm_bindgen] pub fn parse( value: &str, @@ -74,7 +78,12 @@ pub fn parse( ) -> Result { let value = DuperParser::parse_duper_value(value) .map_err(|err| JsError::new(&DuperParser::prettify_error(value, &err, None)))?; - value.accept(&mut Visitor { - json_safe: json_safe.is_some_and(|json_safe| json_safe), - }) + let deserialized = value.accept(&mut Visitor)?; + if json_safe.is_some_and(|json_safe| json_safe) { + deserialized + .to_json() + .map_err(|err| JsError::new(&format!("failed to make JSON-safe: {err:?}"))) + } else { + Ok(deserialized.into()) + } } diff --git a/duper-js-wasm/src/repr.rs b/duper-js-wasm/src/repr.rs new file mode 100644 index 0000000..5e9c079 --- /dev/null +++ b/duper-js-wasm/src/repr.rs @@ -0,0 +1,368 @@ +use std::fmt::Display; + +use duper::{DuperIdentifier, DuperValue}; +use js_sys::{Array, BigInt, Boolean, Function, Object, Reflect, Uint8Array}; +use wasm_bindgen::{convert::TryFromJsValue, prelude::*}; + +use crate::ser::{ + serialize_array, serialize_boolean, serialize_bytes, serialize_float, serialize_integer, + serialize_null, serialize_object, serialize_string, serialize_tuple, +}; + +#[wasm_bindgen(typescript_custom_section)] +const DUPER_VALUE_TYPE: &'static str = r#" +/** + * Valid Duper types. + */ +type DuperValueType = "object" | "array" | "tuple" | "string" | "bytes" | "integer" | "float" | "boolean" | "null";"#; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "DuperValueType")] + pub type DuperValueType; +} + +pub(crate) enum JsDuperValueInner { + Object(JsValue), + Array(JsValue), + Tuple(JsValue), + String(JsValue), + Bytes(JsValue), + Integer(JsValue), + Float(JsValue), + Boolean(JsValue), + Null, +} + +impl JsDuperValueInner { + fn new(typ: Option, inner: JsValue) -> Result { + if let Some(typ) = typ { + match typ.as_str() { + "object" => { + let entries = Object::entries(&inner.dyn_into().map_err(|inner| { + JsError::new(&format!("expected Object, found {inner:?}")) + })?); + let new_object = Object::new(); + for tup in entries.into_iter() { + let tup: Array = tup.dyn_into().expect("expected key-value tuple"); + let key = tup.get(0); + if !key.is_string() { + return Err(JsError::new(&format!( + "invalid key for Object: expected string, found {key:?}" + ))); + } + let value = tup.get(1); + match JsDuperValue::try_from_js_value(value) { + Ok(value) => { + Reflect::set(&new_object, &key, &value.into()).map_err(|err| { + JsError::new(&format!( + "failed to set key {key:?} of Object: {err:?}" + )) + })? + } + Err(value) => { + return Err(JsError::new(&format!( + "invalid value with key {key:?} for Object: expected DuperValue, found {value:?}" + ))); + } + }; + } + Ok(JsDuperValueInner::Object(new_object.into())) + } + "array" => { + let array = inner.dyn_into::().map_err(|inner| { + JsError::new(&format!("expected Array, found {inner:?}")) + })?; + let new_array = Array::new_with_length(array.length()); + for (index, element) in array.into_iter().enumerate() { + match JsDuperValue::try_from_js_value(element) { + Ok(value) => new_array.set(index as u32, value.into()), + Err(element) => { + return Err(JsError::new(&format!( + "invalid element #{index} for Array: expected DuperValue, found {element:?}" + ))); + } + } + } + Ok(JsDuperValueInner::Array(new_array.into())) + } + "tuple" => { + let array = inner.dyn_into::().map_err(|inner| { + JsError::new(&format!("expected Array, found {inner:?}")) + })?; + let new_array = Array::new_with_length(array.length()); + for (index, element) in array.into_iter().enumerate() { + match JsDuperValue::try_from_js_value(element) { + Ok(value) => new_array.set(index as u32, value.into()), + Err(element) => { + return Err(JsError::new(&format!( + "invalid element #{index} for Array: expected DuperValue, found {element:?}" + ))); + } + } + } + Ok(JsDuperValueInner::Tuple(new_array.into())) + } + "string" => { + if inner.is_string() { + Ok(JsDuperValueInner::String(inner)) + } else { + Err(JsError::new(&format!("expected string, found {inner:?}"))) + } + } + "bytes" => { + if Uint8Array::is_type_of(&inner) { + Ok(JsDuperValueInner::Bytes(inner)) + } else if Array::is_array(&inner) { + let array: Array = inner.dyn_into().unwrap(); + let bytes = Uint8Array::new_with_length(array.length()); + for (index, element) in array.into_iter().enumerate() { + bytes.set(&element, index as u32); + } + Ok(JsDuperValueInner::Bytes(bytes.into())) + } else { + Err(JsError::new(&format!( + "expected Uint8Array or Array, found {inner:?}" + ))) + } + } + "integer" => { + if inner.is_bigint() { + Ok(JsDuperValueInner::Integer(inner)) + } else if inner.as_f64().is_some() { + Ok(JsDuperValueInner::Integer( + BigInt::new(&inner) + .map_err(|err| JsError::new(&err.to_string().as_string().unwrap()))? + .into(), + )) + } else { + Err(JsError::new(&format!( + "expected number or BigInt, found {inner:?}" + ))) + } + } + "float" => { + if inner.as_f64().is_some() { + Ok(JsDuperValueInner::Integer(inner)) + } else { + Err(JsError::new(&format!("expected number, found {inner:?}"))) + } + } + "boolean" => { + if Boolean::is_type_of(&inner) { + Ok(JsDuperValueInner::Boolean(inner)) + } else { + Err(JsError::new(&format!("expected boolean, found {inner:?}"))) + } + } + "null" => { + if inner.is_null() || inner.is_undefined() { + Ok(JsDuperValueInner::Null) + } else { + Err(JsError::new(&format!( + "expected null or undefined, found {inner:?}" + ))) + } + } + _ => Err(JsError::new(&format!("unknown type {typ}"))), + } + } else if inner.is_null() || inner.is_undefined() { + Ok(JsDuperValueInner::Null) + } else if Boolean::is_type_of(&inner) { + Ok(JsDuperValueInner::Boolean(inner)) + } else if inner.is_bigint() { + Ok(JsDuperValueInner::Integer(inner)) + } else if inner.as_f64().is_some() { + Ok(JsDuperValueInner::Float(inner)) + } else if Uint8Array::is_type_of(&inner) { + Ok(JsDuperValueInner::Bytes(inner)) + } else if inner.as_string().is_some() { + Ok(JsDuperValueInner::String(inner)) + } else if Array::is_array(&inner) { + Ok(JsDuperValueInner::Array(inner)) + } else if Object::instanceof(&inner) && !inner.is_function() && !inner.is_symbol() { + Ok(JsDuperValueInner::Object(inner)) + } else { + Err(JsError::new(&format!("unknown inner {inner:?}"))) + } + } +} + +impl Display for JsDuperValueInner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + JsDuperValueInner::Object(_) => "object", + JsDuperValueInner::Array(_) => "array", + JsDuperValueInner::Tuple(_) => "tuple", + JsDuperValueInner::String(_) => "string", + JsDuperValueInner::Bytes(_) => "bytes", + JsDuperValueInner::Integer(_) => "integer", + JsDuperValueInner::Float(_) => "float", + JsDuperValueInner::Boolean(_) => "boolean", + JsDuperValueInner::Null => "null", + }) + } +} + +#[wasm_bindgen(js_name = DuperValue)] +pub struct JsDuperValue { + pub(crate) identifier: Option>, + pub(crate) inner: JsDuperValueInner, +} + +impl JsDuperValue { + pub(crate) fn serialize(&self) -> Result, JsValue> { + let identifier = self.identifier.clone(); + match &self.inner { + JsDuperValueInner::Object(inner) => serialize_object(inner, identifier), + JsDuperValueInner::Array(inner) => serialize_array(inner, identifier), + JsDuperValueInner::Tuple(inner) => serialize_tuple(inner, identifier), + JsDuperValueInner::String(inner) => serialize_string(inner, identifier), + JsDuperValueInner::Bytes(inner) => serialize_bytes(inner, identifier), + JsDuperValueInner::Integer(inner) => serialize_integer(inner, identifier), + JsDuperValueInner::Float(inner) => serialize_float(inner, identifier), + JsDuperValueInner::Boolean(inner) => serialize_boolean(inner, identifier), + JsDuperValueInner::Null => serialize_null(identifier), + } + } +} + +#[wasm_bindgen(js_class = DuperValue)] +impl JsDuperValue { + /// Creates a new Duper value. + #[wasm_bindgen(constructor)] + pub fn new( + inner: JsValue, + identifier: Option, + r#type: Option, + ) -> Result { + let typ = r#type.and_then(|typ| JsValue::from(typ).as_string()); + let inner = JsDuperValueInner::new(typ, inner)?; + Ok(Self { + identifier: identifier.map(DuperIdentifier::try_from).transpose()?, + inner, + }) + } + + /// Returns the identifier of this Duper value. + #[wasm_bindgen(getter)] + pub fn identifier(&self) -> Option { + self.identifier + .as_ref() + .map(|identifier| identifier.as_ref().to_owned()) + } + + /// Sets the identifier of this Duper value. + #[wasm_bindgen(setter)] + pub fn set_identifier(&mut self, identifier: Option) -> Result<(), JsError> { + self.identifier = identifier.map(DuperIdentifier::try_from).transpose()?; + Ok(()) + } + + /// Returns the contents of this Duper value. + #[wasm_bindgen(getter)] + pub fn inner(&self) -> JsValue { + match &self.inner { + JsDuperValueInner::Object(inner) + | JsDuperValueInner::Array(inner) + | JsDuperValueInner::Tuple(inner) + | JsDuperValueInner::String(inner) + | JsDuperValueInner::Bytes(inner) + | JsDuperValueInner::Integer(inner) + | JsDuperValueInner::Float(inner) + | JsDuperValueInner::Boolean(inner) => inner.clone(), + JsDuperValueInner::Null => JsValue::NULL, + } + } + + /// Returns the type of this Duper value. + #[wasm_bindgen(getter)] + pub fn r#type(&self) -> DuperValueType { + JsValue::from(self.inner.to_string()).into() + } + + /// Sets the contents for this Duper value, optionally specifying the type. + #[wasm_bindgen(js_name = setValue)] + pub fn set_value( + &mut self, + inner: JsValue, + r#type: Option, + ) -> Result<(), JsError> { + let typ = r#type.and_then(|typ| JsValue::from(typ).as_string()); + self.inner = JsDuperValueInner::new(typ, inner)?; + Ok(()) + } + + #[wasm_bindgen(js_name = toJSON)] + pub fn to_json(&self) -> Result { + match &self.inner { + JsDuperValueInner::Object(inner) => { + let entries = + Object::entries(inner.dyn_ref().ok_or_else(|| { + JsError::new(&format!("expected Object, found {inner:?}")) + })?); + let new_object = Object::new(); + let to_json = JsValue::from_str("toJSON"); + + for (index, tup) in entries.into_iter().enumerate() { + let tup: Array = tup.dyn_into().expect("expected key-value tuple"); + let key = tup.get(0); + if !key.is_string() { + return Err(JsValue::from_str(&format!( + "invalid key #{index} for Object: expected string, found {key:?}" + ))); + } + let value = tup.get(1); + Reflect::set( + &new_object, + &key, + &Reflect::get(&value, &to_json)? + .dyn_into::()? + .call0(&value)?, + )?; + } + + Ok(new_object.into()) + } + JsDuperValueInner::Array(inner) | JsDuperValueInner::Tuple(inner) => { + let array = inner + .dyn_ref::() + .ok_or_else(|| JsError::new(&format!("expected Object, found {inner:?}")))?; + let new_array = Array::new_with_length(array.length()); + let to_json = JsValue::from_str("toJSON"); + + for (index, element) in array.iter().enumerate() { + new_array.set( + index as u32, + Reflect::get(&element, &to_json)? + .dyn_into::()? + .call0(&element)?, + ); + } + + Ok(new_array.into()) + } + JsDuperValueInner::String(inner) + | JsDuperValueInner::Float(inner) + | JsDuperValueInner::Boolean(inner) => Ok(inner.clone()), + JsDuperValueInner::Null => Ok(JsValue::NULL), + JsDuperValueInner::Bytes(inner) => { + let bytes = JsCast::dyn_ref::(inner) + .ok_or_else(|| JsValue::from_str("inner value was not an Uint8Array"))?; + let js_array = Array::new_with_length(bytes.length()); + for (index, value) in bytes.to_vec().into_iter().enumerate() { + js_array.set(index as u32, value.into()); + } + Ok(js_array.into()) + } + JsDuperValueInner::Integer(inner) => { + let bigint = JsCast::dyn_ref::(inner) + .ok_or_else(|| JsValue::from_str("inner value was not a BigInt"))?; + match i64::try_from(bigint.clone()) { + Ok(integer) => Ok((integer as f64).into()), + Err(_) => Ok(bigint.to_string(10)?.into()), + } + } + } + } +} diff --git a/duper-js-wasm/src/ser.rs b/duper-js-wasm/src/ser.rs index a841637..69f1f38 100644 --- a/duper-js-wasm/src/ser.rs +++ b/duper-js-wasm/src/ser.rs @@ -4,99 +4,38 @@ use duper::{ DuperArray, DuperBytes, DuperIdentifier, DuperInner, DuperKey, DuperObject, DuperString, DuperTuple, DuperValue, }; -use js_sys::{Array, BigInt, Boolean, Object, Reflect, Symbol, Uint8Array, try_iter}; -use wasm_bindgen::prelude::*; +use js_sys::{Array, BigInt, Boolean, Object, Uint8Array, try_iter}; +use wasm_bindgen::{convert::TryFromJsValue, prelude::*}; -use crate::{SYMBOL_DUPER_IDENTIFIER, SYMBOL_DUPER_TYPE, SYMBOL_DUPER_VALUE}; +use crate::repr::JsDuperValue; pub(crate) fn serialize_jsvalue(value: &JsValue) -> Result, JsValue> { - let identifier = if value.is_instance_of::() { - let identifier = Reflect::get(value, &Symbol::for_(SYMBOL_DUPER_IDENTIFIER))?; - let identifier = if identifier.is_truthy() { - if identifier.is_string() { - identifier - .as_string() - .map(DuperIdentifier::try_from) - .transpose() - .map_err(|e| JsValue::from_str(&e.to_string()))? - } else { - return Err(JsValue::from_str(&format!( - "invalid Duper identifier {identifier:?}" - ))); - } - } else { - None - }; - let typ = Reflect::get(value, &Symbol::for_(SYMBOL_DUPER_TYPE))?; - if typ.is_truthy() { - if typ.is_string() { - match typ.as_string().expect("checked Duper type").as_str() { - "object" => return serialize_object(value, identifier), - "array" => return serialize_array(value, identifier), - "tuple" => return serialize_tuple(value, identifier), - "string" => { - return serialize_string( - &Reflect::get(value, &Symbol::for_(SYMBOL_DUPER_VALUE))?, - identifier, - ); - } - "bytes" => (), - "integer" => { - return serialize_integer( - &Reflect::get(value, &Symbol::for_(SYMBOL_DUPER_VALUE))?, - identifier, - ); - } - "float" => { - return serialize_float( - &Reflect::get(value, &Symbol::for_(SYMBOL_DUPER_VALUE))?, - identifier, - ); - } - "boolean" => { - return serialize_boolean( - &Reflect::get(value, &Symbol::for_(SYMBOL_DUPER_VALUE))?, - identifier, - ); - } - "null" => return serialize_null(identifier), - _ => return Err(JsValue::from_str(&format!("invalid Duper type {typ:?}"))), - } - } else { - return Err(JsValue::from_str(&format!( - " - invalid Duper type {typ:?}" - ))); - } - } - identifier - } else { - None - }; - + if let Some(value) = JsDuperValue::try_from_js_value_ref(value) { + value.serialize() + } // Not a Duper deserialized value; detect which type it actually is - if value.is_null() || value.is_undefined() { - serialize_null(identifier) + else if value.is_null() || value.is_undefined() { + serialize_null(None) } else if Boolean::is_type_of(value) { - serialize_boolean(value, identifier) + serialize_boolean(value, None) } else if value.is_bigint() { - serialize_integer(value, identifier) + serialize_integer(value, None) } else if value.as_f64().is_some() { - serialize_float(value, identifier) + serialize_float(value, None) } else if Uint8Array::is_type_of(value) { - serialize_bytes(value, identifier) - } else if value.as_string().is_some() { - serialize_string(value, identifier) + serialize_bytes(value, None) + } else if value.is_string() { + serialize_string(value, None) } else if Array::is_array(value) { - serialize_array(value, identifier) + serialize_array(value, None) } else if !value.is_function() && !value.is_symbol() { - serialize_object(value, identifier) + serialize_object(value, None) } else { Err(JsValue::from_str(&format!("unknown value {value:?}"))) } } -fn serialize_object( +pub(crate) fn serialize_object( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { @@ -123,7 +62,7 @@ fn serialize_object( }) } -fn serialize_array( +pub(crate) fn serialize_array( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { @@ -136,7 +75,7 @@ fn serialize_array( }) } -fn serialize_tuple( +pub(crate) fn serialize_tuple( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { @@ -149,7 +88,7 @@ fn serialize_tuple( }) } -fn serialize_string( +pub(crate) fn serialize_string( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { @@ -162,59 +101,44 @@ fn serialize_string( }) } -fn serialize_bytes( +pub(crate) fn serialize_bytes( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { - let bytes: &Uint8Array = - JsCast::dyn_ref(value).ok_or_else(|| format!("expected bytes, found {value:?}"))?; + let bytes = JsCast::dyn_ref::(value) + .ok_or_else(|| format!("expected bytes, found {value:?}"))?; Ok(DuperValue { identifier, inner: DuperInner::Bytes(DuperBytes::from(Cow::Owned(bytes.to_vec()))), }) } -fn serialize_integer( +pub(crate) fn serialize_integer( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { - if let Some(bigint) = JsCast::dyn_ref::(value) { - match i64::try_from(bigint.clone()) { - Ok(integer) => Ok(DuperValue { - identifier, - inner: DuperInner::Integer(integer), - }), - Err(_) => Ok(DuperValue { - identifier: Some(identifier.unwrap_or_else(|| { - DuperIdentifier::try_from(Cow::Borrowed("Integer")).expect("valid identifier") - })), - inner: DuperInner::String(DuperString::from(Cow::Owned( - value - .as_string() - .ok_or_else(|| format!("expected integer, found {value:?}"))?, - ))), - }), - } - } else if let Some(float) = value.as_f64() { - if float.fract() == 0.0 { - Ok(DuperValue { - identifier, - inner: DuperInner::Integer(float as i64), - }) - } else { - Ok(DuperValue { - identifier, - inner: DuperInner::Float(float), - }) - } - } else { - Err(JsValue::from_str(&format!( - "expected integer, found {value:?}" - ))) + let bigint = JsCast::dyn_ref::(value) + .ok_or_else(|| format!("expected BigInt, found {value:?}"))?; + match i64::try_from(bigint.clone()) { + Ok(integer) => Ok(DuperValue { + identifier, + inner: DuperInner::Integer(integer), + }), + Err(_) => Ok(DuperValue { + identifier: Some(identifier.unwrap_or_else(|| { + DuperIdentifier::try_from(Cow::Borrowed("I64")).expect("valid identifier") + })), + inner: DuperInner::String(DuperString::from(Cow::Owned( + bigint + .to_string(10)? + .as_string() + .ok_or_else(|| "failed to convert BigInt to string")?, + ))), + }), } } -fn serialize_float( +pub(crate) fn serialize_float( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { @@ -228,7 +152,7 @@ fn serialize_float( }) } -fn serialize_boolean( +pub(crate) fn serialize_boolean( value: &JsValue, identifier: Option>, ) -> Result, JsValue> { @@ -238,7 +162,7 @@ fn serialize_boolean( }) } -fn serialize_null( +pub(crate) fn serialize_null( identifier: Option>, ) -> Result, JsValue> { Ok(DuperValue { diff --git a/duper-python/Cargo.toml b/duper-python/Cargo.toml index 4f672ce..7178b23 100644 --- a/duper-python/Cargo.toml +++ b/duper-python/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "duper-python" description = "The format that's super!" -version = "0.2.2" +version = "0.3.0" edition = "2024" rust-version = "1.88" license = "MIT" @@ -18,7 +18,7 @@ name = "_duper" crate-type = ["cdylib"] [dependencies] -duper = { path = "../duper", version = "0.2.2" } +duper = { path = "../duper" } pyo3 = { version = "0.27.1", features = [ "extension-module", "generate-import-lib", diff --git a/duper-vs-code/package.json b/duper-vs-code/package.json index 861b69d..a9ac315 100644 --- a/duper-vs-code/package.json +++ b/duper-vs-code/package.json @@ -2,7 +2,7 @@ "name": "duper-vs-code", "displayName": "Duper", "description": "Duper support for Visual Studio Code", - "version": "0.2.2", + "version": "0.3.0", "engines": { "vscode": "^1.105.0" }, diff --git a/duper/Cargo.toml b/duper/Cargo.toml index 0d75421..9bda6c4 100644 --- a/duper/Cargo.toml +++ b/duper/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "duper" description = "The format that's super!" -version = "0.2.2" +version = "0.3.0" edition = "2024" rust-version = "1.88" license = "MIT" diff --git a/duper_website/docs/guide-javascript.md b/duper_website/docs/guide-javascript.md index 30dfa0c..edbc817 100644 --- a/duper_website/docs/guide-javascript.md +++ b/duper_website/docs/guide-javascript.md @@ -14,9 +14,7 @@ npm install --save-dev vite vite-plugin-top-level-await vite-plugin-wasm Add the following to `vite.config.js`: ```javascript -import { - defineConfig -} from 'vite' +import { defineConfig } from "vite"; import wasm from "vite-plugin-wasm"; import topLevelAwait from "vite-plugin-top-level-await"; @@ -49,3 +47,56 @@ console.log(duper_string); const restored_data = parse(duper_string); console.log(restored_data); ``` + +You can also manipulate Duper values: + +```javascript +import { parse, stringify, DuperValue } from "@duper-js/wasm"; + +// Parse some input +const input = ` + Product({ + product_id: Uuid("1dd7b7aa-515e-405f-85a9-8ac812242609"), + name: "Wireless Bluetooth Headphones", + brand: "AudioTech", + price: Decimal("129.99"), + dimensions: (18.5, 15.2, 7.8), // In centimeters + weight: Kilograms(0.285), + in_stock: true, + specifications: { + battery_life: Duration("30h"), + noise_cancellation: true, + connectivity: ["Bluetooth 5.0", "3.5mm Jack"], + }, + image_thumbnail: Png(b"\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x64"), + tags: ["electronics", "audio", "wireless"], + release_date: Date("2023-11-15"), + /* Warranty is optional */ + warranty_period: null, + customer_ratings: { + latest_review: r#"Absolutely ""astounding""!! 😎"#, + average: 4.5, + count: 127, + }, + created_at: DateTime("2023-11-17T21:50:43+00:00"), + }) +`; +const duper = parse(input); +console.log(duper.identifier); // Product +console.log(duper.inner.in_stock.type); // boolean + +// Convert to JSON +console.log(JSON.stringify(duper)); + +// Patch the Duper value and pretty-print it +const newTags = [ + new DuperValue("music"), + new DuperValue("hi-fi", "DeprecatedTag", "string"), +]; +duper.inner.tags.setValue(newTags, "tuple"); +duper.inner.image_thumbnail.identifier = null; +duper.inner.weight.identifier = "Pounds"; +delete duper.inner.dimensions; +duper.inner.test = new DuperValue({ foo: new DuperValue("bar") }); +console.log(stringify(duper, { indent: " " })); +``` diff --git a/serde_duper/Cargo.toml b/serde_duper/Cargo.toml index 7d5bc2a..d4453d5 100644 --- a/serde_duper/Cargo.toml +++ b/serde_duper/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "serde_duper" description = "Serde support for Duper." -version = "0.2.2" +version = "0.3.0" edition = "2024" rust-version = "1.88" license = "MIT" @@ -28,7 +28,7 @@ uuid = ["dep:uuid"] [dependencies] # Core dependencies -duper = { path = "../duper", version = "0.2.2", features = ["serde"] } +duper = { path = "../duper", version = "0.3.0", features = ["serde"] } serde_bytes = "0.11" serde_core = "1" -- knotmirror 0.0.1