microsoft-webui-parser 0.0.20

Core parser for WebUI framework
Documentation
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Parser plugin trait and built-in plugin implementations.
//!
//! The plugin system is framework-aware but phase-local — parser plugins
//! classify framework-owned attributes, capture plugin-facing component templates,
//! and emit per-element hydration metadata for the handler.

pub mod fast;
pub mod fast_v2;
pub mod fast_v3;
pub mod webui;

use crate::component_registry::Component;
use crate::{ParserOptions, Result};

/// Parser-owned decision about how an attribute should be handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttributeAction {
    /// Let the parser process the attribute normally.
    Keep,
    /// Skip the attribute without incrementing the element binding count.
    Skip,
    /// Skip the attribute and count it as a dynamic binding.
    SkipAndCountBinding,
}

/// Build artifacts extracted from a parser plugin after parsing completes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParserPluginArtifacts {
    /// The plugin did not produce any post-parse artifacts.
    None,
    /// Client component templates keyed by tag name.
    ComponentTemplates(Vec<ComponentTemplateArtifact>),
}

/// State surface a component consumes through one hydration channel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StateSurface {
    /// The component is known not to consume state through this channel.
    None,
    /// The component consumes only these sorted, deduplicated keys.
    Keys(Vec<String>),
    /// The complete surface is unknown, so callers must preserve full state.
    All,
}

impl StateSurface {
    /// Create an exact keyed surface, collapsing an empty list to [`Self::None`].
    #[must_use]
    pub fn keys(mut keys: Vec<String>) -> Self {
        keys.sort_unstable();
        keys.dedup();
        if keys.is_empty() {
            Self::None
        } else {
            Self::Keys(keys)
        }
    }
}

/// Client template payload generated by a parser plugin for one component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentTemplateArtifact {
    /// Component custom-element tag name.
    pub tag_name: String,
    /// Non-WebUI plugin template payload, such as FAST `<f-template>` HTML.
    pub template: String,
    /// WebUI JSON-safe template metadata.
    pub template_json: String,
    /// WebUI component-local JavaScript condition closure array.
    pub template_functions: String,
    /// Initial hydration state surface derived by the producing plugin.
    pub hydration: StateSurface,
    /// Partial-navigation state surface derived by the producing plugin.
    pub navigation: StateSurface,
    /// Compiled template roots — the reactive property names referenced
    /// directly by the template (e.g. `{{name}}`) independent of any
    /// authored client script. Always populated (possibly empty), even when
    /// `hydration`/`navigation` collapse to [`StateSurface::All`], so a
    /// bundler-neutral manifest consumer can union exact client keys with
    /// these Rust-derived roots without re-deriving them.
    pub template_roots: Vec<String>,
    /// Whether this component has an authored client module (sibling script
    /// or an externally client-owned package), as opposed to a scriptless
    /// compiled template. Bundler manifest coverage validation only requires
    /// an entry for scripted components; scriptless ones are always
    /// Rust-derived and never require a manifest entry.
    pub is_scripted: bool,
}

impl ComponentTemplateArtifact {
    /// Create a non-WebUI template payload.
    #[must_use]
    pub fn template(tag_name: String, template: String) -> Self {
        Self {
            tag_name,
            template,
            template_json: String::new(),
            template_functions: String::new(),
            hydration: StateSurface::None,
            navigation: StateSurface::None,
            template_roots: Vec::new(),
            is_scripted: false,
        }
    }

    /// Create a WebUI split metadata/function payload.
    ///
    /// The hydration surface starts empty; the producing plugin attaches it with
    /// [`Self::with_hydration`] once it has derived the surface.
    #[must_use]
    pub fn webui(tag_name: String, template_json: String, template_functions: String) -> Self {
        Self {
            tag_name,
            template: String::new(),
            template_json,
            template_functions,
            hydration: StateSurface::None,
            navigation: StateSurface::None,
            template_roots: Vec::new(),
            is_scripted: false,
        }
    }

    /// Attach the initial hydration surface derived by the plugin.
    #[must_use]
    pub fn with_hydration(mut self, hydration: StateSurface) -> Self {
        self.hydration = hydration;
        self
    }

    /// Attach the partial-navigation surface derived by the plugin.
    #[must_use]
    pub fn with_navigation(mut self, navigation: StateSurface) -> Self {
        self.navigation = navigation;
        self
    }

    /// Attach the compiled template roots (see [`Self::template_roots`]).
    #[must_use]
    pub fn with_template_roots(mut self, roots: Vec<String>) -> Self {
        self.template_roots = roots;
        self
    }

    /// Mark whether this component has an authored client module.
    #[must_use]
    pub fn scripted(mut self, is_scripted: bool) -> Self {
        self.is_scripted = is_scripted;
        self
    }
}

/// A parser plugin that can customize template parsing behavior.
///
/// Plugins receive callbacks at key points during HTML parsing:
/// - **Fragment lifecycle**: `start_fragment` before a fragment parse begins
/// - **Component registration**: `register_component_template` when a plugin-facing component template is finalized
/// - **Attribute classification**: `classify_attribute` for framework-specific attrs
/// - **Element completion**: `finish_element` after attributes are processed
///
/// WebUI calls these hooks during parsing; plugins decide what (if anything) to do.
pub trait ParserPlugin {
    /// Called before parsing begins for a fragment.
    ///
    /// Plugins can use this to reset fragment-local counters while preserving
    /// global build-level state such as tracked component templates.
    fn start_fragment(&mut self, _fragment_id: &str) {}

    /// Called when parser output options change.
    fn configure(&mut self, _options: &ParserOptions) {}

    /// Called with the plugin-facing component template for the active CSS/DOM
    /// strategies. Authored root `<template>` attributes are preserved here;
    /// the SSR/internal parse view may strip runtime-only attributes.
    ///
    /// `component` identifies whether browser code owns the tag. Exact
    /// JavaScript state surfaces come from bundler projection metadata rather
    /// than parser-side source analysis.
    fn register_component_template(
        &mut self,
        tag_name: &str,
        component: &Component,
        processed_template: &str,
    ) -> Result<()>;

    /// Decide how a framework-owned attribute should be handled.
    fn classify_attribute(&mut self, attr_name: &str) -> AttributeAction;

    /// Called after all attributes on an element have been processed.
    /// `binding_attribute_count` is the number of dynamic attribute bindings found.
    /// Returns optional opaque bytes to emit as a `Plugin` protocol fragment.
    fn finish_element(&mut self, binding_attribute_count: u32) -> Option<Vec<u8>>;

    /// Consume the plugin and return any build artifacts it captured.
    ///
    /// # Errors
    ///
    /// Returns an error if the plugin encountered an invalid template construct
    /// while producing its artifacts (e.g. an invalid `@event` handler).
    fn into_artifacts(self: Box<Self>) -> Result<ParserPluginArtifacts> {
        Ok(ParserPluginArtifacts::None)
    }
}

#[cfg(test)]
mod artifact_tests {
    use super::{ComponentTemplateArtifact, StateSurface};

    #[test]
    fn template_constructor_starts_with_no_hydration_surface() {
        let artifact = ComponentTemplateArtifact::template("x-a".into(), "<p></p>".into());
        assert_eq!(artifact.tag_name, "x-a");
        assert_eq!(artifact.template, "<p></p>");
        assert!(artifact.template_json.is_empty());
        assert!(artifact.template_functions.is_empty());
        assert_eq!(artifact.hydration, StateSurface::None);
        assert_eq!(artifact.navigation, StateSurface::None);
    }

    #[test]
    fn webui_constructor_starts_with_no_hydration_surface() {
        let artifact =
            ComponentTemplateArtifact::webui("x-b".into(), "{\"j\":1}".into(), "[]".into());
        assert_eq!(artifact.tag_name, "x-b");
        assert!(artifact.template.is_empty());
        assert_eq!(artifact.template_json, "{\"j\":1}");
        assert_eq!(artifact.template_functions, "[]");
        assert_eq!(artifact.hydration, StateSurface::None);
        assert_eq!(artifact.navigation, StateSurface::None);
    }

    #[test]
    fn with_hydration_attaches_surface_fluently() {
        let artifact = ComponentTemplateArtifact::webui("x-c".into(), "{}".into(), "[]".into())
            .with_hydration(StateSurface::keys(vec!["count".into(), "name".into()]));
        assert_eq!(
            artifact.hydration,
            StateSurface::Keys(vec!["count".into(), "name".into()])
        );
    }

    #[test]
    fn with_hydration_is_plugin_agnostic_over_template_payloads() {
        // A non-WebUI plugin payload can carry its own hydration surface too.
        let artifact = ComponentTemplateArtifact::template("x-d".into(), "<f-t></f-t>".into())
            .with_hydration(StateSurface::keys(vec!["value".into()]));
        assert_eq!(artifact.template, "<f-t></f-t>");
        assert_eq!(artifact.hydration, StateSurface::Keys(vec!["value".into()]));
    }

    #[test]
    fn with_navigation_attaches_partial_state_surface() {
        let artifact = ComponentTemplateArtifact::webui("x-e".into(), "{}".into(), "[]".into())
            .with_navigation(StateSurface::keys(vec!["items".into(), "title".into()]));
        assert_eq!(
            artifact.navigation,
            StateSurface::Keys(vec!["items".into(), "title".into()])
        );
        assert_eq!(artifact.hydration, StateSurface::None);
    }
}