### Install Project Dependencies with npm Source: https://github.com/thwbh/tauri-typegen/blob/main/examples/tauri-app/README.md Installs all necessary project dependencies using the npm package manager. This is a prerequisite for running the development server or building the application. ```bash npm install ``` -------------------------------- ### Tauri App Development and Type Generation Example Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md This sequence of bash commands outlines the steps to set up and run an example Tauri application that utilizes tauri-typegen. It includes installing dependencies, starting the development server, and triggering the TypeScript model generation. ```bash cd examples/tauri-app npm install npm run tauri dev ``` -------------------------------- ### Run Tauri Development Server with npm Source: https://github.com/thwbh/tauri-typegen/blob/main/examples/tauri-app/README.md Starts the Tauri development server using npm. This command is typically used to preview changes during development and allows for hot-reloading of the frontend application. ```bash npm run tauri dev ``` -------------------------------- ### Rust Code Example for Tauri Command Source: https://github.com/thwbh/tauri-typegen/blob/main/examples/tauri-app/README.md A basic Rust function intended to be exposed as a Tauri command. This function, 'greet', takes a string name as input and returns a greeting string. It's used to test the type generation capabilities of Tauri TypeGen. ```rust #[tauri::command] fn greet(name: &str) -> String { format!("Hello, {}! You've been greeted from Rust!", name) } ``` -------------------------------- ### Tauri TypeGen Configuration File Example Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md A sample JSON configuration file for Tauri TypeGen. This file specifies paths for the project and output, the chosen validation library, and verbosity settings. ```json { "project_path": "./src-tauri", "output_path": "./src/generated", "validation_library": "zod", "verbose": true, "visualize_deps": false } ``` -------------------------------- ### TypeScript: Use Generated Command Bindings Source: https://context7.com/thwbh/tauri-typegen/llms.txt Provides an example of importing and utilizing the TypeScript command bindings generated by `tauri-typegen`. It showcases type-safe function calls, request/response handling, and error management. ```typescript import { createProduct, getProducts, deleteProduct } from './generated'; import type { Product, CreateProductRequest } from './generated'; // Create product with type safety and validation async function addProduct() { try { const product = await createProduct({ request: { name: "Gaming Laptop", description: "High-performance gaming laptop", price: 1299.99, categoryId: 5 } }); console.log("Created:", product); } catch (error) { console.error("Validation or invocation error:", error); } } // Query products with optional filter async function listProducts() { const products = await getProducts({ filter: { search: "laptop", minPrice: 1000, maxPrice: 2000, inStockOnly: true, categoryId: null } }); return products; } // Delete product async function removeProduct(productId: number) { await deleteProduct({ id: productId }); } ``` -------------------------------- ### Generate TypeScript Bindings with Tauri TypeGen CLI Source: https://github.com/thwbh/tauri-typegen/blob/main/examples/tauri-app/README.md Generates TypeScript bindings for Tauri commands and events using the tauri-typegen CLI. This command specifies the input Tauri project path, the output directory for generated files, the validation schema type (zod), and enables verbose logging. ```bash # From the project root ../../target/debug/cargo-tauri-typegen tauri-typegen generate --project-path ./src-tauri --output-path ./src/generated --validation zod --verbose ``` -------------------------------- ### Install Tauri TypeGen CLI Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Installs the Tauri TypeGen command-line interface using Cargo, Rust's package manager. This is the primary method for obtaining the tool. ```bash cargo install tauri-typegen ``` -------------------------------- ### Tauri TypeGen Package.json Build Scripts Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Integrates Tauri TypeGen type generation into your npm build scripts. This example shows how to run `generate-types` before starting the Tauri development server or building the application, ensuring types are up-to-date. ```json { "scripts": { "generate-types": "cargo tauri-typegen generate", "tauri:dev": "npm run generate-types && tauri dev", "tauri:build": "npm run generate-types && tauri build" } } ``` -------------------------------- ### Use Generated TypeScript Bindings in Frontend Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Demonstrates how to import and use the strongly-typed frontend functions generated by Tauri TypeGen. This example shows calling `createUser` and `getUsers` commands with their respective typed arguments. ```typescript import { createUser, getUsers } from './src/generated'; const user = await createUser({ request: { name: "John", email: "john@example.com" } }); const users = await getUsers({ filter: null }); ``` -------------------------------- ### Tauri Typegen: Manual vs. Generated Bindings Example Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Illustrates the difference between manual API calls and using generated Tauri Typegen bindings for type safety and correct naming conventions. Shows how generated bindings prevent common errors in parameter types and naming. ```typescript // ❌ Before: Manual typing, prone to errors const result = await invoke('create_product', { name: 'Product', price: '19.99', // Oops! Should be number category_id: 1 // Oops! Should be camelCase }); // ✅ After: Generated bindings with validation const result = await createProduct({ request: { name: 'Product', price: 19.99, // Correct type categoryId: 1 // Correct naming } }); ``` -------------------------------- ### Package.json Scripts for Type Generation (Alternative) Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md An alternative method to integrate `tauri-typegen` using npm scripts in `package.json`. Defines scripts like `generate-types`, `dev`, and `build` to explicitly run the type generation command before starting the development server or building the production app. ```json { "scripts": { "generate-types": "cargo tauri-typegen generate", "dev": "npm run generate-types && npm run tauri dev", "build": "npm run generate-types && npm run tauri build", "tauri": "tauri" } } ``` -------------------------------- ### Tauri Typegen: Runtime Validation Example Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Demonstrates the automatic runtime validation provided by Tauri Typegen generated bindings. Shows how invalid input data (e.g., empty name, negative price) will trigger a validation error when calling generated functions. ```typescript // Automatically validates input at runtime try { await createProduct({ request: { name: '', // Will throw validation error price: -5 // Will throw validation error } }); } catch (error) { console.error('Validation failed:', error); } ``` -------------------------------- ### Tauri Build Hooks for Type Generation (Recommended) Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Integrates `tauri-typegen` into Tauri's build process using `tauri.conf.json`. This ensures TypeScript types are generated before the frontend build or development server starts, solving dependency issues. Shows configuration for `beforeDevCommand` and `beforeBuildCommand`. ```json { "build": { "beforeDevCommand": "cargo tauri-typegen generate && npm run dev", "beforeBuildCommand": "cargo tauri-typegen generate && npm run build", "devUrl": "http://localhost:1420", "frontendDist": "../dist" }, "plugins": { "tauri-typegen": { "project_path": "./src-tauri", "output_path": "./src/generated", "validation_library": "zod", "verbose": false, "visualize_deps": false } } } ``` -------------------------------- ### Generate Zod Schemas from Rust Validators (TypeScript) Source: https://context7.com/thwbh/tauri-typegen/llms.txt Shows how Rust validator attributes are automatically converted into Zod validation rules for TypeScript. This example includes a Rust struct with validation attributes and the corresponding automatically generated Zod schema, demonstrating compile-time safety and runtime validation integration. ```typescript // Automatically generated from Rust validators import { z } from 'zod'; export const CreateUserRequestSchema = z.object({ username: z.string().min(3).max(50), email: z.string().email(), age: z.number().min(18).max(120), website: z.string().url().nullable(), }); export const CreateUserParamsSchema = z.object({ request: CreateUserRequestSchema, }); // Type-safe command with runtime validation export async function createUser(params: CreateUserParams): Promise { const validatedParams = CreateUserParamsSchema.parse(params); return invoke('create_user', validatedParams); } ``` -------------------------------- ### CLI: Initialize Tauri TypeGen Configuration Source: https://context7.com/thwbh/tauri-typegen/llms.txt Create a configuration file for Tauri TypeGen. Can be a standalone JSON file or integrated into `tauri.conf.json`. Supports specifying the validation library and forcing an overwrite of existing files. ```bash # Create standalone configuration file cargo tauri-typegen init --output my-config.json --validation zod # Add configuration to tauri.conf.json cargo tauri-typegen init --output tauri.conf.json --validation zod # Force overwrite existing configuration cargo tauri-typegen init --output tauri.conf.json --force ``` -------------------------------- ### Tauri TypeGen Init CLI Options Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Details the options for the `cargo tauri-typegen init` command, which is used to set up the configuration file. Options include the output path for the config file and the desired validation library. ```bash cargo tauri-typegen init [OPTIONS] Options: -o, --output Output path for config file [default: tauri.conf.json] -v, --validation Validation library: zod or none [default: zod] --force Force overwrite existing configuration ``` -------------------------------- ### Svelte Product Store with Tauri Typegen Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Svelte store implementation for managing products using Tauri Typegen generated bindings. It provides asynchronous functions to load, create, and delete products, updating a Svelte writable store. Dependencies include Svelte stores and the generated TypeScript types from Tauri Typegen. ```typescript import { writable } from 'svelte/store'; import { getProducts, createProduct, deleteProduct } from './generated'; import type { Product, ProductFilter } from './generated'; export const products = writable([]); export const loading = writable(false); export const productStore = { async loadProducts(filter: ProductFilter = {}) { loading.set(true); try { const result = await getProducts({ filter }); products.set(result); } catch (error) { console.error('Failed to load products:', error); } finally { loading.set(false); } }, async createProduct(request: CreateProductRequest) { try { const newProduct = await createProduct({ request }); products.update(items => [...items, newProduct]); return newProduct; } catch (error) { console.error('Failed to create product:', error); throw error; } }, async deleteProduct(id: number) { try { await deleteProduct({ id }); products.update(items => items.filter(p => p.id !== id)); } catch (error) { console.error('Failed to delete product:', error); throw error; } } }; ``` -------------------------------- ### Rust: Save and Merge Configuration Source: https://context7.com/thwbh/tauri-typegen/llms.txt Demonstrates how to create, save to files, and merge `GenerateConfig` objects in Rust. This allows for flexible configuration management for type generation. ```rust use tauri_plugin_typegen::interface::GenerateConfig; // Create configuration let mut config = GenerateConfig { project_path: "./src-tauri".to_string(), output_path: "./src/generated".to_string(), validation_library: "zod".to_string(), verbose: Some(true), ..Default::default() }; // Save to standalone file config.save_to_file("typegen.json") .expect("Failed to save config"); // Save to tauri.conf.json config.save_to_tauri_config("tauri.conf.json") .expect("Failed to save to Tauri config"); // Merge with override configuration let override_config = GenerateConfig { verbose: Some(false), visualize_deps: Some(true), ..Default::default() }; config.merge(&override_config); println!("Merged verbose: {}", config.is_verbose()); println!("Merged visualize: {}", config.should_visualize_deps()); ``` -------------------------------- ### Initialize Tauri TypeGen Configuration Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Initializes a configuration file for Tauri TypeGen. This can create a standalone JSON configuration file or integrate settings into your existing `tauri.conf.json`. It allows specifying the validation library. ```bash # Create a standalone config file cargo tauri-typegen init --output my-config.json --validation zod # Or add configuration to your tauri.conf.json cargo tauri-typegen init --output tauri.conf.json --validation zod ``` -------------------------------- ### Generate TypeScript Types with Tauri CLI Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Demonstrates various ways to use the `cargo tauri-typegen generate` command to create TypeScript bindings. Covers default generation, custom paths, validation schema selection (e.g., Zod), verbose output, dependency visualization, configuration file usage, and shorthand options. ```bash # Basic generation with defaults cargo tauri-typegen generate # Custom paths and validation cargo tauri-typegen generate \ --project-path ./src-tauri \ --output-path ./src/lib/generated \ --validation zod \ --verbose # Generate with dependency visualization cargo tauri-typegen generate --visualize-deps # Use configuration file cargo tauri-typegen generate --config my-config.json # Quick examples for different setups cargo tauri-typegen generate -p ./backend -o ./frontend/types -v zod cargo tauri-typegen generate --validation none # No validation schemas ``` -------------------------------- ### Rust: Create Tauri TypeGen Configuration Programmatically Source: https://context7.com/thwbh/tauri-typegen/llms.txt Create and customize Tauri TypeGen generation configuration in Rust code using a builder-style API. Allows setting project/output paths, validation library, verbosity, dependency visualization, and custom type mappings. Includes validation of the final configuration. ```rust use tauri_plugin_typegen::interface::GenerateConfig; use std::collections::HashMap; // Create with defaults let mut config = GenerateConfig::default(); // Customize settings config.project_path = "./backend/src".to_string(); config.output_path = "./frontend/types".to_string(); config.validation_library = "zod".to_string(); config.verbose = Some(true); config.visualize_deps = Some(true); config.include_private = Some(false); // Add custom type mappings let mut type_mappings = HashMap::new(); type_mappings.insert("DateTime".to_string(), "string".to_string()); type_mappings.insert("Uuid".to_string(), "string".to_string()); config.type_mappings = Some(type_mappings); // Add file patterns config.exclude_patterns = Some(vec!["**/tests/**".to_string()]); config.include_patterns = Some(vec!["**/commands/**".to_string()]); // Validate configuration config.validate().expect("Invalid configuration"); ``` -------------------------------- ### Rust: Generate Bindings Programmatically Source: https://context7.com/thwbh/tauri-typegen/llms.txt Shows how to programmatically generate TypeScript bindings from Rust code using the `tauri-plugin-typegen` API. This method takes a `GenerateConfig` object and produces the necessary type definitions. ```rust use tauri_plugin_typegen::interface::{GenerateConfig, generate_from_config}; // Create configuration let config = GenerateConfig { project_path: "./src-tauri".to_string(), output_path: "./src/generated".to_string(), validation_library: "zod".to_string(), verbose: Some(true), visualize_deps: Some(false), ..Default::default() }; // Generate bindings match generate_from_config(&config) { Ok(files) => { println!("✅ Generated {} files:", files.len()); for file in files { println!(" 📄 {}", file); } } Err(err) => { eprintln!("❌ Generation failed: {}", err); } } ``` -------------------------------- ### Running Tests for Tauri TypeGen Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md This bash command executes the test suite for the tauri-typegen project. Running tests ensures that the plugin functions correctly and that recent changes have not introduced regressions. ```bash cargo test ``` -------------------------------- ### Tauri TypeGen CLI Options Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Lists the available options for the `cargo tauri-typegen generate` command. These options control aspects like the project path, output directory, validation library, and verbosity. ```bash cargo tauri-typegen generate [OPTIONS] Options: -p, --project-path Path to Tauri source directory [default: ./src-tauri] -o, --output-path Output path for TypeScript files [default: ./src/generated] -v, --validation Validation library: zod or none [default: zod] --verbose Verbose output --visualize-deps Generate dependency graph visualization -c, --config Configuration file path ``` -------------------------------- ### Rust: Analyze Tauri Commands Source: https://context7.com/thwbh/tauri-typegen/llms.txt Demonstrates how to use `CommandAnalyzer` to inspect Tauri commands within a project. It extracts command names, parameters, return types, and associated struct/enum definitions. ```rust use tauri_plugin_typegen::analysis::CommandAnalyzer; // Create analyzer let mut analyzer = CommandAnalyzer::new(); // Analyze project let commands = analyzer.analyze_project("./src-tauri") .expect("Failed to analyze project"); // Inspect discovered commands for cmd in &commands { println!("Command: {} (async: {})", cmd.name, cmd.is_async); println!(" File: {}:{}", cmd.file_path, cmd.line_number); println!(" Returns: {}", cmd.return_type); for param in &cmd.parameters { println!(" Param: {} -> {}", param.rust_type, param.typescript_type); } } // Get discovered struct definitions let structs = analyzer.get_discovered_structs(); for (name, struct_info) in structs { let kind = if struct_info.is_enum { "enum" } else { "struct" }; println!("{} {}: {} fields", kind, name, struct_info.fields.len()); } ``` -------------------------------- ### Building the Tauri TypeGen Plugin Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md This bash command compiles the tauri-typegen Rust plugin. It's a standard command for building Rust projects and is necessary for local development or deployment. ```bash cargo build ``` -------------------------------- ### Rust: Load Tauri TypeGen Configuration from Tauri Config Source: https://context7.com/thwbh/tauri-typegen/llms.txt Load Tauri TypeGen generation configuration from the `plugins.typegen` section of `tauri.conf.json` using `GenerateConfig::from_tauri_config`. ```rust use tauri_plugin_typegen::interface::GenerateConfig; // Load from tauri.conf.json with typegen plugin configuration let config = GenerateConfig::from_tauri_config("tauri.conf.json") .expect("Failed to load Tauri configuration"); // The configuration is extracted from plugins.typegen section if config.is_verbose() { println!("Loaded configuration from Tauri config"); } ``` -------------------------------- ### CLI: Generate TypeScript Bindings with Tauri TypeGen Source: https://context7.com/thwbh/tauri-typegen/llms.txt Generate TypeScript models and bindings from a Tauri project. Supports custom paths, validation libraries (like Zod), and visualization of dependencies. Can also use a configuration file or disable validation. ```bash cargo tauri-typegen generate cargo tauri-typegen generate \ --project-path ./src-tauri \ --output-path ./src/lib/generated \ --validation zod \ --verbose cargo tauri-typegen generate --visualize-deps cargo tauri-typegen generate --config my-config.json cargo tauri-typegen generate --validation none ``` -------------------------------- ### Rust Tauri Commands for E-commerce App Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Defines data structures (Product, CreateProductRequest, ProductFilter) and Tauri commands (create_product, get_products, delete_product) for an e-commerce application. Uses `serde` for serialization/deserialization and `validator` for request validation. These commands can be used with `tauri-typegen` to generate TypeScript types. ```rust use serde::{Deserialize, Serialize}; use tauri::command; use validator::Validate; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Product { pub id: i32, pub name: String, pub description: String, pub price: f64, pub in_stock: bool, pub category_id: i32, } #[derive(Debug, Deserialize, Validate)] #[serde(rename_all = "camelCase")] pub struct CreateProductRequest { #[validate(length(min = 1, max = 100))] pub name: String, #[validate(length(max = 500))] pub description: String, #[validate(range(min = 0.01, max = 10000.0))] pub price: f64, pub category_id: i32, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ProductFilter { pub search: Option, pub category_id: Option, pub min_price: Option, pub max_price: Option, pub in_stock_only: Option, } #[command] pub async fn create_product(request: CreateProductRequest) -> Result { // Implementation here Ok(Product { id: 1, name: request.name, description: request.description, price: request.price, in_stock: true, category_id: request.category_id, }) } #[command] pub async fn get_products(filter: Option) -> Result, String> { // Implementation here Ok(vec![]) } #[command] pub async fn delete_product(id: i32) -> Result<(), String> { // Implementation here Ok(()) } ``` -------------------------------- ### Generate TypeScript Bindings with Tauri TypeGen CLI Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Generates TypeScript types and command bindings from your Tauri project's Rust source files. This command should be run from your Tauri project's root directory. It automatically discovers commands and creates corresponding frontend definitions. ```bash # In your Tauri project root cargo tauri-typegen generate ``` -------------------------------- ### Rust: Load Tauri TypeGen Configuration from JSON File Source: https://context7.com/thwbh/tauri-typegen/llms.txt Load Tauri TypeGen generation configuration from a standalone JSON file using `GenerateConfig::from_file`. The configuration is automatically validated upon loading. ```rust use tauri_plugin_typegen::interface::GenerateConfig; // Load configuration from file let config = GenerateConfig::from_file("my-config.json") .expect("Failed to load configuration"); // Configuration is automatically validated println!("Project path: {}", config.project_path); println!("Output path: {}", config.output_path); println!("Validation: {}", config.validation_library); ``` -------------------------------- ### React Integration with Tauri Generated Types Source: https://context7.com/thwbh/tauri-typegen/llms.txt This snippet shows how to integrate generated TypeScript types and commands into a React application using hooks. It demonstrates fetching a list of products, creating a new product, and deleting an existing product, handling loading and error states. ```typescript import React, { useEffect, useState } from 'react'; import { getProducts, createProduct, deleteProduct } from '../generated'; import type { Product } from '../generated'; export function ProductList() { const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { loadProducts(); }, []); const loadProducts = async () => { try { setLoading(true); setError(null); const result = await getProducts({ filter: null }); setProducts(result); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load'); } finally { setLoading(false); } }; const handleCreate = async () => { try { const newProduct = await createProduct({ request: { name: 'New Item', description: 'A new product', price: 29.99, categoryId: 1 } }); setProducts([...products, newProduct]); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to create'); } }; const handleDelete = async (id: number) => { try { await deleteProduct({ id }); setProducts(products.filter(p => p.id !== id)); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to delete'); } }; if (loading) return
Loading...
; if (error) return
Error: {error}
; return (
{products.map(product => (

{product.name}

{product.description}

${product.price}

))}
); } ``` -------------------------------- ### Tauri TypeGen Library Usage in Rust Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md This Rust code snippet demonstrates how to programmatically use the tauri-typegen library within a build script. It configures generation settings, including project and output paths, and initiates the type generation process. ```rust use tauri_plugin_typegen::interface::{GenerateConfig, generate_from_config}; let config = GenerateConfig { project_path: "./src-tauri".to_string(), output_path: "./src/generated".to_string(), validation_library: "zod".to_string(), verbose: Some(true), visualize_deps: Some(false), ..Default::default() }; let files = generate_from_config(&config)?; ``` -------------------------------- ### React Component for Managing Products with Tauri Bindings Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md A React component demonstrating how to use the generated Tauri command functions (`getProducts`, `createProduct`, `deleteProduct`) to fetch, create, and delete products. It includes state management for products, loading status, and error handling. ```tsx import React, { useEffect, useState } from 'react'; import { getProducts, createProduct, deleteProduct } from '../lib/generated'; import type { Product, ProductFilter } from '../lib/generated'; export function ProductList() { const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { loadProducts(); }, []); const loadProducts = async () => { try { setLoading(true); const result = await getProducts({ filter: null }); setProducts(result); } catch (error) { console.error('Failed to load products:', error); } finally { setLoading(false); } }; const handleCreateProduct = async () => { try { const newProduct = await createProduct({ request: { name: 'New Product', description: 'A new product', price: 19.99, categoryId: 1, } }); setProducts([...products, newProduct]); } catch (error) { console.error('Failed to create product:', error); } }; const handleDeleteProduct = async (productId: number) => { try { await deleteProduct({ id: productId }); setProducts(products.filter(p => p.id !== productId)); } catch (error) { console.error('Failed to delete product:', error); } }; if (loading) return
Loading...
; return (

Products

{products.map((product) => (

{product.name}

{product.description}

${product.price}

Stock: {product.inStock ? '✅' : '❌'}

))}
); } ``` -------------------------------- ### Cargo Build Scripts for Advanced Type Generation Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md An advanced method for integrating `tauri-typegen` directly into the Rust build process via `src-tauri/build.rs`. This Rust script uses `std::process::Command` to execute `cargo tauri-typegen generate` and checks for successful execution before proceeding with the Tauri build. ```rust use std::process::Command; fn main() { // Generate TypeScript bindings before build let output = Command::new("cargo") .args(&["tauri-typegen", "generate"]) .output() .expect("Failed to run cargo tauri-typegen"); if !output.status.success() { panic!("TypeScript generation failed: {}", String::from_utf8_lossy(&output.stderr)); } tauri_build::build() } ``` -------------------------------- ### Library Usage Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Programmatic usage of the Tauri TypeGen library within Rust build scripts for advanced customization. ```APIDOC ## Library Usage (Advanced) ### Description Provides a programmatic interface to generate TypeScript types from Rust code within your build scripts. ### Method Rust Library Function ### Endpoint `tauri_plugin_typegen::interface::generate_from_config(&config)?` ### Parameters #### Request Body (`GenerateConfig` struct) - **project_path** (string) - Required - Path to the Tauri project source directory - **output_path** (string) - Required - Output path for generated TypeScript files - **validation_library** (string) - Required - Validation library to use (`zod` or `none`) - **verbose** (boolean) - Optional - Enable verbose output - **visualize_deps** (boolean) - Optional - Generate dependency graph visualization - Other fields available via `..Default::default()` ### Request Example ```rust use tauri_plugin_typegen::interface::{GenerateConfig, generate_from_config}; let config = GenerateConfig { project_path: "./src-tauri".to_string(), output_path: "./src/generated".to_string(), validation_library: "zod".to_string(), verbose: Some(true), visualize_deps: Some(false), ..Default::default() }; let files = generate_from_config(&config)?; ``` ### Response #### Success Response (Result) - **files** (Vec) - A vector of generated file paths. #### Response Example (Returns a `Result` containing `Vec` on success or an error. ``` -------------------------------- ### CLI Commands Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md The `tauri-typegen` CLI command allows you to generate TypeScript types and schemas directly from your Tauri project. ```APIDOC ## CLI Commands ### Description Generates TypeScript types and Zod schemas from Rust code in a Tauri project. ### Method CLI Command ### Endpoint `cargo tauri-typegen generate [OPTIONS]` ### Parameters #### Command Options - **-p, --project-path ** (string) - Optional - Path to the Tauri project source directory (`default: ./src-tauri`) - **-o, --output-path ** (string) - Optional - Output path for generated TypeScript files (`default: ./src/generated`) - **-v, --validation ** (string) - Optional - Validation library to use (`default: zod`, possible values: `zod`, `none`) - **--verbose** (boolean) - Optional - Enable verbose output - **--visualize-deps** (boolean) - Optional - Generate dependency graph visualization - **-c, --config ** (string) - Optional - Configuration file path - **-h, --help** (boolean) - Optional - Print help information ### Request Example ```bash cargo tauri-typegen generate -p ./src-tauri -o ./src/types --validation zod ``` ### Response #### Success Response (0) - Output: Generates `.ts` and `.d.ts` files at the specified output path. #### Response Example (No direct response body, output is file generation) ``` -------------------------------- ### Configure Custom Rust-to-TypeScript Type Mappings (Rust) Source: https://context7.com/thwbh/tauri-typegen/llms.txt Demonstrates how to configure custom type mappings for domain-specific Rust types to their TypeScript equivalents within the `tauri-plugin-typegen` configuration. This allows for precise control over how complex or custom types are represented in the generated TypeScript code. ```rust use tauri_plugin_typegen::interface::GenerateConfig; use std::collections::HashMap; let mut config = GenerateConfig::default(); // Map custom Rust types to TypeScript let mut type_mappings = HashMap::new(); type_mappings.insert("chrono::DateTime".to_string(), "string".to_string()); type_mappings.insert("uuid::Uuid".to_string(), "string".to_string()); type_mappings.insert("rust_decimal::Decimal".to_string(), "number".to_string()); type_mappings.insert("serde_json::Value".to_string(), "any".to_string()); type_mappings.insert("PathBuf".to_string(), "string".to_string()); config.type_mappings = Some(type_mappings); // Now when generating, these types will use custom mappings // Rust: pub created_at: DateTime // TypeScript: createdAt: string ``` -------------------------------- ### Integrate Type Generation with Cargo Build Script (Rust) Source: https://context7.com/thwbh/tauri-typegen/llms.txt Integrates TypeScript type generation into the Rust build process using a `build.rs` script. This ensures types are generated before the Tauri application is built. It executes `cargo tauri-typegen` to generate bindings and then proceeds with the standard Tauri build. ```rust // src-tauri/build.rs use std::process::Command; fn main() { // Generate TypeScript bindings before building println!("cargo:rerun-if-changed=src"); let output = Command::new("cargo") .args(&[ "tauri-typegen", "generate", "--project-path", "./src-tauri", "--output-path", "./src/generated", "--validation", "zod" ]) .output() .expect("Failed to run cargo tauri-typegen"); if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); panic!("TypeScript generation failed:\n{}", stderr); } println!("cargo:warning=TypeScript bindings generated successfully"); // Continue with Tauri build tauri_build::build() } ``` -------------------------------- ### Tauri TypeGen CLI Generation Command Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md This bash command invokes the tauri-typegen CLI to generate TypeScript types and schemas. It accepts various options to specify the Tauri project path, output directory, validation library, and enables verbose output or dependency visualization. ```bash cargo tauri-typegen generate [OPTIONS] OPTIONS: -p, --project-path Path to the Tauri project source directory [default: ./src-tauri] -o, --output-path Output path for generated TypeScript files [default: ./src/generated] -v, --validation Validation library to use [default: zod] [possible values: zod, none] --verbose Enable verbose output --visualize-deps Generate dependency graph visualization -c, --config Configuration file path -h, --help Print help information ``` -------------------------------- ### Vue Product Management with Tauri Typegen Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Vue.js component for managing products using Tauri Typegen generated bindings. It fetches, creates, and deletes products from a backend API. Dependencies include Vue.js and the generated TypeScript types from Tauri Typegen. ```vue ``` -------------------------------- ### Integrate Type Generation with Package.json Scripts (JSON) Source: https://context7.com/thwbh/tauri-typegen/llms.txt Integrates TypeScript type generation into the npm/pnpm build workflow using `package.json` scripts. These scripts can be chained to ensure type generation precedes development or build commands, enabling type safety throughout the development lifecycle. ```json { "scripts": { "generate-types": "cargo tauri-typegen generate", "dev": "npm run generate-types && vite", "build": "npm run generate-types && tsc && vite build", "tauri:dev": "cargo tauri-typegen generate && tauri dev", "tauri:build": "cargo tauri-typegen generate && tauri build", "predev": "npm run generate-types", "prebuild": "npm run generate-types" }, "devDependencies": { "@tauri-apps/api": "^2.0.0", "zod": "^3.22.0", "typescript": "^5.3.0", "vite": "^5.0.0" } } ``` -------------------------------- ### TypeScript Configuration for Tauri TypeGen Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md This JSON configuration object specifies TypeScript compiler options necessary for compatibility with the code generated by tauri-typegen. It ensures proper module resolution, strict type checking, and support for modern JavaScript features. ```json { "compilerOptions": { "target": "ES2018", "module": "ESNext", "moduleResolution": "node", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true } } ``` -------------------------------- ### Configure Type Generation in Tauri Configuration (JSON) Source: https://context7.com/thwbh/tauri-typegen/llms.txt Configures TypeScript type generation directly within the `tauri.conf.json` file using build hooks and plugin options. This allows for fine-grained control over the generation process, including pathing, validation, and custom type mappings. ```json { "build": { "beforeDevCommand": "cargo tauri-typegen generate && npm run dev", "beforeBuildCommand": "cargo tauri-typegen generate && npm run build", "devUrl": "http://localhost:5173", "frontendDist": "../dist" }, "plugins": { "typegen": { "projectPath": "./src-tauri", "outputPath": "./src/generated", "validationLibrary": "zod", "verbose": true, "visualizeDeps": false, "includePrivate": false, "typeMappings": { "DateTime": "string", "Uuid": "string", "BigDecimal": "string" }, "excludePatterns": ["**/tests/**", "**/target/**"], "includePatterns": ["**/commands/**", "**/models/**"] } } } ``` -------------------------------- ### Generated Tauri Command Functions with Zod Validation Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Provides typed asynchronous functions for interacting with Tauri commands. It uses Zod schemas for validation and the `invoke` API from `@tauri-apps/api/core` to communicate with the backend. These functions ensure type safety and data integrity. ```typescript import { invoke } from '@tauri-apps/api/core'; import * as schemas from './schemas'; import type * as types from './types'; export async function createProduct(params: types.CreateProductParams): Promise { const validatedParams = schemas.CreateProductParamsSchema.parse(params); return invoke('create_product', validatedParams); } export async function getProducts(params: types.GetProductsParams): Promise { const validatedParams = schemas.GetProductsParamsSchema.parse(params); return invoke('get_products', validatedParams); } export async function deleteProduct(params: types.DeleteProductParams): Promise { const validatedParams = schemas.DeleteProductParamsSchema.parse(params); return invoke('delete_product', validatedParams); } ``` -------------------------------- ### Generated TypeScript Types for Tauri Commands Source: https://github.com/thwbh/tauri-typegen/blob/main/README.md Defines the TypeScript interfaces for data structures used in Tauri commands, such as products and requests. These types are essential for maintaining type safety between the frontend and backend. ```typescript export interface Product { id: number; name: string; description: string; price: number; inStock: boolean; categoryId: number; } export interface CreateProductRequest { name: string; description: string; price: number; categoryId: number; } export interface CreateProductParams { request: CreateProductRequest; } export interface GetProductsParams { filter?: ProductFilter | null; } export interface DeleteProductParams { id: number; } ```