A fast, helpful, and open-source document parser
fix: reject invalid output formats in bindings
sanjayy061266150f59a2c7
diff --git a/crates/liteparse-napi/src/lib.rs b/crates/liteparse-napi/src/lib.rsindex c7e7ba3..3c13372 100644--- a/crates/liteparse-napi/src/lib.rs+++ b/crates/liteparse-napi/src/lib.rs@@ -20,13 +20,16 @@ impl LiteParse {/// Create a new LiteParse instance with optional configuration./// Any fields not provided will use defaults.#[napi(constructor)]- pub fn new(config: Option<JsLiteParseConfig>) -> Self {- let rust_config = config.map(|c| c.into_rust()).unwrap_or_default();+ pub fn new(config: Option<JsLiteParseConfig>) -> Result<Self> {+ let rust_config = config+ .map(|c| c.into_rust())+ .transpose()?+ .unwrap_or_default();let inner = liteparse::parser::LiteParse::new(rust_config.clone());- Self {+ Ok(Self {inner,config: rust_config,- }+ })}/// Parse a document. Accepts a file path (string) or raw PDF bytes (Buffer).diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rsindex 4d7df3d..f7f7edc 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -1,5 +1,6 @@use std::collections::HashMap;+use napi::bindgen_prelude::{Error, Result};use napi_derive::napi;use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};@@ -133,7 +134,7 @@ pub struct JsCropBox {}impl JsLiteParseConfig {- pub fn into_rust(self) -> LiteParseConfig {+ pub fn into_rust(self) -> Result<LiteParseConfig> {let mut cfg = LiteParseConfig::default();if let Some(v) = self.ocr_language {cfg.ocr_language = v;@@ -166,11 +167,7 @@ impl JsLiteParseConfig {cfg.dpi = v as f32;}if let Some(v) = self.output_format {- cfg.output_format = match v.as_str() {- "text" => OutputFormat::Text,- "markdown" | "md" => OutputFormat::Markdown,- _ => OutputFormat::Json,- };+ cfg.output_format = parse_output_format(&v)?;}if let Some(v) = self.preserve_very_small_text {cfg.preserve_very_small_text = v;@@ -259,7 +256,7 @@ impl JsLiteParseConfig {if let Some(v) = self.extract_vector_graphics {cfg.extract_vector_graphics = v;}- cfg+ Ok(cfg)}pub fn from_rust(cfg: &LiteParseConfig) -> Self {@@ -327,6 +324,17 @@ impl JsLiteParseConfig {}}+fn parse_output_format(value: &str) -> Result<OutputFormat> {+ match value {+ "json" => Ok(OutputFormat::Json),+ "text" => Ok(OutputFormat::Text),+ "markdown" | "md" => Ok(OutputFormat::Markdown),+ _ => Err(Error::from_reason(format!(+ "invalid outputFormat: {value} (expected 'json', 'text', or 'markdown')"+ ))),+ }+}+// ---------------------------------------------------------------------------// TextItem// ---------------------------------------------------------------------------@@ -1384,7 +1392,23 @@ mod tests {let mut js = JsLiteParseConfig::from_rust(&LiteParseConfig::default());assert_eq!(js.extract_text_metadata, Some(false));js.extract_text_metadata = Some(true);- assert!(js.into_rust().extract_text_metadata);+ assert!(js.into_rust().unwrap().extract_text_metadata);+ }++ #[test]+ fn output_format_rejects_invalid_values() {+ assert_eq!(parse_output_format("json").unwrap(), OutputFormat::Json);+ assert_eq!(parse_output_format("text").unwrap(), OutputFormat::Text);+ assert_eq!(+ parse_output_format("markdown").unwrap(),+ OutputFormat::Markdown+ );+ assert_eq!(parse_output_format("md").unwrap(), OutputFormat::Markdown);++ let mut config = JsLiteParseConfig::from_rust(&LiteParseConfig::default());+ config.output_format = Some("yaml".to_string());+ let error = config.into_rust().unwrap_err();+ assert!(error.reason.contains("invalid outputFormat: yaml"));}#[test]diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rsindex 5ad832d..77d09bb 100644--- a/crates/liteparse-python/src/lib.rs+++ b/crates/liteparse-python/src/lib.rs@@ -8,6 +8,17 @@ use liteparse::types::PdfInput;mod cli;+fn parse_output_format(value: &str) -> PyResult<OutputFormat> {+ match value {+ "json" => Ok(OutputFormat::Json),+ "text" => Ok(OutputFormat::Text),+ "markdown" | "md" => Ok(OutputFormat::Markdown),+ _ => Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(+ "invalid output_format: {value} (expected 'json', 'text', or 'markdown')"+ ))),+ }+}+// ---------------------------------------------------------------------------// Python type wrappers// ---------------------------------------------------------------------------@@ -1534,11 +1545,7 @@ impl LiteParse {cfg.dpi = v;}if let Some(v) = output_format {- cfg.output_format = match v.as_str() {- "text" => OutputFormat::Text,- "markdown" | "md" => OutputFormat::Markdown,- _ => OutputFormat::Json,- };+ cfg.output_format = parse_output_format(&v)?;}if let Some(v) = preserve_very_small_text {cfg.preserve_very_small_text = v;@@ -1955,6 +1962,20 @@ mod tests {assert!(py.extract_text_metadata);}+ #[test]+ fn output_format_rejects_invalid_values() {+ assert_eq!(parse_output_format("json").unwrap(), OutputFormat::Json);+ assert_eq!(parse_output_format("text").unwrap(), OutputFormat::Text);+ assert_eq!(+ parse_output_format("markdown").unwrap(),+ OutputFormat::Markdown+ );+ assert_eq!(parse_output_format("md").unwrap(), OutputFormat::Markdown);++ let error = parse_output_format("yaml").unwrap_err();+ assert!(error.to_string().contains("invalid output_format: yaml"));+ }+#[test]fn converts_vector_graphics_to_python_shape() {let rust = liteparse::types::VectorGraphics {diff --git a/packages/node/tests/exports.test.mjs b/packages/node/tests/exports.test.mjsindex b96b9fb..5113771 100644--- a/packages/node/tests/exports.test.mjs+++ b/packages/node/tests/exports.test.mjs@@ -83,6 +83,15 @@ test("CJS: require by package name loads the native module and parses", async ()assert.ok(result.text.length > 0, "expected non-empty extracted text");});+test("rejects an invalid outputFormat", async () => {+ const { LiteParse } = await import(PACKAGE_NAME);++ assert.throws(+ () => new LiteParse({ outputFormat: "yaml" }),+ /invalid outputFormat: yaml/,+ );+});+// The native .node binary is located relative to the built file's own path.// Loading from a working directory outside the package, via an entry script// that cannot resolve the package by name, is the case that catches a loaderdiff --git a/packages/python/tests/test_parse_e2e.py b/packages/python/tests/test_parse_e2e.pyindex 11b9334..22cca2e 100644--- a/packages/python/tests/test_parse_e2e.py+++ b/packages/python/tests/test_parse_e2e.py@@ -106,6 +106,10 @@ class TestParsedPageStructure:class TestParseOptions:"""Test that CLI options are correctly forwarded."""+ def test_invalid_output_format(self):+ with pytest.raises(ValueError, match="invalid output_format: yaml"):+ LiteParse(output_format="yaml")+def test_target_pages(self, parser: LiteParse, invoice_pdf: Path):# invoice.pdf has 2 pages — parse only page 1result = parser.parse(invoice_pdf, ocr_enabled=False, target_pages="1")