diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ceff30..35b2bc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - **C2/C3**:`marqdo wasm build`;会话 `mq_boot`/`mq_call`;GFM wire 表 + `set_text` DOM 回写;[interact.html](examples/browser-hello/interact.html) 计数器示例。 - **C4**:[ADR 0003](doc/adr/0003-browser-async-effects.md) 效应表(`fetch` / `after`)+ bridge 续体;[fetch.html](examples/browser-hello/fetch.html)。 - **C5**:`release-wasm` 体积配置;`marqdo wasm build` 报告 KiB 并可选 `wasm-opt`;`run_source` bytecode 单测;会话仍为 tree。 +- **WASM 收口**:规范 `crates/marqdo-wasm/js/marqdo-bridge.js`;`wasm build` 同时拷贝 bridge;Node 冒烟 `tests/wasm`;`web.client_embed` / `网页.客户端挂载`;路线图标 Completed。 ### Fixed - **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。 diff --git a/README.md b/README.md index e452df1..c708846 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ marqdo catalog public -o .marqdo - **原生插件 ABI**:[`include/marqdo_abi.h`](include/marqdo_abi.h) · [ext-abi.md](doc/design/ext-abi.md);`plugins/{demo,agent,web,quantum}` - **用户静态站**:`public/` → `view output` → CI 发布 [gh-pages](https://cflmy.github.io/marqdo/) - **VS Code 扩展**:分支 **`vscode-extension`**(`main` 不跟踪源码;见 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md));Release 附带 `.vsix` -- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM 解释器](doc/adr/0002-browser-marqdo-wasm.md)(路线 C,实现中见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md)) +- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md) ### 如何使用最新 Marqdo(v0.3.1) diff --git a/crates/marqdo-wasm/js/marqdo-bridge.js b/crates/marqdo-wasm/js/marqdo-bridge.js new file mode 100644 index 0000000..f30a46e --- /dev/null +++ b/crates/marqdo-wasm/js/marqdo-bridge.js @@ -0,0 +1,204 @@ +/** + * Canonical Marqdo browser bridge (route C). Host glue only — not app logic. + * Copied to site dirs by `marqdo wasm build`. + * + * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version + * Packed results: u32le length + UTF-8 JSON { ok, stdout, error, value } + * + * Effects (ADR 0003): set_text, fetch, after + */ + +export function readCString(memory, ptr) { + const bytes = new Uint8Array(memory.buffer); + let end = ptr; + while (bytes[end] !== 0) end += 1; + return new TextDecoder().decode(bytes.subarray(ptr, end)); +} + +function decodePacked(exports, outPtr) { + if (!outPtr) throw new Error("null wasm result pointer"); + const view = new DataView(exports.memory.buffer); + const jsonLen = view.getUint32(outPtr, true); + const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen); + const text = new TextDecoder().decode(jsonBytes); + exports.mq_dealloc(outPtr, 4 + jsonLen); + return JSON.parse(text); +} + +function writeUtf8(exports, text) { + const encoded = new TextEncoder().encode(text); + const ptr = exports.mq_alloc(encoded.length || 1); + if (!ptr) throw new Error("mq_alloc failed"); + new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded); + return { ptr, len: encoded.length }; +} + +export function runSource(exports, source) { + const { ptr, len } = writeUtf8(exports, source); + const outPtr = exports.mq_run(ptr, len); + exports.mq_dealloc(ptr, len || 1); + return decodePacked(exports, outPtr); +} + +export function boot(exports, source) { + const { ptr, len } = writeUtf8(exports, source); + const outPtr = exports.mq_boot(ptr, len); + exports.mq_dealloc(ptr, len || 1); + return decodePacked(exports, outPtr); +} + +export function call(exports, name, argsObj = {}) { + const n = writeUtf8(exports, name); + const a = writeUtf8(exports, JSON.stringify(argsObj ?? {})); + const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len); + exports.mq_dealloc(n.ptr, n.len || 1); + exports.mq_dealloc(a.ptr, a.len || 1); + return decodePacked(exports, outPtr); +} + +export async function loadWasm(url = "./marqdo_wasm.wasm") { + const res = await fetch(url); + if (!res.ok) { + throw new Error( + `failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`, + ); + } + const { instance } = await WebAssembly.instantiateStreaming(res, {}); + return instance.exports; +} + +/** Apply C3/C4 return effects: set_text, fetch, after */ +export function applyDomPatch(value) { + if (!value || typeof value !== "object") return; + const setText = value.set_text || value.setText; + if (setText && typeof setText === "object") { + for (const [sel, text] of Object.entries(setText)) { + const el = document.querySelector(sel); + if (el) el.textContent = String(text); + } + } +} + +/** + * Run sync DOM patches then schedule async effects (ADR 0003). + */ +export function applyEffects(exports, value, { onError } = {}) { + applyDomPatch(value); + if (!value || typeof value !== "object") return Promise.resolve(); + + const tasks = []; + + const fetchSpec = value.fetch; + if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) { + tasks.push(runFetchEffect(exports, fetchSpec, onError)); + } + + const afterSpec = value.after; + if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { + tasks.push(runAfterEffect(exports, afterSpec, onError)); + } + + return Promise.all(tasks); +} + +async function runFetchEffect(exports, spec, onError) { + const thenFn = spec.then; + const method = (spec.method || "GET").toUpperCase(); + const init = { method }; + if (spec.headers && typeof spec.headers === "object") { + init.headers = spec.headers; + } + if (spec.body != null && method !== "GET" && method !== "HEAD") { + init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); + } + try { + const res = await fetch(String(spec.url), init); + const body = await res.text(); + const result = call(exports, thenFn, { + ok: res.ok, + status: res.status, + body, + }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + try { + const result = call(exports, thenFn, { + ok: false, + status: 0, + body: "", + error: String(e), + }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + else if (onError) onError(result.error); + } catch (e2) { + if (onError) onError(String(e2)); + else console.error(e2); + } + } +} + +function runAfterEffect(exports, spec, onError) { + const ms = Math.max(0, Number(spec.ms) || 0); + const thenFn = spec.then; + return new Promise((resolve) => { + setTimeout(() => { + try { + const result = call(exports, thenFn, { ok: true }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + resolve(); + return; + } + Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + resolve(); + } + }, ms); + }); +} + +/** + * Wire events from `# main` return value. + * Accepts a list of row maps, or `{ wire: [...] }`. + */ +export function wireEvents(exports, bootValue, { onError } = {}) { + let rows = []; + if (Array.isArray(bootValue)) rows = bootValue; + else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire; + + for (const row of rows) { + const sel = row["选择器"] || row.selector || row.sel; + const ev = row["事件"] || row.event || "click"; + const fn = row["调用"] || row.call || row.fn; + if (!sel || !fn) continue; + const nodes = document.querySelectorAll(sel); + nodes.forEach((node) => { + node.addEventListener(ev, () => { + try { + const result = call(exports, fn, { event: ev }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } + }); + }); + } + return rows.length; +} diff --git a/doc/design/browser-marqdo-wasm.md b/doc/design/browser-marqdo-wasm.md index bd2408b..16d1f0e 100644 --- a/doc/design/browser-marqdo-wasm.md +++ b/doc/design/browser-marqdo-wasm.md @@ -122,7 +122,7 @@ source: &str (+ optional import map) | 路径 | 角色 | |------|------| | `marqdo`(根) | 核心;feature-gate | -| `crates/marqdo-wasm` | `cdylib`:`mq_alloc` / `mq_dealloc` / `mq_run` / `mq_version`(长度前缀 JSON;**无** wasm-bindgen CLI) | +| `crates/marqdo-wasm` | `cdylib`:`mq_*` ABI + `js/marqdo-bridge.js` | | `ext/web` 或 `web/browser` | L1:`浏览器.运行` / `交互装配`(C3+) | | `examples/browser-hello/` | 静态页 + wasm 冒烟 | | `tests/browser/` 或金样脚本 | Node/wasmtime 跑 `run_source` 对齐 | @@ -229,11 +229,28 @@ Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不** | 层 | 负责 | |----|------| | 服务端 `plugins/web` | 路由、DB、会话、SSR HTML、样式/头/图装配 | -| 页面壳 | 输出时可选嵌入 `"** + ## images + `table` diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index f8b2025..a02db27 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -116,6 +116,15 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c **> web_page_head page=`self` table=`表`** +## 客户端挂载 + + `桥`="/static/marqdo-bridge.js" + +返回一段用于挂载浏览器 Marqdo(路线 C)的 HTML:加载官方 `marqdo-bridge.js` 模块。 +请先 `marqdo wasm build -o static`(或站点静态目录),并用 `头装配` 挂 `关系=module` 行; +业务 `.mq.md` 与 `wire`/`fetch` 效应见 [browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md)。 + +**""** + ## 图片装配 + `表` diff --git a/src/wasm_cli.rs b/src/wasm_cli.rs index 5706de6..7b8c3b6 100644 --- a/src/wasm_cli.rs +++ b/src/wasm_cli.rs @@ -1,11 +1,13 @@ -//! `marqdo wasm build` — compile `marqdo-wasm` and copy the `.wasm` artifact. +//! `marqdo wasm build` — compile `marqdo-wasm` and copy artifacts for the browser host. use std::path::{Path, PathBuf}; use std::process::Command; use anyhow::{bail, Context, Result}; -/// Build size-optimized wasm32 artifact and copy `marqdo_wasm.wasm` into `out_dir`. +/// Build size-optimized wasm32 artifact and copy into `out_dir`: +/// - `marqdo_wasm.wasm` +/// - `marqdo-bridge.js` (canonical host glue) pub fn build_wasm(out_dir: &Path) -> Result<()> { let status = Command::new("cargo") .args([ @@ -26,31 +28,70 @@ pub fn build_wasm(out_dir: &Path) -> Result<()> { let mut 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"); if let Some(optimized) = try_wasm_opt(&artifact)? { artifact = optimized; } - std::fs::copy(&artifact, &dest).with_context(|| { + let dest_wasm = out_dir.join("marqdo_wasm.wasm"); + std::fs::copy(&artifact, &dest_wasm).with_context(|| { format!( "copy {} → {}", artifact.display(), - dest.display() + dest_wasm.display() ) })?; - let bytes = std::fs::metadata(&dest) + let bytes = std::fs::metadata(&dest_wasm) .map(|m| m.len()) .unwrap_or(0); println!( "wrote {} ({:.1} KiB)", - dest.display(), + dest_wasm.display(), bytes as f64 / 1024.0 ); + + let bridge_src = find_bridge_js()?; + let dest_bridge = out_dir.join("marqdo-bridge.js"); + std::fs::copy(&bridge_src, &dest_bridge).with_context(|| { + format!( + "copy {} → {}", + bridge_src.display(), + dest_bridge.display() + ) + })?; + println!("wrote {}", dest_bridge.display()); Ok(()) } -/// Run `wasm-opt -Oz` when Binaryen is installed; returns path to optimized file. +fn find_bridge_js() -> Result { + let mut candidates = Vec::new(); + if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") { + candidates.push( + PathBuf::from(manifest).join("crates/marqdo-wasm/js/marqdo-bridge.js"), + ); + } + candidates.push(PathBuf::from("crates/marqdo-wasm/js/marqdo-bridge.js")); + // When running from installed binary, try next to current_exe ../../… + if let Ok(exe) = std::env::current_exe() { + if let Some(root) = exe.parent().and_then(|p| p.parent()).and_then(|p| p.parent()) { + candidates.push(root.join("crates/marqdo-wasm/js/marqdo-bridge.js")); + } + } + for c in &candidates { + if c.is_file() { + return Ok(c.clone()); + } + } + bail!( + "marqdo-bridge.js not found; tried: {}", + candidates + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join(", ") + ) +} + fn try_wasm_opt(input: &Path) -> Result> { let which = Command::new("wasm-opt").arg("--version").output(); let Ok(out) = which else { @@ -68,7 +109,6 @@ fn try_wasm_opt(input: &Path) -> Result> { .status() .context("wasm-opt spawn failed")?; if !status.success() { - // Retry without bulk-memory flag for older binaryen. let status2 = Command::new("wasm-opt") .args(["-Oz"]) .arg(input) diff --git a/tests/wasm/smoke.mjs b/tests/wasm/smoke.mjs new file mode 100644 index 0000000..0a64800 --- /dev/null +++ b/tests/wasm/smoke.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +/** + * WASM ABI smoke (C1/C3): boot counter.mq.md, call bump twice. + * Usage: node tests/wasm/smoke.mjs [path/to/marqdo_wasm.wasm] + */ +import fs from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const root = path.resolve(__dirname, "../.."); + +const wasmPath = + process.argv[2] || + path.join(root, "examples/browser-hello/marqdo_wasm.wasm"); +const srcPath = path.join(root, "examples/browser-hello/counter.mq.md"); + +if (!fs.existsSync(wasmPath)) { + console.error("missing wasm:", wasmPath); + console.error("build: marqdo wasm build -o examples/browser-hello"); + process.exit(2); +} + +const buf = fs.readFileSync(wasmPath); +const { instance } = await WebAssembly.instantiate(buf, {}); +const e = instance.exports; +const enc = new TextEncoder(); +const dec = new TextDecoder(); + +function pack(ptr) { + const len = new DataView(e.memory.buffer).getUint32(ptr, true); + const j = JSON.parse(dec.decode(new Uint8Array(e.memory.buffer, ptr + 4, len))); + e.mq_dealloc(ptr, 4 + len); + return j; +} + +function write(s) { + const b = enc.encode(s); + const p = e.mq_alloc(b.length || 1); + new Uint8Array(e.memory.buffer, p, b.length).set(b); + return { p, n: b.length }; +} + +function boot(source) { + const { p, n } = write(source); + const o = e.mq_boot(p, n); + e.mq_dealloc(p, n || 1); + return pack(o); +} + +function call(name, args) { + const a = write(name); + const b = write(JSON.stringify(args || {})); + const o = e.mq_call(a.p, a.n, b.p, b.n); + e.mq_dealloc(a.p, a.n || 1); + e.mq_dealloc(b.p, b.n || 1); + return pack(o); +} + +const source = fs.readFileSync(srcPath, "utf8"); +const b = boot(source); +if (!b.ok) { + console.error("boot failed", b.error); + process.exit(1); +} +if (!Array.isArray(b.value) || b.value.length < 1) { + console.error("expected wire list", b.value); + process.exit(1); +} +const c1 = call("bump", {}); +const c2 = call("bump", {}); +if (!c1.ok || !c2.ok) { + console.error("call failed", c1, c2); + process.exit(1); +} +if (c2.value?.set_text?.["#count"] !== "2") { + console.error("expected count 2, got", c2.value); + process.exit(1); +} +console.log("wasm smoke ok"); diff --git a/tests/wasm_smoke.rs b/tests/wasm_smoke.rs new file mode 100644 index 0000000..ce3fe7f --- /dev/null +++ b/tests/wasm_smoke.rs @@ -0,0 +1,54 @@ +//! Browser WASM integration smoke (Node + wasm artifact). + +use std::path::PathBuf; +use std::process::Command; + +fn wasm_artifact() -> Option { + let mut cands = Vec::new(); + if let Ok(td) = std::env::var("CARGO_TARGET_DIR") { + cands.push(PathBuf::from(td).join("wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm")); + } + cands.push(PathBuf::from( + "target/wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm", + )); + cands.push(PathBuf::from("examples/browser-hello/marqdo_wasm.wasm")); + cands.into_iter().find(|p| p.is_file()) +} + +#[test] +fn wasm_node_abi_smoke() { + if Command::new("node").arg("--version").output().is_err() { + eprintln!("skip: node not installed"); + return; + } + let wasm = match wasm_artifact() { + Some(p) => p, + None => { + if std::env::var("MARQDO_WASM_SMOKE").ok().as_deref() != Some("1") { + eprintln!("skip: no wasm artifact (run `marqdo wasm build` or set MARQDO_WASM_SMOKE=1)"); + return; + } + let status = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["wasm", "build", "-o", "examples/browser-hello"]) + .status() + .expect("marqdo wasm build"); + assert!(status.success(), "marqdo wasm build failed"); + PathBuf::from("examples/browser-hello/marqdo_wasm.wasm") + } + }; + assert!(wasm.is_file(), "missing {}", wasm.display()); + let out = Command::new("node") + .args(["tests/wasm/smoke.mjs", wasm.to_str().unwrap()]) + .output() + .expect("node smoke"); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + out.status.success(), + "smoke failed: status={} stdout={} stderr={}", + out.status, + stdout, + stderr + ); + assert!(stdout.contains("wasm smoke ok"), "stdout={stdout}"); +}