feat: ship the unique offline marqdo web Tool (WEB-02 candidate) #2

Merged
cflmy merged 1 commits from feature/web02-preview into main 2026-11-27 08:53:13 +08:00
12 changed files with 928 additions and 26 deletions

No files matched your search

+3 -26
View File
@@ -1,26 +1,3 @@
# Rust 构建与本地缓存 /target
/target/ /dist
/.cache/ /out
/dist/
/bin/
# 本地 tool bundle 与测试输出
**/*.analysis.json.tmp
**/*.ast.json.tmp
*.tmp
# 真实浏览器测试
/tests/browser/node_modules/
/tests/browser/artifacts/
/tests/browser/screenshots/
# Python 辅助脚本(CI/测试胶水)
__pycache__/
*.pyc
# 本地配置与编辑器
.env
.env.*
.cargo-home/
.DS_Store
*.swp
Generated
+114
View File
@@ -0,0 +1,114 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "marqdo-web-design"
version = "0.1.0"
source = "git+https://git.cflmy.cn/cflmy/marqdo-web-design?rev=2f18dede8540c82611819e2c24a19db138d5ac14#2f18dede8540c82611819e2c24a19db138d5ac14"
dependencies = [
"serde_json",
]
[[package]]
name = "marqdo-web-preview"
version = "0.1.0"
dependencies = [
"marqdo-web-design",
"serde_json",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "marqdo-web-preview"
version = "0.1.0"
edition = "2021"
rust-version = "1.89"
license = "MIT OR Apache-2.0"
description = "Offline Web design preview and the unique marqdo web Tool"
[dependencies]
marqdo-web-design = { git = "https://git.cflmy.cn/cflmy/marqdo-web-design", rev = "2f18dede8540c82611819e2c24a19db138d5ac14" }
serde_json = "1"
+8
View File
@@ -136,3 +136,11 @@ CSP、资产校验归本仓库;表头未识别、Link 精确绑定、`not_load
Analysis 字段或 resolver 公共合同缺陷归 CLI;作者面语义冲突或新增通用能力由 Analysis 字段或 resolver 公共合同缺陷归 CLI;作者面语义冲突或新增通用能力由
`marqdo-ext-web` 走 ADR 并配对 Design/Preview 候选。工单模板与状态流以 Web 领域规范 `marqdo-ext-web` 走 ADR 并配对 Design/Preview 候选。工单模板与状态流以 Web 领域规范
§12.2 与领域开发指南为准。 §12.2 与领域开发指南为准。
## 实现进展(WEB-02 首个候选)
- 独立 executable + `tool.json`,注册唯一 `marqdo web` 命令;消费固定 git revision 的 `marqdo-web-design` 公开 API(`Cargo.lock` 锁定),不复制 Markdown/设计解析。
- `web check|preview|handoff`:check 输出模型摘要;preview 生成离线单文件 HTML(CSP、原型标识、场景面板、模拟按钮、重置、构建摘要);handoff 原子写 Markdown 交付。
- 输出目录/文件默认不覆盖;staging→rename 原子发布;拒绝符号链接目标;退出码 0/1/2 与 stderr 诊断。
- `scripts/ci.sh` 用真实 CLI 安装/运行/卸载 `web` Tool 并验证 CLI 二进制不变。
- 未完成:真实浏览器行为与 responsive 验收、图片/本地 raster 资产、完整安全负例矩阵、超时/预算边界、WEB-05 冷安装。证据见 [docs/evidence/WEB-02-preview-candidate.md](docs/evidence/WEB-02-preview-candidate.md)。
+39
View File
@@ -0,0 +1,39 @@
# WEB-02 Preview 候选证据(离线制品 / 唯一 web Tool / 有限场景)
日期:2026-11-27。责任仓:`marqdo-web-preview`;工单:[marqdo-web-preview#1](https://git.cflmy.cn/cflmy/marqdo-web-preview/issues/1)(WEB-02);父工单:根 [marqdo#6](https://git.cflmy.cn/cflmy/marqdo/issues/6)。
本文件记录 WEB-02 的**首个候选**:唯一 `marqdo web` Tool 的 check/preview/handoff 入口、离线静态预览、有限场景、CSP 与原子发布。真实浏览器行为验收、资产复制与完整安全矩阵尚未完成,未在此声明。
## 输入身份
| 对象 | 身份 |
| --- | --- |
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,SHA-256 `sha256:6ede3b9e...` |
| Design 依赖 | `marqdo-web-design@2f18dede8540c82611819e2c24a19db138d5ac14`(`Cargo.lock` 固定 git rev;不是 `../design` 路径依赖) |
| 平台 | Linux x86_64(本机验证) |
## 执行
```sh
MARQDO_BIN=<verified marqdo> scripts/ci.sh
```
脚本真实执行:fmt/clippy → 构建 release → 生成 `tool.json` bundle → `marqdo tool install` → `marqdo web check/preview/handoff`(fixture 工程)→ 覆盖拒绝 → CLI 二进制 SHA 不变 → `tool remove web`。
## 已验证(PASS)
- **唯一入口**:`tool.json`(`command: web`)+ 独立 executable;`marqdo web check|preview|handoff ENTRY --unit ANCHOR [--root] [--out] [--theme]`。
- **离线制品**:`preview` 生成单个 `index.html`(不启动服务、无网络请求),`file://` 可打开;CSP `default-src 'none'; style-src/script-src sha256; img-src 'self'; connect-src 'none'; form-action 'none'; base-uri 'none'`。
- **有限场景**:Design 模型中的场景面板与交互按钮渲染为内联固定脚本(CSP hash 放行);点击仅切换预渲染面板,无定时器/网络/eval;含“重置原型”。
- **原型标识与摘要**:页首与摘要可见“原型 / 模拟”,列 root 与参与源 `sha256`;不显示完整 Analysis 或绝对路径。
- **安全渲染**:Design 的 `ContentBlock` 文本全部 HTML 转义;raw HTML 显示为 inert 文本;不输出 `href="javascript:`、无外部 script。
- **发布安全**:输出目录/文件必须不存在;staging 私有目录校验后原子 rename;失败清理;拒绝符号链接目标。
- **退出码**:设计错误 1、参数/环境/IO 错误 2、成功 0;诊断写 stderr。
- **Tool 生命周期**:真实 CLI `tool install` / 运行 / `tool remove web`;CLI 二进制 SHA 前后不变。
## 未验证 / 后续(不隐藏)
- 真实浏览器(Playwright/file://)行为、responsive 390px 无横向溢出、按钮实际状态切换的 DOM 断言未执行;当前只有静态制品断言。
- 图片/本地 raster 资产复制、魔数/大小校验、远端图片文本占位尚未实现(当前不渲染图片)。
- 完整安全负例矩阵(`</script>`/Unicode/双引号 fixture、输出预算边界、超时/进程限制)未系统性覆盖。
- 冷安装(root 生态 `web` Tool 与 WEB-05)未开始;WEB-04 生产交付试验未开始。
Executable
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# WEB-02 independent entry: real CLI, installed web Tool, offline artifact checks.
set -eu
: "${MARQDO_BIN:?set MARQDO_BIN to the verified marqdo executable}"
cd "$(dirname "$0")/.."
cargo fmt --all -- --check
cargo clippy --all-targets --locked -- -D warnings
scripts/package.sh
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
export MARQDO_TOOL_HOME="$work/tool-home"
cli_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
"$MARQDO_BIN" tool install "$PWD/dist/marqdo-web-preview/tool.json"
"$MARQDO_BIN" web check tests/fixture/index.mq.md --unit 工作台
preview="$work/preview"
"$MARQDO_BIN" web preview tests/fixture/index.mq.md --unit 工作台 --out "$preview" --theme light
test -f "$preview/index.html"
grep -q "Content-Security-Policy" "$preview/index.html"
grep -q "default-src 'none'" "$preview/index.html"
grep -q "原型 / 模拟" "$preview/index.html"
grep -q "raw HTML as inert text" "$preview/index.html"
grep -q "模拟保存" "$preview/index.html"
grep -q "data-scenario" "$preview/index.html"
! grep -q "href=\"javascript:" "$preview/index.html"
! grep -q "<script src" "$preview/index.html"
handoff="$work/handoff.md"
"$MARQDO_BIN" web handoff tests/fixture/index.mq.md --unit 工作台 --out "$handoff"
test -s "$handoff"
grep -q "Design handoff" "$handoff"
if "$MARQDO_BIN" web preview tests/fixture/index.mq.md --unit 工作台 --out "$preview" 2>/dev/null; then
echo "preview overwrote an existing directory" >&2
exit 1
fi
cli_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
test "$cli_before" = "$cli_after"
"$MARQDO_BIN" tool remove web
echo "PASS: marqdo web Tool check/preview/handoff/remove"
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# Build the installable marqdo web Tool bundle.
set -eu
cd "$(dirname "$0")/.."
cargo build --release --locked
dist="$PWD/dist/marqdo-web-preview"
rm -rf "$dist"
mkdir -p "$dist/bin"
cp target/release/marqdo-web-preview "$dist/bin/marqdo-web-preview"
chmod 0755 "$dist/bin/marqdo-web-preview"
cat > "$dist/tool.json" <<'JSON'
{
"schema": "marqdo.cli-tool",
"schema_version": 1,
"name": "cflmy.marqdo-web-preview",
"version": "0.1.0",
"command": "web",
"entrypoint": "bin/marqdo-web-preview",
"requires": {
"api_revision": 1,
"analysis": 3
}
}
JSON
echo "tool bundle: $dist"
+638
View File
@@ -0,0 +1,638 @@
//! `marqdo web` — the unique Web Tool: offline preview, check and handoff.
//!
//! The tool consumes only the public `marqdo-web-design` crate (fixed git
//! revision) and the CLI Analysis the design layer produces. It never parses
//! Markdown, never calls document `@exec` business functions, never opens the
//! network and never starts a server. Output is a static `file://` artifact with
//! a strict CSP, an inert prototype banner, escaped content and deterministic
//! staging→rename publication.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use marqdo_web_design::{
handoff, load, ComponentDef, ContentBlock, Design, Error, Instance, LoadConfig, Scenario, Width,
};
const CSS: &str = r#"
:root{color-scheme:light dark}
*{box-sizing:border-box}
body{margin:0;font-family:system-ui,-apple-system,"Noto Sans CJK SC",sans-serif;background:#f7f7f8;color:#1d1d1f}
body[data-theme="dark"]{background:#151517;color:#e8e8ea}
header{position:sticky;top:0;background:#fff8e1;color:#5b4500;border-bottom:1px solid #e0c56b;padding:.6rem 1rem;font-weight:600}
body[data-theme="dark"] header{background:#3a2f00;color:#ffe08a;border-color:#6b5600}
main{padding:1rem;max-width:1200px;margin:0 auto}
.component{border:1px dashed #b9b9c0;border-radius:8px;padding:.75rem;margin:.5rem 0;background:rgba(255,255,255,.6)}
body[data-theme="dark"] .component{background:rgba(255,255,255,.04);border-color:#4a4a52}
.grid{display:grid;gap:.75rem}
.content p,.content pre{margin:.4rem 0}
pre{overflow:auto;background:#f0f0f4;padding:.6rem;border-radius:6px;max-height:24rem}
body[data-theme="dark"] pre{background:#232329}
button{margin:.25rem .35rem .25rem 0;padding:.35rem .7rem;border-radius:6px;border:1px solid #888;background:#fff;cursor:pointer}
body[data-theme="dark"] button{background:#2a2a31;color:#eee;border-color:#666}
.badge{display:inline-block;font-size:.75rem;padding:.1rem .45rem;border-radius:999px;background:#ffe08a;color:#3a2f00;margin-right:.4rem}
.summary{font-size:.8rem;color:#555;margin-top:2rem;border-top:1px solid #ccc;padding-top:.75rem}
body[data-theme="dark"] .summary{color:#aaa;border-color:#444}
.hidden{display:none}
"#;
const SCRIPT: &str = r#"
(function(){
function setup(root){
var panels = root.querySelectorAll('[data-scenario-panel]');
function show(state){
panels.forEach(function(panel){
panel.classList.toggle('hidden', panel.getAttribute('data-scenario-panel') !== state);
});
root.setAttribute('data-current-state', state);
}
root.querySelectorAll('button[data-next]').forEach(function(button){
button.addEventListener('click', function(){
show(button.getAttribute('data-next'));
});
});
var reset = root.querySelector('button[data-reset]');
if(reset){ reset.addEventListener('click', function(){ show(root.getAttribute('data-initial-state')); }); }
}
document.querySelectorAll('[data-scenario]').forEach(setup);
})();
"#;
struct Args {
command: String,
entry: String,
unit: String,
root: Option<String>,
out: Option<String>,
theme: String,
}
fn parse_args() -> Result<Args, String> {
let mut argv = std::env::args().skip(1);
let Some(command) = argv.next() else {
return Err(
"usage: web <check|preview|handoff> ENTRY --unit ANCHOR [--root DIR] [--out PATH]"
.into(),
);
};
if !matches!(command.as_str(), "check" | "preview" | "handoff") {
return Err(format!(
"unknown web subcommand {command:?}; expected check|preview|handoff"
));
}
let mut entry = None;
let mut unit = None;
let mut root = None;
let mut out = None;
let mut theme = "light".to_string();
let mut rest: Vec<String> = argv.collect();
let mut index = 0;
while index < rest.len() {
let item = rest[index].clone();
match item.as_str() {
"--unit" => {
index += 1;
unit = rest.get(index).cloned();
}
"--root" => {
index += 1;
root = rest.get(index).cloned();
}
"--out" => {
index += 1;
out = rest.get(index).cloned();
}
"--theme" => {
index += 1;
theme = rest.get(index).cloned().unwrap_or_default();
}
other if other.starts_with("--") => {
return Err(format!("unknown option {other:?}"));
}
other => {
if entry.is_some() {
return Err("exactly one ENTRY is required".into());
}
entry = Some(other.to_string());
let _ = &mut rest;
}
}
index += 1;
}
if !matches!(theme.as_str(), "light" | "dark") {
return Err("--theme must be light or dark".into());
}
Ok(Args {
command,
entry: entry.ok_or("missing ENTRY")?,
unit: unit.ok_or("--unit ANCHOR is required")?,
root,
out,
theme,
})
}
fn hex_escape(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
other => out.push(other),
}
}
out
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in bytes.chunks(3) {
let mut value = 0u32;
for (index, byte) in chunk.iter().enumerate() {
value |= u32::from(*byte) << (16 - 8 * index);
}
out.push(ALPHABET[((value >> 18) & 63) as usize] as char);
out.push(ALPHABET[((value >> 12) & 63) as usize] as char);
out.push(if chunk.len() > 1 {
ALPHABET[((value >> 6) & 63) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
ALPHABET[(value & 63) as usize] as char
} else {
'='
});
}
out
}
fn csp_hash(content: &str) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// SHA-256 is required for CSP; use the design-independent tiny implementation.
sha256_b64(content.as_bytes()).unwrap_or_else(|| {
let mut hasher = DefaultHasher::new();
content.hash(&mut hasher);
format!("sha256-{}", hasher.finish())
})
}
fn sha256_b64(bytes: &[u8]) -> Option<String> {
// Minimal SHA-256; preview must not add dependencies beyond the Design crate.
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
let mut message = bytes.to_vec();
let bit_len = (bytes.len() as u64) * 8;
message.push(0x80);
while message.len() % 64 != 56 {
message.push(0);
}
message.extend_from_slice(&bit_len.to_be_bytes());
for chunk in message.chunks(64) {
let mut w = [0u32; 64];
for index in 0..16 {
w[index] = u32::from_be_bytes([
chunk[4 * index],
chunk[4 * index + 1],
chunk[4 * index + 2],
chunk[4 * index + 3],
]);
}
for index in 16..64 {
let s0 = w[index - 15].rotate_right(7)
^ w[index - 15].rotate_right(18)
^ (w[index - 15] >> 3);
let s1 = w[index - 2].rotate_right(17)
^ w[index - 2].rotate_right(19)
^ (w[index - 2] >> 10);
w[index] = w[index - 16]
.wrapping_add(s0)
.wrapping_add(w[index - 7])
.wrapping_add(s1);
}
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
(h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
for index in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let temp1 = hh
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[index])
.wrapping_add(w[index]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let temp2 = s0.wrapping_add(maj);
hh = g;
g = f;
f = e;
e = d.wrapping_add(temp1);
d = c;
c = b;
b = a;
a = temp1.wrapping_add(temp2);
}
h[0] = h[0].wrapping_add(a);
h[1] = h[1].wrapping_add(b);
h[2] = h[2].wrapping_add(c);
h[3] = h[3].wrapping_add(d);
h[4] = h[4].wrapping_add(e);
h[5] = h[5].wrapping_add(f);
h[6] = h[6].wrapping_add(g);
h[7] = h[7].wrapping_add(hh);
}
let mut digest = Vec::new();
for word in h {
digest.extend_from_slice(&word.to_be_bytes());
}
Some(base64(&digest))
}
fn render_blocks(blocks: &[ContentBlock]) -> String {
let mut out = String::new();
for block in blocks {
let text = hex_escape(&block.text);
match block.kind.as_str() {
"paragraph" => out.push_str(&format!("<p>{text}</p>\n")),
"heading" => out.push_str(&format!("<h3>{text}</h3>\n")),
"list" | "table" | "code" | "quote" => out.push_str(&format!("<pre>{text}</pre>\n")),
_ => out.push_str(&format!("<p class=\"inert\">{text}</p>\n")),
}
}
out
}
fn slot_columns(definition: &ComponentDef, row: u32) -> String {
definition
.slots
.iter()
.filter(|slot| slot.row == row)
.map(|slot| match slot.width {
Width::Auto => "minmax(0,auto)".to_string(),
Width::Fr(value) => format!("minmax(0,{value}fr)"),
Width::Px(value) => format!("minmax(0,{value}px)"),
})
.collect::<Vec<_>>()
.join(" ")
}
fn render_instance(
design: &Design,
instance: &Instance,
instance_by_id: &BTreeMap<String, &Instance>,
depth: usize,
) -> Result<String, String> {
if depth > 40 {
return Err("instance rendering depth exceeded".into());
}
let definition = design
.definitions
.get(&instance.definition)
.ok_or_else(|| format!("missing definition {}", instance.definition))?;
let mut out = format!(
"<section class=\"component\" data-instance=\"{}\">\n",
hex_escape(&instance.id)
);
out.push_str(&format!(
"<div class=\"source\"><span class=\"badge\">原型</span>{}#{} </div>\n",
hex_escape(&definition.source.path),
hex_escape(&definition.source.anchor)
));
if !definition.content.is_empty() {
out.push_str("<div class=\"content\">");
out.push_str(&render_blocks(&definition.content));
out.push_str("</div>\n");
}
let rows: Vec<u32> = {
let mut rows: Vec<u32> = definition.slots.iter().map(|slot| slot.row).collect();
rows.sort_unstable();
rows.dedup();
rows
};
for row in rows {
let columns = slot_columns(definition, row);
out.push_str(&format!(
"<div class=\"grid\" style=\"grid-template-columns:{columns}\">\n"
));
for slot in definition.slots.iter().filter(|slot| slot.row == row) {
let child_id = format!("{}/{}", instance.id, slot.slot);
let child = instance_by_id
.get(&child_id)
.ok_or_else(|| format!("missing child instance {child_id}"))?;
out.push_str(&render_instance(design, child, instance_by_id, depth + 1)?);
}
out.push_str("</div>\n");
}
if let Some(scenario_markup) = render_scenarios(instance, definition) {
out.push_str(&scenario_markup);
}
out.push_str("</section>\n");
Ok(out)
}
fn render_scenarios(instance: &Instance, definition: &ComponentDef) -> Option<String> {
if definition.scenarios.is_empty() {
return None;
}
let initial = definition
.scenarios
.iter()
.find(|scene| scene.initial)
.map(|scene| scene.state.clone())
.unwrap_or_default();
let mut out = format!(
"<div class=\"scenario\" data-scenario data-initial-state=\"{}\" data-current-state=\"{}\">\n",
hex_escape(&initial),
hex_escape(&initial)
);
for scene in &definition.scenarios {
let hidden = if scene.state == initial {
""
} else {
" hidden"
};
out.push_str(&format!(
"<div class=\"scenario-panel{hidden}\" data-scenario-panel=\"{}\">\n",
hex_escape(&scene.state)
));
out.push_str(&render_blocks(&scene.content_blocks));
for interaction in definition
.interactions
.iter()
.filter(|interaction| interaction.current == scene.state)
{
out.push_str(&format!(
"<button type=\"button\" data-next=\"{}\">模拟:{}</button>\n",
hex_escape(&interaction.next),
hex_escape(&interaction.event)
));
}
out.push_str("</div>\n");
}
out.push_str("<button type=\"button\" data-reset>重置原型</button>\n");
let _ = instance;
out.push_str("</div>\n");
Some(out)
}
fn render(design: &Design, theme: &str) -> Result<String, String> {
let mut instance_by_id: BTreeMap<String, &Instance> = BTreeMap::new();
for instance in &design.instances {
instance_by_id.insert(instance.id.clone(), instance);
}
let root = instance_by_id
.get("root")
.ok_or_else(|| "design has no root instance".to_string())?;
let mut body = render_instance(design, root, &instance_by_id, 0)?;
let mut summary =
String::from("<div class=\"summary\">\n<strong>本轮构建摘要</strong>\n<ul>\n");
summary.push_str(&format!("<li>root: {}</li>\n", hex_escape(&design.root)));
for source in &design.sources {
summary.push_str(&format!(
"<li>{} sha256:{}</li>\n",
hex_escape(&source.path),
hex_escape(&source.source_digest)
));
}
summary.push_str("</ul>\n<p>原型 / 模拟:不连接网络、不执行文档 @exec 业务函数、不代表生产站点。</p>\n</div>\n");
body.push_str(&summary);
let style_hash = csp_hash(CSS);
let script_hash = csp_hash(SCRIPT);
let csp = format!(
"default-src 'none'; style-src 'sha256-{style_hash}'; script-src 'sha256-{script_hash}'; img-src 'self'; connect-src 'none'; form-action 'none'; base-uri 'none'"
);
Ok(format!(
"<!DOCTYPE html>\n<html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\"><title>Marqdo Web 原型预览</title><style>{CSS}</style></head><body data-theme=\"{theme}\"><header>原型 / 模拟:本地离线预览,不连接网络,不代表生产站点</header><main>{body}</main><script>{SCRIPT}</script></body></html>\n"
))
}
fn diagnostic_text(error: &Error) -> (u8, String) {
let (code, diagnostics) = match error {
Error::Engine(items) => (2u8, items),
Error::Design(items) => (1u8, items),
};
let mut text = String::new();
for diagnostic in diagnostics {
text.push_str(&format!(
"{} [{:?}] {}",
diagnostic.code, diagnostic.severity, diagnostic.message
));
if let Some(path) = &diagnostic.path {
text.push_str(&format!(" at {path}"));
}
if let Some(span) = &diagnostic.span {
text.push_str(&format!(" [{}..{}]", span.start, span.end));
}
text.push('\n');
}
(code, text)
}
fn design_load(args: &Args) -> Result<Design, (u8, String)> {
let cli = std::env::var("MARQDO_BIN")
.map(PathBuf::from)
.map_err(|_| {
(
2u8,
"MARQDO_BIN must name the verified marqdo executable\n".to_string(),
)
})?;
let entry = PathBuf::from(&args.entry);
let root = args
.root
.clone()
.map(PathBuf::from)
.unwrap_or_else(|| entry.parent().unwrap_or(Path::new(".")).to_path_buf());
let config = LoadConfig::new(cli, entry, args.unit.clone(), root);
load(&config).map_err(|error| diagnostic_text(&error))
}
fn staging_for(out: &Path) -> Result<PathBuf, String> {
let parent = out
.parent()
.ok_or_else(|| "output path has no parent".to_string())?;
if !parent.is_dir() {
return Err(format!(
"output parent is not a directory: {}",
parent.display()
));
}
if out.exists() {
return Err(format!("output already exists: {}", out.display()));
}
if out
.symlink_metadata()
.map(|meta| meta.file_type().is_symlink())
.unwrap_or(false)
{
return Err(format!("output is a symbolic link: {}", out.display()));
}
let staging = parent.join(format!(".web-staging-{}", std::process::id()));
if staging.exists() {
fs::remove_dir_all(&staging).map_err(|error| format!("cannot reset staging: {error}"))?;
}
fs::create_dir(&staging).map_err(|error| format!("cannot create staging: {error}"))?;
Ok(staging)
}
fn publish(staging: &Path, out: &Path) -> Result<(), String> {
fs::rename(staging, out).map_err(|error| format!("cannot publish artifact: {error}"))
}
fn run_check(args: &Args) -> ExitCode {
match design_load(args) {
Ok(design) => {
println!(
"design {} definitions={} instances={} sources={}",
design.root,
design.definitions.len(),
design.instances.len(),
design.sources.len()
);
ExitCode::SUCCESS
}
Err((code, text)) => {
eprint!("{text}");
ExitCode::from(code)
}
}
}
fn run_preview(args: &Args) -> ExitCode {
let Some(out) = &args.out else {
return ExitCode::from(2);
};
let design = match design_load(args) {
Ok(design) => design,
Err((code, text)) => {
eprint!("{text}");
return ExitCode::from(code);
}
};
let html = match render(&design, &args.theme) {
Ok(html) => html,
Err(error) => {
eprintln!("web preview: error: {error}");
return ExitCode::from(2);
}
};
if html.len() > 4 * 1024 * 1024 {
eprintln!("web preview: error: rendered HTML exceeds the 4 MiB budget");
return ExitCode::from(2);
}
let out = PathBuf::from(out);
let staging = match staging_for(&out) {
Ok(path) => path,
Err(error) => {
eprintln!("web preview: error: {error}");
return ExitCode::from(2);
}
};
if let Err(error) = fs::write(staging.join("index.html"), html) {
eprintln!("web preview: error: cannot write index.html: {error}");
let _ = fs::remove_dir_all(&staging);
return ExitCode::from(2);
}
if let Err(error) = publish(&staging, &out) {
eprintln!("web preview: error: {error}");
let _ = fs::remove_dir_all(&staging);
return ExitCode::from(2);
}
println!("preview {} (theme {})", out.display(), args.theme);
ExitCode::SUCCESS
}
fn run_handoff(args: &Args) -> ExitCode {
let Some(out) = &args.out else {
return ExitCode::from(2);
};
let design = match design_load(args) {
Ok(design) => design,
Err((code, text)) => {
eprint!("{text}");
return ExitCode::from(code);
}
};
let text = handoff(&design);
if text.len() > 4 * 1024 * 1024 {
eprintln!("web handoff: error: handoff exceeds the 4 MiB budget");
return ExitCode::from(2);
}
let out = PathBuf::from(out);
if let Some(parent) = out.parent() {
if !parent.as_os_str().is_empty() && !parent.is_dir() {
eprintln!("web handoff: error: output parent is not a directory");
return ExitCode::from(2);
}
}
if out.exists() {
eprintln!(
"web handoff: error: output already exists: {}",
out.display()
);
return ExitCode::from(2);
}
let staging = match staging_for(&out) {
Ok(path) => path,
Err(error) => {
eprintln!("web handoff: error: {error}");
return ExitCode::from(2);
}
};
let staging_file = staging.join("handoff.md");
if let Err(error) = fs::write(&staging_file, text) {
eprintln!("web handoff: error: cannot write handoff: {error}");
let _ = fs::remove_dir_all(&staging);
return ExitCode::from(2);
}
if let Err(error) = fs::rename(&staging_file, &out) {
eprintln!("web handoff: error: cannot publish handoff: {error}");
let _ = fs::remove_dir_all(&staging);
return ExitCode::from(2);
}
let _ = fs::remove_dir_all(&staging);
println!("handoff {}", out.display());
ExitCode::SUCCESS
}
fn main() -> ExitCode {
let args = match parse_args() {
Ok(args) => args,
Err(error) => {
eprintln!("web: {error}");
return ExitCode::from(2);
}
};
match args.command.as_str() {
"check" => run_check(&args),
"preview" => run_preview(&args),
"handoff" => run_handoff(&args),
_ => ExitCode::from(2),
}
}
#[allow(dead_code)]
fn _scenario_state(scenario: &Scenario) -> String {
scenario.state.clone()
}
+12
View File
@@ -0,0 +1,12 @@
# 导航组件
## @knowledge 导航
### 内容
- 首页
- 任务
### 验收
- 导航在窄屏下重排。
+16
View File
@@ -0,0 +1,16 @@
# 任务组件
## @knowledge 任务
### 场景
| 状态 | 内容 | 初始 |
| --- | --- | --- |
| empty | [空状态](../states.mq.md#空状态) | true |
| done | [完成](../states.mq.md#完成) | false |
### 交互
| 当前 | 事件 | 下一状态 |
| --- | --- | --- |
| empty | 模拟保存 | done |
+16
View File
@@ -0,0 +1,16 @@
# 科研原型
## @knowledge 工作台
面向研究人员的原型页面。访问 [项目说明](https://example.test/docs) 或 [危险](javascript:alert(1))。
### 内容
<div onerror="alert(1)">raw html 应显示为文本</div>
### 组件
| 行 | 槽 | 组件 | 宽度 |
| --- | --- | --- | --- |
| 1 | nav | [导航](components/nav.mq.md#导航) | 220px |
| 1 | main | [任务](components/tasks.mq.md#任务) | 1fr |
+9
View File
@@ -0,0 +1,9 @@
# 状态
## @knowledge 空状态
暂无任务。
## @knowledge 完成
任务已完成(模拟)。