feat(wasm): C2/C3 session boot, wire events, and interact demo

Add BrowserSession with shared entry env, mq_boot/mq_call exports,
marqdo wasm build, and a counter page driven only by counter.mq.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-01 10:48:46 +08:00
1 parent fb037022ba
commit aac896b044
17 files changed
+698 -168

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
//! In-memory browser / WASM session: boot `# main`, then call handlers with shared entry env.
use anyhow::{bail, Result};
use crate::ast::Module;
use crate::host::json::{json_to_value, value_to_json};
use crate::host::{HostCaps, HostContext};
use crate::interp::Interpreter;
use crate::load::load_module_from_source;
use crate::value::Value;
/// Persistent Marqdo program for the browser host bridge.
pub struct BrowserSession {
module: Module,
interp: Interpreter,
}
impl BrowserSession {
/// Parse source, run `# main`, keep entry bindings for later [`Self::call`].
pub fn boot(source: &str) -> Result<(Self, Value)> {
if source.trim().is_empty() {
bail!("source is empty");
}
let module = load_module_from_source(source)?;
let caps = HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
};
let mut host = HostContext::for_capture(None, caps);
host.set_entry_source(None, source);
host.sleep_limit_ms = Some(0);
let mut interp = Interpreter::with_capture(None, false).with_host(host);
let value = interp.run_module(&module)?;
Ok((Self { module, interp }, value))
}
/// Invoke `name` with optional JSON object of named args; updates entry bindings.
pub fn call(&mut self, name: &str, args_json: &str) -> Result<Value> {
let args = parse_named_args(args_json)?;
self.interp.captured_stdout.clear();
self.interp.invoke_in_entry(&self.module, name, &args)
}
pub fn take_stdout(&mut self) -> String {
std::mem::take(&mut self.interp.captured_stdout)
}
}
fn parse_named_args(args_json: &str) -> Result<Vec<(String, Value)>> {
let t = args_json.trim();
if t.is_empty() || t == "{}" || t == "null" {
return Ok(Vec::new());
}
let v: serde_json::Value =
serde_json::from_str(t).map_err(|e| anyhow::anyhow!("call args json: {e}"))?;
match v {
serde_json::Value::Object(map) => {
let mut out = Vec::new();
for (k, j) in map {
out.push((k, json_to_value(&j).map_err(|e| anyhow::anyhow!(e))?));
}
Ok(out)
}
serde_json::Value::Null => Ok(Vec::new()),
_ => bail!("call args must be a JSON object"),
}
}
/// Serialize a runtime [`Value`] to JSON (for WASM bridge responses).
pub fn value_as_json(v: &Value) -> Result<serde_json::Value, String> {
value_to_json(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn boot_and_call_share_count() {
let src = r##"---
import json:lib/json.mq.md
---
# main
*`count` = 0*
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#btn" | click | bump |
**`wire`**
## bump
*`count` = count + 1*
*`label` = > str count*
*`patch` = > json.set map=None key="#out" value=label*
**> json.set map=None key="set_text" value=patch**
"##;
let (mut sess, wire) = BrowserSession::boot(src).expect("boot");
assert!(matches!(wire, Value::List(_)), "wire={wire:?}");
let _v1 = sess.call("bump", "{}").expect("call1");
let v2 = sess.call("bump", "{}").expect("call2");
let j2 = value_as_json(&v2).unwrap();
assert_eq!(j2["set_text"]["#out"], "2");
}
}
+21
View File
@@ -151,6 +151,27 @@ impl Interpreter {
self.run_function(module, fun, Env::new(), args, false)
}
/// Call a function using (and updating) [`Self::entry_bindings`] from `# main`.
/// Used by browser WASM sessions so handlers share state with the entry object.
pub fn invoke_in_entry(
&mut self,
module: &Module,
name: &str,
args: &[(String, Value)],
) -> Result<Value> {
let fun = find_function_anywhere(module, name)
.ok_or_else(|| self.err(format!("unknown function `{name}`")))?;
let mut env = Env::new();
for (k, v) in &self.entry_bindings {
env.set(k.clone(), v.clone());
}
let prev = self.site_module;
self.site_module = Some(module as *const Module);
let result = self.run_function(module, fun, env, args, true);
self.site_module = prev;
result
}
pub fn run_module(&mut self, module: &Module) -> Result<Value> {
let prev = self.site_module;
self.site_module = Some(module as *const Module);
+5
View File
@@ -5,6 +5,7 @@
pub mod aliases;
pub mod ast;
pub mod browser_session;
pub mod builtin;
pub mod bytecode;
pub mod capture;
@@ -29,6 +30,8 @@ pub mod value;
pub mod version_check;
#[cfg(feature = "view")]
pub mod view;
#[cfg(feature = "cli")]
pub mod wasm_cli;
use std::path::Path;
@@ -42,6 +45,8 @@ use crate::interp::Interpreter;
use crate::lex::{classify_source, format_lines_dump};
use crate::load::{load_module, load_module_from_source};
pub use browser_session::{value_as_json, BrowserSession};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Backend {
#[default]
+21
View File
@@ -124,6 +124,11 @@ enum Commands {
#[arg(long)]
check: bool,
},
/// Build browser WASM artifact (route C)
Wasm {
#[command(subcommand)]
action: WasmAction,
},
}
#[derive(Subcommand, Debug)]
@@ -142,6 +147,16 @@ enum ExtAction {
},
}
#[derive(Subcommand, Debug)]
enum WasmAction {
/// `cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release` and copy `.wasm`
Build {
/// Destination directory (default: examples/browser-hello)
#[arg(short = 'o', long = "out", default_value = "examples/browser-hello")]
out: PathBuf,
},
}
#[derive(Subcommand, Debug)]
enum ViewAction {
/// Write static HTML documentation site
@@ -282,5 +297,11 @@ fn try_main() -> Result<i32> {
}
Ok(0)
}
Commands::Wasm { action } => match action {
WasmAction::Build { out } => {
marqdo::wasm_cli::build_wasm(&out)?;
Ok(0)
}
},
}
}
+65
View File
@@ -0,0 +1,65 @@
//! `marqdo wasm build` — compile `marqdo-wasm` and copy the `.wasm` artifact.
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{bail, Context, Result};
/// Build release wasm32 artifact and copy `marqdo_wasm.wasm` into `out_dir`.
pub fn build_wasm(out_dir: &Path) -> Result<()> {
let status = Command::new("cargo")
.args([
"build",
"-p",
"marqdo-wasm",
"--target",
"wasm32-unknown-unknown",
"--release",
])
.status()
.context("failed to spawn cargo (is it on PATH?)")?;
if !status.success() {
bail!("cargo build -p marqdo-wasm failed with {status}");
}
let artifact = find_wasm_artifact()?;
std::fs::create_dir_all(out_dir)
.with_context(|| format!("create {}", out_dir.display()))?;
let dest = out_dir.join("marqdo_wasm.wasm");
std::fs::copy(&artifact, &dest).with_context(|| {
format!(
"copy {} → {}",
artifact.display(),
dest.display()
)
})?;
println!("wrote {}", dest.display());
Ok(())
}
fn find_wasm_artifact() -> Result<PathBuf> {
let mut candidates = Vec::new();
if let Ok(td) = std::env::var("CARGO_TARGET_DIR") {
candidates.push(
PathBuf::from(td)
.join("wasm32-unknown-unknown/release/marqdo_wasm.wasm"),
);
}
candidates.push(PathBuf::from(
"target/wasm32-unknown-unknown/release/marqdo_wasm.wasm",
));
// Workspace may place target next to crates when invoked oddly — still try root.
for c in &candidates {
if c.is_file() {
return Ok(c.clone());
}
}
bail!(
"built wasm not found; tried: {}",
candidates
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
)
}