jsxbin-analyzer 1.0.0

Comprehensive code analyzer for JSX with dependency detection, API classification, and security scanning
Documentation
use crate::types::{ApiType, ApiUsage};
use jsxbin_parser::types::Token;
use log::{debug, trace};
use std::collections::HashMap;

/// Detects Adobe API usage in code
pub struct ApiDetector;

impl ApiDetector {
    /// Extract API usage from tokens
    pub fn extract_from_tokens(tokens: &[Token]) -> Vec<ApiUsage> {
        debug!("Extracting API usage from tokens");
        let mut apis: HashMap<String, (ApiType, usize)> = HashMap::new();

        Self::scan_tokens_for_apis(tokens, &mut apis);

        let result: Vec<ApiUsage> = apis
            .into_iter()
            .map(|(api_name, (api_type, count))| ApiUsage {
                api_name,
                api_type,
                count,
                locations: Vec::new(),
            })
            .collect();

        debug!("Found {} API usages", result.len());
        result
    }

    fn scan_tokens_for_apis(tokens: &[Token], apis: &mut HashMap<String, (ApiType, usize)>) {
        for token in tokens {
            match token {
                Token::Identifier(name) => {
                    if let Some(api_type) = Self::classify_api(name) {
                        trace!("Found API: {} ({:?})", name, api_type);
                        apis.entry(name.clone())
                            .and_modify(|(_, count)| *count += 1)
                            .or_insert((api_type, 1));
                    }
                }

                Token::MemberAccess { object, property, .. } => {
                    if let Token::Identifier(prop_name) = &*property.token {
                        if let Some(api_type) = Self::classify_api(prop_name) {
                            trace!("Found API (member): {}", prop_name);
                            apis.entry(prop_name.clone())
                                .and_modify(|(_, count)| *count += 1)
                                .or_insert((api_type, 1));
                        }
                    }
                }

                Token::FunctionCall { callee, .. } => {
                    if let Token::Identifier(func_name) = &*callee.token {
                        if let Some(api_type) = Self::classify_api(func_name) {
                            trace!("Found API (function call): {}", func_name);
                            apis.entry(func_name.clone())
                                .and_modify(|(_, count)| *count += 1)
                                .or_insert((api_type, 1));
                        }
                    }
                }

                _ => {}
            }
        }
    }

    /// Classify an identifier as an Adobe API
    fn classify_api(name: &str) -> Option<ApiType> {
        match name {
            // Document APIs
            "activeDocument"
            | "documents"
            | "open"
            | "close"
            | "save"
            | "export"
            | "importFile" => Some(ApiType::Document),

            // Layer APIs
            "artLayers"
            | "layers"
            | "layerSets"
            | "groupLayers"
            | "createLayer"
            | "deleteLayer"
            | "mergeDown" => Some(ApiType::Layer),

            // Selection APIs
            "selection"
            | "select"
            | "deselect"
            | "selectAll"
            | "invert"
            | "feather"
            | "expand"
            | "contract" => Some(ApiType::Selection),

            // Transform APIs
            "transform"
            | "scale"
            | "rotate"
            | "skew"
            | "flip"
            | "flipHorizontal"
            | "flipVertical" => Some(ApiType::Transform),

            // Effects/Filters
            "applyFilter"
            | "blur"
            | "sharpen"
            | "distort"
            | "stylize"
            | "render" => Some(ApiType::Effects),

            // Text APIs
            "textLayers"
            | "textRange"
            | "addText"
            | "textItem"
            | "font"
            | "fontSize" => Some(ApiType::Text),

            // Shape APIs
            "pathItems"
            | "paths"
            | "createPath"
            | "bezier"
            | "stroke"
            | "fill" => Some(ApiType::Shape),

            // Color APIs
            "color"
            | "colorModel"
            | "RGB"
            | "CMYK"
            | "setRGBColor"
            | "setCMYKColor" => Some(ApiType::Color),

            _ => None,
        }
    }

    /// Get all known Adobe APIs
    pub fn get_known_apis() -> Vec<&'static str> {
        vec![
            // Documents
            "activeDocument",
            "documents",
            "open",
            "close",
            "save",
            "export",
            "importFile",
            // Layers
            "artLayers",
            "layers",
            "layerSets",
            "groupLayers",
            "createLayer",
            "deleteLayer",
            "mergeDown",
            // Selection
            "selection",
            "select",
            "deselect",
            "selectAll",
            "invert",
            "feather",
            "expand",
            "contract",
            // Transform
            "transform",
            "scale",
            "rotate",
            "skew",
            "flip",
            "flipHorizontal",
            "flipVertical",
            // Effects
            "applyFilter",
            "blur",
            "sharpen",
            "distort",
            "stylize",
            "render",
            // Text
            "textLayers",
            "textRange",
            "addText",
            "textItem",
            "font",
            "fontSize",
            // Shapes
            "pathItems",
            "paths",
            "createPath",
            "bezier",
            "stroke",
            "fill",
            // Color
            "color",
            "colorModel",
            "RGB",
            "CMYK",
            "setRGBColor",
            "setCMYKColor",
        ]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_classify_document_api() {
        assert_eq!(
            ApiDetector::classify_api("activeDocument"),
            Some(ApiType::Document)
        );
        assert_eq!(ApiDetector::classify_api("save"), Some(ApiType::Document));
    }

    #[test]
    fn test_classify_layer_api() {
        assert_eq!(
            ApiDetector::classify_api("artLayers"),
            Some(ApiType::Layer)
        );
    }

    #[test]
    fn test_unknown_api() {
        assert_eq!(ApiDetector::classify_api("unknownFunction"), None);
    }

    #[test]
    fn test_extract_from_tokens() {
        let tokens = vec![
            Token::Identifier("activeDocument".to_string()),
            Token::Identifier("selection".to_string()),
            Token::Identifier("activeDocument".to_string()),
        ];

        let apis = ApiDetector::extract_from_tokens(&tokens);
        assert!(apis.len() >= 2);

        let active_doc = apis.iter().find(|a| a.api_name == "activeDocument");
        assert!(active_doc.is_some());
        assert_eq!(active_doc.unwrap().count, 2);
    }
}