feat(wasm): route E host effects for author-zero-JS frontend

Expand the official bridge with style/focus/list/navigate/storage/ws/
fetch_all/interval effects; relax the design rule to forbid only
author-written JS. Add browser-app demo and L1 list_html/dom_patch keys.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-04 09:06:21 +08:00
1 parent a9d30cdf4a
commit 8fbf617e05
18 files changed
+2543 -291

No files matched your search

+419 -78
View File
@@ -1,13 +1,11 @@
/**
* Canonical Marqdo browser bridge (route C/D). Host glue only — not app logic.
* Copied to site dirs by `marqdo wasm build`.
* Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic.
* Authors write .mq.md only; this file may grow host mechanisms freely.
*
* 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 + route D): set_text, set_value, set_attr, set_class,
* toggle_class, set_html (#trusted* only), fetch, after
* Mount: mount() / data-mq-* / #marqdo-boot auto-start (author zero JS)
* Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style,
* focus, blur, scroll_into, set_html, replace_children, render_list,
* navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval
*/
export function readCString(memory, ptr) {
@@ -73,42 +71,27 @@ function isPlainObject(v) {
return v != null && typeof v === "object" && !Array.isArray(v);
}
function asSelList(v) {
if (v == null) return [];
if (Array.isArray(v)) return v.map(String);
return [String(v)];
}
/** Normalize mount options from plain object or DOM dataset. */
export function normalizeMountOptions(raw = {}) {
const o = raw && typeof raw === "object" ? raw : {};
const dataset = o.dataset || {};
const wasmUrl =
o.wasmUrl ||
o.wasm ||
dataset.mqWasm ||
dataset.wasm ||
"./marqdo_wasm.wasm";
o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm";
const sourceUrl =
o.sourceUrl ||
o.source_url ||
dataset.mqSourceUrl ||
dataset.sourceUrl ||
"";
o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || "";
let source = o.source != null ? o.source : dataset.mqSource || "";
if (!source && typeof o.sourceInline === "string") source = o.sourceInline;
const playground =
o.playground ||
dataset.mqPlayground ||
dataset.playground ||
"";
const ready =
o.ready ||
o.readySel ||
dataset.mqReady ||
"";
const enable =
o.enable ||
dataset.mqEnable ||
"";
const playground = o.playground || dataset.mqPlayground || dataset.playground || "";
const ready = o.ready || o.readySel || dataset.mqReady || "";
const enable = o.enable || dataset.mqEnable || "";
const noBoot =
o.noBoot === true ||
dataset.mqNoBoot === "1" ||
dataset.mqNoBoot === "true";
o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true";
return {
wasmUrl: String(wasmUrl),
sourceUrl: sourceUrl ? String(sourceUrl) : "",
@@ -121,18 +104,13 @@ export function normalizeMountOptions(raw = {}) {
};
}
/**
* Collect mount configs from `#marqdo-boot` JSON and `script[data-mq-*]`.
* Pure DOM scan — safe to call once after DOM ready.
*/
export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) {
if (!doc) return [];
const out = [];
const bootEl = doc.getElementById("marqdo-boot");
if (bootEl) {
try {
const json = JSON.parse(bootEl.textContent || "{}");
out.push(normalizeMountOptions(json));
out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}")));
} catch (e) {
console.error("marqdo-boot JSON:", e);
}
@@ -143,10 +121,7 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu
for (const el of scripts) {
if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue;
const hasWork =
el.dataset.mqSourceUrl ||
el.dataset.mqSource ||
el.dataset.mqPlayground;
if (!hasWork && !el.dataset.mqWasm) continue;
el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground;
if (!hasWork) continue;
out.push(
normalizeMountOptions({
@@ -163,19 +138,27 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu
return out;
}
/** Build mq_call args from a DOM event + optional value_from selector. */
export function eventArgsFromDom(ev, valueFromSel) {
const t = ev && ev.target;
const args = {
event: ev && ev.type ? ev.type : "click",
};
const args = { event: ev && ev.type ? ev.type : "click" };
if (t && typeof t === "object") {
if ("value" in t && t.value != null) args.value = String(t.value);
if ("checked" in t) args.checked = !!t.checked;
if (t.id) args.id = String(t.id);
if (t.getAttribute) {
const did = t.getAttribute("data-id");
if (did != null) args.data_id = did;
}
if (typeof t.textContent === "string" && !("value" in t)) {
args.text = t.textContent;
}
if (ev.key != null) args.key = String(ev.key);
if (ev.code != null) args.code = String(ev.code);
}
if (ev && ev.type === "popstate") {
args.url = typeof location !== "undefined" ? location.href : "";
args.path = typeof location !== "undefined" ? location.pathname + location.search : "";
args.state = ev.state;
}
if (valueFromSel && typeof document !== "undefined") {
const src = document.querySelector(valueFromSel);
@@ -193,16 +176,64 @@ export function eventArgsFromDom(ev, valueFromSel) {
/* ignore */
}
const fields = {};
for (const [k, v] of new FormData(form)) {
fields[k] = String(v);
}
for (const [k, v] of new FormData(form)) fields[k] = String(v);
args.fields = fields;
}
}
return args;
}
/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */
function applyStyle(el, styleVal) {
if (typeof styleVal === "string") {
el.setAttribute("style", styleVal);
return;
}
if (isPlainObject(styleVal)) {
for (const [k, v] of Object.entries(styleVal)) {
if (v === null || v === false) el.style.removeProperty(k);
else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v));
}
}
}
export function renderListItems(spec) {
const tag = String(spec.tag || "li");
const items = Array.isArray(spec.items) ? spec.items : [];
return items
.map((it) => {
if (it == null) return "";
if (typeof it === "string" || typeof it === "number") {
return `<${tag}>${escapeHtml(String(it))}</${tag}>`;
}
if (!isPlainObject(it)) return "";
const text = it.text != null ? String(it.text) : it.html != null ? null : "";
const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : "";
let attrs = "";
if (isPlainObject(it.attrs)) {
for (const [k, v] of Object.entries(it.attrs)) {
if (v === null || v === false) continue;
attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`;
}
}
const inner = it.html != null ? String(it.html) : escapeHtml(text ?? "");
return `<${tag}${cls}${attrs}>${inner}</${tag}>`;
})
.join("");
}
function escapeHtml(s) {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function escapeAttr(s) {
return escapeHtml(s).replace(/'/g, "&#39;");
}
/** Sync DOM patches (E1/E2/E3 navigate is sync too). */
export function applyDomPatch(value) {
if (!value || typeof value !== "object") return;
if (typeof document === "undefined") return;
@@ -251,18 +282,66 @@ export function applyDomPatch(value) {
}
}
const setStyle = value.set_style || value.setStyle;
if (isPlainObject(setStyle)) {
for (const [sel, st] of Object.entries(setStyle)) {
const el = document.querySelector(sel);
if (el) applyStyle(el, st);
}
}
for (const sel of asSelList(value.focus)) {
const el = document.querySelector(sel);
if (el && el.focus) el.focus();
}
for (const sel of asSelList(value.blur)) {
const el = document.querySelector(sel);
if (el && el.blur) el.blur();
}
for (const sel of asSelList(value.scroll_into || value.scrollInto)) {
const el = document.querySelector(sel);
if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" });
}
const setHtml = value.set_html || value.setHtml;
if (isPlainObject(setHtml)) {
for (const [sel, html] of Object.entries(setHtml)) {
if (!String(sel).startsWith("#trusted")) continue;
const el = document.querySelector(sel);
if (el) el.innerHTML = String(html);
}
}
const replaceChildren = value.replace_children || value.replaceChildren;
if (isPlainObject(replaceChildren)) {
for (const [sel, html] of Object.entries(replaceChildren)) {
const el = document.querySelector(sel);
if (el) el.innerHTML = String(html);
}
}
const renderList = value.render_list || value.renderList;
if (isPlainObject(renderList)) {
for (const [sel, spec] of Object.entries(renderList)) {
const el = document.querySelector(sel);
if (!el || !isPlainObject(spec)) continue;
el.innerHTML = renderListItems(spec);
}
}
const nav = value.navigate;
if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") {
const url = String(nav.url);
if (nav.replace) history.replaceState(nav.state ?? null, "", url);
else history.pushState(nav.state ?? null, "", url);
}
}
const intervalHandles = new Map();
const wsHandles = new Map();
let wsSeq = 0;
/**
* Run sync DOM patches then schedule async effects (ADR 0003).
* Run sync DOM patches then schedule async effects.
*/
export function applyEffects(exports, value, { onError } = {}) {
applyDomPatch(value);
@@ -275,32 +354,64 @@ export function applyEffects(exports, value, { onError } = {}) {
tasks.push(runFetchEffect(exports, fetchSpec, onError));
}
const fetchAll = value.fetch_all || value.fetchAll;
if (fetchAll && typeof fetchAll === "object" && fetchAll.then) {
tasks.push(runFetchAllEffect(exports, fetchAll, onError));
}
const afterSpec = value.after;
if (afterSpec && typeof afterSpec === "object" && afterSpec.then) {
tasks.push(runAfterEffect(exports, afterSpec, onError));
}
const intervalSpec = value.interval;
if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) {
runIntervalEffect(exports, intervalSpec, onError);
}
const clearIv = value.clear_interval || value.clearInterval;
if (clearIv && typeof clearIv === "object") {
const id = String(clearIv.id || "default");
const h = intervalHandles.get(id);
if (h != null) {
clearInterval(h);
intervalHandles.delete(id);
}
}
const storageSpec = value.storage;
if (storageSpec && typeof storageSpec === "object" && storageSpec.op) {
tasks.push(runStorageEffect(exports, storageSpec, onError));
}
const wsSpec = value.ws;
if (wsSpec && typeof wsSpec === "object" && wsSpec.op) {
tasks.push(runWsEffect(exports, wsSpec, onError));
}
return Promise.all(tasks);
}
function buildFetchInit(spec) {
const method = (spec.method || "GET").toUpperCase();
const init = { method };
if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers };
if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") {
const fd = new FormData();
for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v));
init.body = fd;
} else if (spec.body != null && method !== "GET" && method !== "HEAD") {
init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body);
}
return init;
}
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 res = await fetch(String(spec.url), buildFetchInit(spec));
const body = await res.text();
const result = call(exports, thenFn, {
ok: res.ok,
status: res.status,
body,
});
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);
@@ -325,6 +436,34 @@ async function runFetchEffect(exports, spec, onError) {
}
}
async function runFetchAllEffect(exports, spec, onError) {
const thenFn = spec.then;
const reqs = Array.isArray(spec.requests) ? spec.requests : [];
try {
const results = await Promise.all(
reqs.map(async (r) => {
try {
const res = await fetch(String(r.url), buildFetchInit(r));
const body = await res.text();
return { ok: res.ok, status: res.status, body, url: String(r.url) };
} catch (e) {
return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") };
}
}),
);
const result = call(exports, thenFn, { ok: true, results });
if (!result.ok) {
if (onError) onError(result.error);
else console.error(result.error);
return;
}
await applyEffects(exports, result.value, { onError });
} catch (e) {
if (onError) onError(String(e));
else console.error(e);
}
}
function runAfterEffect(exports, spec, onError) {
const ms = Math.max(0, Number(spec.ms) || 0);
const thenFn = spec.then;
@@ -349,9 +488,182 @@ function runAfterEffect(exports, spec, onError) {
});
}
function runIntervalEffect(exports, spec, onError) {
const ms = Math.max(1, Number(spec.ms) || 1000);
const thenFn = spec.then;
const id = String(spec.id || "default");
if (intervalHandles.has(id)) {
clearInterval(intervalHandles.get(id));
intervalHandles.delete(id);
}
const handle = setInterval(() => {
try {
const result = call(exports, thenFn, { ok: true, id });
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);
}
}, ms);
intervalHandles.set(id, handle);
}
function storageStore(scope) {
if (typeof localStorage === "undefined") return null;
return scope === "session" ? sessionStorage : localStorage;
}
async function runStorageEffect(exports, spec, onError) {
const op = String(spec.op || "").toLowerCase();
const key = String(spec.key || "");
const store = storageStore(spec.scope || "local");
if (!store) {
if (onError) onError("storage unavailable");
return;
}
try {
if (op === "set") {
store.setItem(key, spec.value != null ? String(spec.value) : "");
if (spec.then) {
const result = call(exports, spec.then, { ok: true, op, key });
if (result.ok) await applyEffects(exports, result.value, { onError });
}
return;
}
if (op === "remove" || op === "delete") {
store.removeItem(key);
if (spec.then) {
const result = call(exports, spec.then, { ok: true, op, key });
if (result.ok) await applyEffects(exports, result.value, { onError });
}
return;
}
if (op === "get") {
const value = store.getItem(key);
if (spec.then) {
const result = call(exports, spec.then, {
ok: true,
op,
key,
value: value == null ? "" : value,
found: value != null,
});
if (!result.ok) {
if (onError) onError(result.error);
return;
}
await applyEffects(exports, result.value, { onError });
}
}
} catch (e) {
if (onError) onError(String(e));
else console.error(e);
}
}
function runWsEffect(exports, spec, onError) {
const op = String(spec.op || "").toLowerCase();
return new Promise((resolve) => {
try {
if (op === "open") {
if (typeof WebSocket === "undefined") {
if (onError) onError("WebSocket unavailable");
resolve();
return;
}
const id = String(spec.id || `ws${++wsSeq}`);
const sock = new WebSocket(String(spec.url));
wsHandles.set(id, sock);
sock.addEventListener("open", () => {
if (spec.then_open || spec.thenOpen) {
try {
const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id });
if (result.ok) applyEffects(exports, result.value, { onError });
} catch (e) {
if (onError) onError(String(e));
}
}
resolve();
});
sock.addEventListener("message", (ev) => {
const thenMsg = spec.then_message || spec.thenMessage;
if (!thenMsg) return;
try {
const result = call(exports, thenMsg, {
ok: true,
id,
data: typeof ev.data === "string" ? ev.data : String(ev.data),
});
if (result.ok) applyEffects(exports, result.value, { onError });
} catch (e) {
if (onError) onError(String(e));
}
});
sock.addEventListener("close", () => {
wsHandles.delete(id);
const thenClose = spec.then_close || spec.thenClose;
if (thenClose) {
try {
const result = call(exports, thenClose, { ok: true, id });
if (result.ok) applyEffects(exports, result.value, { onError });
} catch (e) {
if (onError) onError(String(e));
}
}
});
sock.addEventListener("error", () => {
const thenErr = spec.then_error || spec.thenError;
if (thenErr) {
try {
const result = call(exports, thenErr, { ok: false, id, error: "ws error" });
if (result.ok) applyEffects(exports, result.value, { onError });
} catch (e) {
if (onError) onError(String(e));
}
}
});
return;
}
if (op === "send") {
const id = String(spec.id || [...wsHandles.keys()][0] || "");
const sock = wsHandles.get(id);
if (sock && sock.readyState === WebSocket.OPEN) {
sock.send(spec.data != null ? String(spec.data) : "");
} else if (onError) onError(`ws send: no open socket ${id}`);
resolve();
return;
}
if (op === "close") {
const id = String(spec.id || [...wsHandles.keys()][0] || "");
const sock = wsHandles.get(id);
if (sock) sock.close();
wsHandles.delete(id);
resolve();
return;
}
resolve();
} catch (e) {
if (onError) onError(String(e));
resolve();
}
});
}
function bindTarget(sel) {
if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null;
if (sel === "document" || sel === "@document")
return typeof document !== "undefined" ? document : null;
return null;
}
/**
* Wire events from `# main` return value.
* Accepts a list of row maps, or `{ wire: [...] }`.
* Wire events from `# main` return value (list or `{ wire: [...] }`).
*/
export function wireEvents(exports, bootValue, { onError } = {}) {
let rows = [];
@@ -364,12 +676,47 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
const fn = row["调用"] || row.call || row.fn;
const valueFrom =
row["值选择器"] || row.value_from || row.valueFrom || row.from || "";
const delegate =
row["委托"] || row.delegate || row.delegation || "";
if (!sel || !fn) continue;
const nodes = document.querySelectorAll(sel);
nodes.forEach((node) => {
const special = bindTarget(sel);
const roots = special
? [special]
: typeof document !== "undefined"
? [...document.querySelectorAll(sel)]
: [];
roots.forEach((node) => {
node.addEventListener(ev, (domEv) => {
try {
if (delegate) {
const hit =
typeof domEv.target?.closest === "function"
? domEv.target.closest(delegate)
: null;
if (!hit || (node.contains && !node.contains(hit))) return;
}
if (
ev === "click" &&
typeof domEv.target?.closest === "function" &&
domEv.target.closest("a[href]")
) {
try {
domEv.preventDefault();
} catch (_) {
/* ignore */
}
}
const args = eventArgsFromDom(domEv, valueFrom);
if (delegate && domEv.target) {
const hit = domEv.target.closest?.(delegate);
if (hit?.getAttribute) {
const did = hit.getAttribute("data-id");
if (did != null) args.data_id = did;
if (hit.id) args.id = hit.id;
}
}
const result = call(exports, fn, args);
if (!result.ok) {
if (onError) onError(result.error);
@@ -459,10 +806,6 @@ function wirePlayground(exports, playgroundSpec, { onError } = {}) {
return 1;
}
/**
* One-shot: load wasm, boot session (or playground), wire events.
* @returns {{ exports, boot, wired }}
*/
export async function mount(rawOpts = {}) {
const opts = normalizeMountOptions(rawOpts);
const onError = (err) => markError(opts, err);
@@ -505,7 +848,6 @@ export async function mount(rawOpts = {}) {
throw new Error(result.error || "boot failed");
}
// If boot value is a map with effects alongside wire, apply them.
if (result.value && !Array.isArray(result.value)) {
await applyEffects(exports, result.value, { onError });
}
@@ -516,7 +858,6 @@ export async function mount(rawOpts = {}) {
return { exports, boot: result, wired: n };
}
/** Auto-mount from DOM configs (route D). */
export async function autoMount(doc) {
const configs = collectMountConfigs(doc);
const results = [];