Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d591674aa | ||
|
|
e40d21760a | ||
|
|
2445c290c9 | ||
|
|
04890e0c73 | ||
|
|
ab52db2037 | ||
|
|
aac896b044 | ||
|
|
fb037022ba | ||
|
|
a75b7a1c87 | ||
|
|
f2fd4fb34e | ||
|
|
2079577314 | ||
|
|
416914a346 |
No files matched your search
@@ -0,0 +1,166 @@
|
||||
---
|
||||
name: marqdo-release
|
||||
description: >-
|
||||
Run a full Marqdo product release: detect latest version and ask the user for
|
||||
the next tag, update CHANGELOG/README/skills/public docs, bump Cargo versions,
|
||||
sync VS Code extension on branch vscode-extension when needed, build or
|
||||
trigger install assets (CLI, stdlib, ext, public zip, VSIX, wasm notes), push
|
||||
tag, publish GitHub Release with detailed notes, and recover from network
|
||||
failures via proxy. Use when the user asks to release, cut a version, publish
|
||||
vX.Y.Z, ship a GitHub release, 发版, 发布新版本, or tag marqdo.
|
||||
---
|
||||
|
||||
# Marqdo release
|
||||
|
||||
Canonical release playbook for **cflmy/marqdo**. Read this skill **before** tagging or uploading assets. Details: [reference.md](reference.md).
|
||||
|
||||
## Hard rules
|
||||
|
||||
1. **Never invent the next version.** Detect current versions → **stop and ask the user** for the next SemVer (`X.Y.Z`). Do not proceed until they confirm.
|
||||
2. **Never force-push** `main` / tags. **Never** `--no-verify` unless the user explicitly orders it.
|
||||
3. **Never commit `vscode-extension/` on `main`** (gitignored). Extension source lives only on branch **`vscode-extension`**. See `doc/design/vscode-extension-commit.md`.
|
||||
4. **Do not release from a dirty tree** (except intentional release commits you create in this flow).
|
||||
5. **Tag format** is always `vX.Y.Z` matching root `Cargo.toml` `version = "X.Y.Z"`.
|
||||
6. Prefer **tag push → GitHub Actions** (`.github/workflows/release.yml`) for Windows CLI + VSIX + zips. Local packaging is fallback / verification.
|
||||
7. After network errors: apply [reference.md § Proxy](reference.md); retry; do not silently skip uploads.
|
||||
|
||||
## Defaults (after version is confirmed)
|
||||
|
||||
Unless the user overrides, apply these automatically — **do not re-ask**:
|
||||
|
||||
| Setting | Default |
|
||||
|---------|---------|
|
||||
| Sync / bump `vscode-extension` to same `VER` | **yes** |
|
||||
| Push `main`, create annotated tag, push tag immediately (trigger CI) | **yes** |
|
||||
| Release notes language | **中英双语** (Chinese first, then English section, or paired ZH/EN under each heading) |
|
||||
| Skip VSIX | **no** |
|
||||
| Docs-only release | **no** (full asset pipeline via CI) |
|
||||
| Deploy gh-pages after release | **no** (only if user asks) |
|
||||
|
||||
Phase 0 asks **only** for the next version (and optional overrides). Example ask:
|
||||
|
||||
> 当前最新是 **vA.B.C**。请指定下一个版本号(如 `0.3.2`)。其余按默认:同步扩展、立刻打 tag 发布、中英双语说明。
|
||||
|
||||
## Phase 0 — Detect versions (mandatory stop)
|
||||
|
||||
Run in repo root (parallel OK):
|
||||
|
||||
```bash
|
||||
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
|
||||
# or: rg / git tag / gh release list — see reference.md
|
||||
```
|
||||
|
||||
Report briefly, then **ask only for the next SemVer** (defaults above). Wait for confirmation. Normalize to `VER=X.Y.Z` and `TAG=vX.Y.Z`.
|
||||
|
||||
## Phase 1 — Preflight
|
||||
|
||||
Copy and track:
|
||||
|
||||
```
|
||||
Release progress:
|
||||
- [ ] Phase 0: version confirmed by user (TAG=…)
|
||||
- [ ] Phase 1: preflight green
|
||||
- [ ] Phase 2: docs + version bumps committed
|
||||
- [ ] Phase 3: extension branch (if needed)
|
||||
- [ ] Phase 4: main pushed; tag created & pushed
|
||||
- [ ] Phase 5: CI / assets / release notes verified
|
||||
- [ ] Phase 6: post-release checks
|
||||
```
|
||||
|
||||
Checks:
|
||||
|
||||
1. `git status` clean or only release WIP you control.
|
||||
2. `git checkout main && git pull --ff-only origin main`.
|
||||
3. Quick gate: `cargo test --test gold structure_hello` (and any release-critical tests the user named). Full gold suite if time allows.
|
||||
4. `CHANGELOG.md` has meaningful **Unreleased** notes; if empty, draft from `git log vLAST..HEAD --oneline` and confirm with user.
|
||||
5. Confirm no secrets in the commit (`*.env`, credentials).
|
||||
|
||||
## Phase 2 — Docs & version bumps (main)
|
||||
|
||||
Bump **in lockstep**:
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `Cargo.toml` | `version = "VER"` |
|
||||
| `crates/marqdo-wasm/Cargo.toml` | same `VER` |
|
||||
| `CHANGELOG.md` | Move `## Unreleased` → `## vVER — YYYY-MM-DD`; leave fresh empty `## Unreleased` |
|
||||
| `README.md` | 「现状 / 如何使用最新」version strings, checkout tag, release URL |
|
||||
| `.cursor/skills/marqdo/SKILL.md` | Version-sensitive bullets if any (WASM/web status); keep rules accurate |
|
||||
| `public/**` | User-facing tutorials if features shipped (welcome, features/*, extensions). Prefer small factual updates over rewrites |
|
||||
| `doc/roadmap/*.md` | Mark shipped waves done if this release closes them |
|
||||
| `.github/workflows/release.yml` | Update **Highlights** body template to this release (CI still uses hardcoded blurb—keep in sync) |
|
||||
|
||||
Public HTML: regenerate before packaging / pages deploy:
|
||||
|
||||
```bash
|
||||
./scripts/build-public.sh
|
||||
# outputs under public/ (gitignored HTML); used by release zip / gh-pages
|
||||
```
|
||||
|
||||
Commit on `main` (HEREDOC message), e.g.:
|
||||
|
||||
```text
|
||||
release: vVER — <one-line highlight>
|
||||
|
||||
EOF
|
||||
```
|
||||
|
||||
Push `main`: `git push origin main` (with proxy/`all` perms if needed).
|
||||
|
||||
## Phase 3 — VS Code / Cursor extension
|
||||
|
||||
**Default: always** bump extension to `VER` on branch `vscode-extension` (skip only if user said so).
|
||||
|
||||
1. `git fetch origin vscode-extension`
|
||||
2. Work on `vscode-extension` branch (not main):
|
||||
- Bump `vscode-extension/package.json` `version` to `VER`.
|
||||
- Update `engines` / CLI version hints in extension README if present.
|
||||
- `npm ci && npm run compile`
|
||||
3. Commit & `git push origin vscode-extension`.
|
||||
4. Return to `main`. **Do not** add `vscode-extension/` to main.
|
||||
|
||||
## Phase 4 — Tag & trigger CI
|
||||
|
||||
```bash
|
||||
git tag -a "TAG" -m "TAG"
|
||||
git push origin "TAG"
|
||||
```
|
||||
|
||||
This runs `.github/workflows/release.yml` (Windows): CLI exe/zip, stdlib zip, ext zip, source zip, public zip, VSIX.
|
||||
|
||||
If tag push fails: [reference.md § Proxy](reference.md), retry once; then report.
|
||||
|
||||
## Phase 5 — Release notes & assets
|
||||
|
||||
1. Wait for Actions success: `gh run list --workflow=Release --limit 3` / open the run URL.
|
||||
2. Ensure GitHub Release for `TAG` exists with assets (workflow uses `softprops/action-gh-release`).
|
||||
3. **Rewrite release body** (workflow body is a stub) with **中英双语** — see [reference.md § Notes template](reference.md). `gh release edit TAG --notes-file …`.
|
||||
4. Include: Highlights, Breaking, Install (`ext add`, plugins build), Downloads table, WASM (`marqdo wasm build`), links to CHANGELOG/README, extension branch note.
|
||||
5. Optional Linux local extras (not required if CI green): `marqdo wasm build` smoke; document in notes that wasm is built from source via CLI.
|
||||
|
||||
Local Windows fallback: `scripts/release-full.ps1 -Tag TAG -Upload` (see script header).
|
||||
|
||||
## Phase 6 — Post-release
|
||||
|
||||
1. `gh release view TAG` — confirm assets + notes.
|
||||
2. `git status` clean; `main` synced.
|
||||
3. Tell user: release URL `https://github.com/cflmy/marqdo/releases/tag/TAG`.
|
||||
4. Optional: `./scripts/deploy-public.ps1` / pages workflow if user wants user-site refresh.
|
||||
5. Open fresh `## Unreleased` already done in Phase 2.
|
||||
|
||||
## Failure matrix (short)
|
||||
|
||||
| Failure | Action |
|
||||
|---------|--------|
|
||||
| `gh` / git TLS or proxy `7890` refused | Unset bad proxy; use working `HTTP(S)_PROXY` or `required_permissions: ["all"]`; see reference |
|
||||
| Tag exists | Stop; ask user to bump or delete tag (no force on shared tags without explicit order) |
|
||||
| CI red | Fix on main, move tag only if user explicitly allows delete+re-push tag |
|
||||
| VSIX missing | Fetch `vscode-extension`, build locally, `gh release upload TAG dist/*.vsix` |
|
||||
| Partial assets | Re-run workflow or upload missing files only |
|
||||
|
||||
## Do not
|
||||
|
||||
- Ship without user-confirmed version.
|
||||
- Hardcode release highlights only in Actions YAML and forget CHANGELOG.
|
||||
- Commit `target/`, `dist/`, `*.wasm`, or `public/**/*.html` unless project policy changes.
|
||||
- Merge extension tree into `main`.
|
||||
@@ -0,0 +1,305 @@
|
||||
# Marqdo release — reference
|
||||
|
||||
Companion to [SKILL.md](SKILL.md). Use during a release; keep SKILL short.
|
||||
|
||||
## Detect versions (commands)
|
||||
|
||||
```bash
|
||||
# From repo root
|
||||
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
|
||||
# or manually:
|
||||
git fetch --tags origin 2>/dev/null || true
|
||||
echo "Cargo: $(sed -n 's/^version = \"\(.*\)\"/\1/p' Cargo.toml | head -1)"
|
||||
echo "wasm: $(sed -n 's/^version = \"\(.*\)\"/\1/p' crates/marqdo-wasm/Cargo.toml | head -1)"
|
||||
echo "tags: $(git tag -l 'v*' --sort=-v:refname | head -3 | tr '\n' ' ')"
|
||||
gh release list --limit 3 2>/dev/null || true
|
||||
```
|
||||
|
||||
**SemVer guidance for the ask (do not choose for the user):**
|
||||
|
||||
| Kind | When |
|
||||
|------|------|
|
||||
| patch `x.y.(z+1)` | Fixes, docs, no public API / MQ surface break |
|
||||
| minor `x.(y+1).0` | New features (WASM route C, new ext APIs) backward compatible |
|
||||
| major `(x+1).0.0` | Breaking MQ / CLI / plugin ABI |
|
||||
|
||||
## Asset matrix (CI tag `v*`)
|
||||
|
||||
Produced by `.github/workflows/release.yml` on **windows-latest**:
|
||||
|
||||
| Asset | Role |
|
||||
|-------|------|
|
||||
| `marqdo-VER-x86_64-pc-windows-msvc.exe` | CLI (stdlib embedded) |
|
||||
| `marqdo-VER-x86_64-pc-windows-msvc.zip` | `marqdo.exe` + `lib/` |
|
||||
| `marqdo-VER-stdlib.zip` | `lib/` only |
|
||||
| `marqdo-VER-ext.zip` | Official `ext/` L1 |
|
||||
| `marqdo-VER-source.zip` | `git archive` of tagged commit |
|
||||
| `marqdo-VER.vsix` | VS Code / Cursor (from branch `vscode-extension`) |
|
||||
| `marqdo-VER-public.zip` | Static user docs (`marqdo view output public`) |
|
||||
|
||||
Not CI-uploaded (document in notes): Linux/macOS build from source; WASM via `marqdo wasm build` → `dist/wasm/`.
|
||||
|
||||
## Doc sync checklist (Phase 2 detail)
|
||||
|
||||
### CHANGELOG.md
|
||||
|
||||
1. Ensure `## Unreleased` lists everything shipping.
|
||||
2. Rename to `## vVER — YYYY-MM-DD` (use release day in Asia/Shanghai unless user says otherwise).
|
||||
3. Add a short **Highlights** subsection (install snippet + 3–6 bullets).
|
||||
4. Insert empty:
|
||||
|
||||
```markdown
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
```
|
||||
|
||||
### README.md
|
||||
|
||||
Update every user-visible version pin, typically:
|
||||
|
||||
- Section title `## 现状(vVER)`
|
||||
- `### 如何使用最新 Marqdo(vVER)`
|
||||
- `git checkout vVER`
|
||||
- Release URL `…/releases/tag/vVER`
|
||||
|
||||
Keep install / `ext add` / plugin build instructions accurate for this release.
|
||||
|
||||
### `.cursor/skills/marqdo/SKILL.md`
|
||||
|
||||
- Sync hard rules / feature bullets that this release changes (e.g. WASM, web).
|
||||
- Do **not** dump full CHANGELOG into the skill.
|
||||
- If release-only process changed, point to `.cursor/skills/marqdo-release/`.
|
||||
|
||||
### `public/` (author Markdown sources)
|
||||
|
||||
User tutorials under `public/` (not generated HTML). Update when:
|
||||
|
||||
- New CLI (`marqdo wasm …`, `ext add`, `version`)
|
||||
- New tutorials (browser hello, web client embed)
|
||||
- Version badges / “requires vVER” lines
|
||||
|
||||
Then regenerate HTML for zip/pages:
|
||||
|
||||
```bash
|
||||
./scripts/build-public.sh
|
||||
# Windows: powershell -File ./scripts/build-public.ps1
|
||||
```
|
||||
|
||||
HTML under `public/**/*.html` is typically gitignored — zip still ships from CI `marqdo view output public`.
|
||||
|
||||
### Workflow stub
|
||||
|
||||
Edit `.github/workflows/release.yml` `body:` **Highlights** so the first auto body matches this tag (agent still replaces with full notes via `gh release edit`).
|
||||
|
||||
### Roadmaps / ADRs
|
||||
|
||||
If this release closes a wave: set status Completed in `doc/roadmap/*`; leave ADRs immutable (link from CHANGELOG).
|
||||
|
||||
## Extension checklist (Phase 3 detail)
|
||||
|
||||
Branch policy: `doc/design/vscode-extension-commit.md`.
|
||||
|
||||
```bash
|
||||
git fetch origin vscode-extension
|
||||
git checkout vscode-extension
|
||||
# edit vscode-extension/package.json version → VER
|
||||
# npm ci && npm run compile
|
||||
git add vscode-extension/
|
||||
git commit -m "$(cat <<'EOF'
|
||||
vscode-extension: bump to VER for release
|
||||
|
||||
EOF
|
||||
)"
|
||||
git push origin vscode-extension
|
||||
git checkout main
|
||||
```
|
||||
|
||||
Local VSIX only (fallback):
|
||||
|
||||
```bash
|
||||
git fetch origin vscode-extension
|
||||
git checkout origin/vscode-extension -- vscode-extension
|
||||
(cd vscode-extension && npm ci && npm run compile && npx @vscode/vsce package --no-dependencies -o "../dist/marqdo-VER.vsix")
|
||||
# cleanup ignored tree if desired
|
||||
gh release upload "vVER" "dist/marqdo-VER.vsix" --clobber
|
||||
```
|
||||
|
||||
## Defaults (mirror of SKILL)
|
||||
|
||||
| Setting | Default |
|
||||
|---------|---------|
|
||||
| Sync `vscode-extension` to `VER` | yes |
|
||||
| Push main + annotated tag immediately | yes |
|
||||
| Release notes | 中英双语 |
|
||||
| Skip VSIX / docs-only / deploy pages | no |
|
||||
|
||||
Phase 0 asks **only** for the next version unless the user wants overrides.
|
||||
|
||||
## Notes template (中英双语 — default)
|
||||
|
||||
Save as `/tmp/marqdo-vVER-notes.md` then:
|
||||
|
||||
```bash
|
||||
gh release edit "vVER" --notes-file /tmp/marqdo-vVER-notes.md
|
||||
```
|
||||
|
||||
```markdown
|
||||
## Marqdo vVER
|
||||
|
||||
### 亮点 / Highlights
|
||||
|
||||
- **中文** … / **EN** …
|
||||
- …
|
||||
|
||||
### 安装 / Install
|
||||
|
||||
```bash
|
||||
git clone https://github.com/cflmy/marqdo.git && cd marqdo
|
||||
git checkout vVER
|
||||
cargo build --release
|
||||
./target/release/marqdo version
|
||||
|
||||
cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum
|
||||
marqdo ext add web && marqdo ext add agent && marqdo ext add quantum
|
||||
# 中文 id:网页 / 智能体 / 量子
|
||||
```
|
||||
|
||||
**浏览器 WASM / Browser WASM**
|
||||
|
||||
```bash
|
||||
marqdo wasm build
|
||||
# → dist/wasm/marqdo_wasm_bg.wasm + marqdo-bridge.js
|
||||
# examples: examples/browser-hello/
|
||||
```
|
||||
|
||||
### 破坏性变更 / Breaking changes
|
||||
|
||||
- 无 / None
|
||||
- …
|
||||
|
||||
### 下载 / Downloads
|
||||
|
||||
| Asset | 内容 / Contents |
|
||||
|-------|-----------------|
|
||||
| `marqdo-*-windows-msvc.exe` | CLI(内置 stdlib) |
|
||||
| `marqdo-*-windows-msvc.zip` | exe + `lib/` |
|
||||
| `marqdo-*-stdlib.zip` | 仅 `lib/` |
|
||||
| `marqdo-*-ext.zip` | 官方 `ext/` |
|
||||
| `marqdo-*-source.zip` | 源码快照 |
|
||||
| `marqdo-*.vsix` | VS Code / Cursor 扩展 |
|
||||
| `marqdo-*-public.zip` | 用户文档站 |
|
||||
|
||||
扩展源码分支 / Extension branch: **`vscode-extension`** ([policy](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md)).
|
||||
|
||||
### 链接 / Links
|
||||
|
||||
- [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md)
|
||||
- [README](https://github.com/cflmy/marqdo/blob/main/README.md)
|
||||
```
|
||||
|
||||
## Proxy & auth (network recovery)
|
||||
|
||||
Symptoms seen in this project: broken local proxy on `127.0.0.1:7890`, TLS failures, `gh` needing token, Cursor sandbox blocking git/gh.
|
||||
|
||||
### Diagnose
|
||||
|
||||
```bash
|
||||
env | grep -iE 'proxy|PROXY' || true
|
||||
curl -sI https://github.com | head -5
|
||||
gh auth status
|
||||
```
|
||||
|
||||
### Fix order
|
||||
|
||||
1. **Unset bad proxy** if connection refused:
|
||||
|
||||
```bash
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy
|
||||
```
|
||||
|
||||
2. **Set a working proxy** only if the user provides one (or known working):
|
||||
|
||||
```bash
|
||||
export HTTPS_PROXY=http://HOST:PORT
|
||||
export HTTP_PROXY=http://HOST:PORT
|
||||
```
|
||||
|
||||
3. **Agent Shell**: retry `git push` / `gh` with `required_permissions: ["all"]` (and `full_network` if needed).
|
||||
|
||||
4. **`gh` auth**: if `gh auth status` fails, ask user to `gh auth login` or set `GH_TOKEN` / `GITHUB_TOKEN` for the session — **never commit tokens**.
|
||||
|
||||
5. **Git remote**: prefer `https://github.com/cflmy/marqdo.git`; SSH needs keys.
|
||||
|
||||
6. **Partial upload**:
|
||||
|
||||
```bash
|
||||
gh release upload "vVER" dist/FILE --clobber
|
||||
```
|
||||
|
||||
7. **Re-run CI** without retagging (if tag already correct):
|
||||
|
||||
```bash
|
||||
gh workflow run Release --ref "vVER" # only if workflow_dispatch exists; else fix + new patch tag
|
||||
```
|
||||
|
||||
Current Release workflow is **tag-push only**. Red CI after tag → fix on `main`, then either new patch tag or **user-approved** delete+recreate tag (dangerous; prefer patch).
|
||||
|
||||
## Local Windows fallback
|
||||
|
||||
```powershell
|
||||
powershell -File ./scripts/release-full.ps1 -Tag vVER -Upload
|
||||
# -SkipVsix / -SkipPublic / -DeployPages as needed
|
||||
```
|
||||
|
||||
Also: `scripts/release-windows.ps1`, `scripts/publish-release.py` if present.
|
||||
|
||||
## Commit message style
|
||||
|
||||
```text
|
||||
release: vVER — <highlight>
|
||||
|
||||
```
|
||||
|
||||
Extension:
|
||||
|
||||
```text
|
||||
vscode-extension: bump to VER for release
|
||||
|
||||
```
|
||||
|
||||
## Pre-tag test suggestions
|
||||
|
||||
Minimum:
|
||||
|
||||
```bash
|
||||
cargo test --test gold structure_hello
|
||||
./target/release/marqdo version # after cargo build --release
|
||||
```
|
||||
|
||||
Stronger (time permitting):
|
||||
|
||||
```bash
|
||||
cargo test --test gold
|
||||
cargo test -p marqdo-wasm -- --nocapture # if wasm tests exist
|
||||
# optional Node: node tests/wasm/smoke.mjs after marqdo wasm build
|
||||
```
|
||||
|
||||
## Ask-user prompt (copy)
|
||||
|
||||
```text
|
||||
版本探测结果:
|
||||
- Cargo.toml: A.B.C
|
||||
- crates/marqdo-wasm: …
|
||||
- 最新 git tag: v…
|
||||
- 最新 GitHub Release: v…
|
||||
- CHANGELOG Unreleased: 有 / 无(摘要:…)
|
||||
|
||||
请指定下一个版本号(例如 0.3.2)。
|
||||
默认(无需确认):同步 vscode-extension 同号、立刻 push tag 发版、发布说明中英双语。
|
||||
若要改默认请一并说明。
|
||||
```
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Detect Marqdo version sources for release Phase 0. Never invent next SemVer."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# …/marqdo/.cursor/skills/marqdo-release/scripts/this.py → parents[4] = repo root
|
||||
ROOT = Path(__file__).resolve().parents[4]
|
||||
|
||||
|
||||
def cargo_version(path: Path) -> str | None:
|
||||
if not path.is_file():
|
||||
return None
|
||||
m = re.search(r'^version\s*=\s*"([^"]+)"', path.read_text(encoding="utf-8"), re.M)
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def run(cmd: list[str]) -> str:
|
||||
try:
|
||||
out = subprocess.check_output(cmd, cwd=ROOT, stderr=subprocess.DEVNULL, text=True)
|
||||
return out.strip()
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
return ""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
cargo = cargo_version(ROOT / "Cargo.toml")
|
||||
wasm = cargo_version(ROOT / "crates" / "marqdo-wasm" / "Cargo.toml")
|
||||
tags = run(["git", "tag", "-l", "v*", "--sort=-v:refname"])
|
||||
latest_tag = tags.splitlines()[0] if tags else "(none)"
|
||||
gh_list = run(["gh", "release", "list", "--limit", "3"])
|
||||
latest_gh = "(gh unavailable)"
|
||||
if gh_list:
|
||||
# first column is tag name for `gh release list`
|
||||
latest_gh = gh_list.splitlines()[0].split("\t")[0].strip()
|
||||
|
||||
changelog = ROOT / "CHANGELOG.md"
|
||||
unreleased = False
|
||||
unreleased_preview = ""
|
||||
if changelog.is_file():
|
||||
text = changelog.read_text(encoding="utf-8")
|
||||
m = re.search(r"^## Unreleased\s*\n(.*?)(?=^## |\Z)", text, re.M | re.S)
|
||||
if m:
|
||||
body = m.group(1).strip()
|
||||
# nonempty if any bullet or non-heading content beyond empty section headers
|
||||
content_lines = [
|
||||
ln
|
||||
for ln in body.splitlines()
|
||||
if ln.strip() and not re.match(r"^###\s+", ln.strip())
|
||||
]
|
||||
unreleased = bool(content_lines)
|
||||
unreleased_preview = " | ".join(content_lines[:3])[:200]
|
||||
|
||||
print("=== Marqdo version detect (do NOT invent next; ask the user) ===")
|
||||
print(f"repo: {ROOT}")
|
||||
print(f"Cargo.toml: {cargo or '(missing)'}")
|
||||
print(f"marqdo-wasm: {wasm or '(missing)'}")
|
||||
print(f"latest git tag: {latest_tag}")
|
||||
print(f"latest gh release: {latest_gh}")
|
||||
print(f"Unreleased notes: {'YES' if unreleased else 'NO/empty'}")
|
||||
if unreleased_preview:
|
||||
print(f"Unreleased peek: {unreleased_preview}")
|
||||
if cargo and latest_tag.lstrip("v") != cargo:
|
||||
print("WARN: Cargo version != latest tag (expected during pre-bump or lag)")
|
||||
if cargo and wasm and cargo != wasm:
|
||||
print("WARN: root Cargo.toml and marqdo-wasm versions differ — sync before release")
|
||||
print()
|
||||
print("ASK USER: next SemVer X.Y.Z (tag will be vX.Y.Z)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -16,6 +16,8 @@ Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation a
|
||||
|
||||
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
|
||||
|
||||
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
|
||||
|
||||
## Hard rules (do not violate)
|
||||
|
||||
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
|
||||
@@ -24,9 +26,10 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
|
||||
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return.
|
||||
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
|
||||
6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions).
|
||||
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed.
|
||||
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
|
||||
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
|
||||
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
|
||||
10. **Browser (route C):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); async I/O via return effects `fetch`/`after` ([ADR 0003](../../../doc/adr/0003-browser-async-effects.md)); official bridge is host glue only.
|
||||
|
||||
## Markup → meaning (v0.2)
|
||||
|
||||
@@ -154,6 +157,7 @@ Import **one language file** — never mix EN/ZH API names in the same `.mq.md`:
|
||||
|
||||
- Authors use **GFM tables + `#` classes** — no `json.parse` / `json.set` glue, no hand-built part JSON.
|
||||
- Table cells stay **literal strings**; path text like `` `posts`.`title` `` is resolved by web classes.
|
||||
- **Quote path/MIME cells** that contain `/` (T5 cell expressions treat bare `/` as division): `"/static/logo.svg"`, `"image/png"`.
|
||||
- **`ext/**` never calls `host_*`** — hot path is native `plugins/web` ABI.
|
||||
- HTTPS: terminate at reverse proxy; set `cookie_secure=True` on auth (no in-process TLS).
|
||||
|
||||
@@ -164,17 +168,18 @@ index.mq.md # entry + home page table + listen
|
||||
pages/ # sub-pages
|
||||
components/ # reusable |属性|值|样式| tables
|
||||
styles/ # CSS modules
|
||||
public/ # static + favicon.ico|png|svg
|
||||
db/ # schema + open/init
|
||||
data/ # sqlite runtime (gitignore)
|
||||
```
|
||||
|
||||
**Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`.
|
||||
|
||||
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.render` → `app` with `route` / `static` / `configure` / `listen`.
|
||||
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`.
|
||||
|
||||
**Shipped surface (W0–W7 + P3):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads.
|
||||
**Shipped surface (W0–W7 + P3 + W8):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`).
|
||||
|
||||
Design: [ext-web.md](../../doc/design/ext-web.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
|
||||
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
|
||||
|
||||
Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md).
|
||||
|
||||
|
||||
@@ -92,10 +92,10 @@ jobs:
|
||||
body: |
|
||||
## Marqdo ${{ github.ref_name }}
|
||||
|
||||
### Highlights — v0.3
|
||||
- **`ext/web`**: W0–W7 + P3 complete (sessions, cache, upload, WebSocket, style assembly); see marqdo-blog
|
||||
- **`ext/quantum`**: Q7 linalg + Q8 themed SVG viz
|
||||
- **`ext/agent`**: A1–A4 (OKF reuse, events, context budget, RAG/MCP fixtures)
|
||||
### 亮点 / Highlights — v0.3.2
|
||||
- **浏览器 Marqdo(路线 C)**:`marqdo wasm build`、官方 bridge、会话 ABI、`fetch`/`after` 效应;示例 `examples/browser-hello/`
|
||||
- **Browser Marqdo (route C)**: WASM build, official bridge, session ABI, async effects; see CHANGELOG
|
||||
- Fix: Admin 长内容布局 · `ext add` 原生插件预检 · `@keyframes` / 样式表比率引号约定
|
||||
- Install: `marqdo ext list` / `marqdo ext add llm|agent|web|quantum`
|
||||
- Native plugins: `cargo build --release -p marqdo_plugin_*` then `ext add`
|
||||
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [README](https://github.com/cflmy/marqdo/blob/main/README.md)
|
||||
|
||||
@@ -39,6 +39,10 @@ spike/.pytest_cache/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Built browser WASM (rebuild via crates/marqdo-wasm README)
|
||||
/examples/browser-hello/marqdo_wasm.wasm
|
||||
/examples/browser-hello/pkg/
|
||||
|
||||
# Local sqlite / scratch
|
||||
/data/
|
||||
/tmp/
|
||||
|
||||
@@ -2,6 +2,58 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
## v0.3.2 — 2026-09-01
|
||||
|
||||
### Highlights
|
||||
|
||||
**浏览器 Marqdo(路线 C)首版完备**:`wasm-core`、`marqdo wasm build`、会话 ABI、DOM/`fetch`/`after` 效应、官方 bridge、体积与冒烟;并修 Admin 长内容布局、`ext add` 原生插件预检、`@keyframes` 与样式表 `/` 比率约定。
|
||||
|
||||
```bash
|
||||
git checkout v0.3.2
|
||||
cargo build --release
|
||||
marqdo wasm build
|
||||
marqdo ext add web # 改插件后请重新 add
|
||||
```
|
||||
|
||||
### Added
|
||||
- **浏览器 Marqdo(路线 C)**: [ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [design](doc/design/browser-marqdo-wasm.md) · [roadmap C0–C5](doc/roadmap/browser-wasm.md)。
|
||||
- **C0/C1**:`wasm-core` feature 门控;`run_source`;crate `crates/marqdo-wasm`(`mq_run` ABI);示例 [examples/browser-hello](examples/browser-hello/)。
|
||||
- **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。
|
||||
- **发版 Skill**:`.cursor/skills/marqdo-release/`(探测版本 → 用户确认 → 文档/资产/扩展/Release 说明)。
|
||||
|
||||
### Fixed
|
||||
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
|
||||
- **`marqdo ext add`**:安装含原生插件的扩展时**先**定位/自动 `cargo build` 再拷贝 `.mq.md`,避免只装上文稿、运行时报 `native plugin not found`;扩大 `.so` 搜索路径。
|
||||
- **`web_style` / 样式装配**:正确输出 `@keyframes` 块(停点为嵌套规则,不再写成 `0%: opacity: 0`)。
|
||||
- **样式表含 `/` 的值**:文档明确**引号优先**(`"16/9"`、`"1/5"`);不引入靠空格消歧的表单元格比率折叠。
|
||||
|
||||
## v0.3.1 — 2026-08-29
|
||||
|
||||
### Highlights
|
||||
|
||||
**W8 站点资源**:favicon / Head 资源表 / 图片装配一次补齐;并修复相对入口路径下 `entry_dir` 双重拼接导致的嵌套目录问题。
|
||||
|
||||
```bash
|
||||
git checkout v0.3.1
|
||||
cargo build --release
|
||||
marqdo ext add web # 改插件后请重新 add
|
||||
```
|
||||
|
||||
### Added
|
||||
- **`ext/web` W8(站点图标 / Head / 图片装配)** ([web-assets-and-images.md](doc/design/web-assets-and-images.md)):`app.icons` / `应用.图标` 挂 `GET /favicon.ico`;`page.head` / `头装配`;`make_images` / `图片装配`;`meta` 认 `icon`/`favicon`/`apple-touch-icon`;`static` 约定 `favicon.*`;金样 `web-assets-smoke` / `web-assets-live`;[marqdo-blog](examples/marqdo-blog/) 接入。
|
||||
|
||||
### Fixed
|
||||
- **`host_query("entry_dir")`**:相对入口脚本(如 `tests/ext/….mq.md`)时对进程 cwd 绝对化,避免与 `for_run` 已设的脚本目录 cwd 再次拼接成 `tests/ext/tests/ext/…`。
|
||||
|
||||
## v0.3.0 — 2026-08-29
|
||||
|
||||
### Highlights
|
||||
|
||||
Generated
+9
-1
@@ -1018,7 +1018,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo"
|
||||
version = "0.3.0"
|
||||
version = "0.3.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
@@ -1040,6 +1040,14 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-wasm"
|
||||
version = "0.3.2"
|
||||
dependencies = [
|
||||
"marqdo",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo_plugin_agent"
|
||||
version = "0.1.0"
|
||||
|
||||
+41
-9
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "marqdo"
|
||||
version = "0.3.0"
|
||||
version = "0.3.2"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "Marqdo — Markdown markers as an interpreted programming language"
|
||||
@@ -10,25 +10,48 @@ repository = "https://github.com/cflmy/marqdo"
|
||||
[[bin]]
|
||||
name = "marqdo"
|
||||
path = "src/main.rs"
|
||||
required-features = ["cli"]
|
||||
|
||||
[features]
|
||||
default = ["native"]
|
||||
native = ["cli", "view", "net-host", "plugin-host", "exec-host", "fs-host", "tty"]
|
||||
cli = ["dep:clap"]
|
||||
view = ["dep:tiny_http"]
|
||||
net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize"]
|
||||
plugin-host = ["dep:libloading"]
|
||||
exec-host = []
|
||||
fs-host = []
|
||||
tty = ["dep:libc"]
|
||||
wasm-core = []
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
clap = { version = "=4.4.18", features = ["derive"] }
|
||||
clap = { version = "=4.4.18", features = ["derive"], optional = true }
|
||||
pulldown-cmark = "0.12"
|
||||
serde_json = "1"
|
||||
thiserror = "1"
|
||||
tiny_http = "0.12"
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
# Pin for Cargo/rustc 1.81 (newer rustls/idna/zeroize need edition2024).
|
||||
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"] }
|
||||
idna_adapter = "=1.1.0"
|
||||
zeroize = "=1.8.1"
|
||||
libloading = "=0.8.6"
|
||||
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"], optional = true }
|
||||
idna_adapter = { version = "=1.1.0", optional = true }
|
||||
zeroize = { version = "=1.8.1", optional = true }
|
||||
libloading = { version = "=0.8.6", optional = true }
|
||||
include_dir = "0.7"
|
||||
libc = "0.2"
|
||||
libc = { version = "0.2", optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# No `wasmbind`: keeps cdylib free of wasm-bindgen imports (raw mq_* ABI).
|
||||
chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] }
|
||||
|
||||
[workspace]
|
||||
members = ["plugins/demo", "plugins/agent", "plugins/web", "plugins/quantum"]
|
||||
members = [
|
||||
"plugins/demo",
|
||||
"plugins/agent",
|
||||
"plugins/web",
|
||||
"plugins/quantum",
|
||||
"crates/marqdo-wasm",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -37,3 +60,12 @@ predicates = "=3.1.0"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] }
|
||||
tokio-tungstenite = "0.24"
|
||||
futures-util = "0.3"
|
||||
|
||||
# Size-oriented profile for `marqdo-wasm` (C5). Use: cargo build -p marqdo-wasm --profile release-wasm --target wasm32-unknown-unknown
|
||||
[profile.release-wasm]
|
||||
inherits = "release"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
opt-level = "z"
|
||||
strip = true
|
||||
panic = "abort"
|
||||
@@ -99,7 +99,7 @@ marqdo catalog public -o .marqdo
|
||||
|
||||
---
|
||||
|
||||
## 现状(v0.3.0)
|
||||
## 现状(v0.3.2)
|
||||
|
||||
- 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/`
|
||||
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
|
||||
@@ -109,7 +109,7 @@ marqdo catalog public -o .marqdo
|
||||
- **`marqdo version --check`**:与 GitHub 最新 release 对比
|
||||
- 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**
|
||||
- **官方扩展库 `ext/`**(**非** stdlib,本版收口):
|
||||
- **`web`**:W0–W7 + P3 完结(会话 / 缓存 / 上传 / WebSocket / 样式装配等);示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)(反向代理 → 嵌入式 `listen`,非 Daphne/Uvicorn)
|
||||
- **`web`**:W0–W7 + P3 + **W8**(favicon / Head 资源 / 图片装配,见 [web-assets-and-images.md](doc/design/web-assets-and-images.md));示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)(反向代理 → 嵌入式 `listen`,非 Daphne/Uvicorn)
|
||||
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
|
||||
- **`agent`**:A1–A4(OKF 复用、过程事件、上下文预算、RAG/MCP fixture);下一波缺口 [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)
|
||||
- **`llm`**:OpenAI 兼容对话
|
||||
@@ -117,14 +117,15 @@ 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)
|
||||
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge;示例 [browser-hello](examples/browser-hello/);站点挂载 `web.client_embed` / `网页.客户端挂载`([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [ADR 0003](doc/adr/0003-browser-async-effects.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.0)
|
||||
### 如何使用最新 Marqdo(v0.3.2)
|
||||
|
||||
```bash
|
||||
# 1) 源码安装(跟 tag 或 main)
|
||||
git clone https://github.com/cflmy/marqdo.git && cd marqdo
|
||||
git checkout v0.3.0 # 或留在 main
|
||||
git checkout v0.3.2 # 或留在 main
|
||||
cargo build --release
|
||||
export PATH="$PWD/target/release:$PATH"
|
||||
marqdo version
|
||||
@@ -146,10 +147,14 @@ marqdo ext add llm # 或:大模型
|
||||
|
||||
# 4) 动态站示例(扩展装好后)
|
||||
marqdo run examples/marqdo-blog/index.mq.md
|
||||
# 浏览器打开终端打印的 listen 地址
|
||||
# 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8
|
||||
|
||||
# 5) Windows:也可从 GitHub Releases 下载 exe / zip / vsix
|
||||
# https://github.com/cflmy/marqdo/releases/tag/v0.3.0
|
||||
# 5) 浏览器 WASM(可选)
|
||||
marqdo wasm build
|
||||
# → dist/wasm/ … 见 examples/browser-hello/
|
||||
|
||||
# 6) Windows:也可从 GitHub Releases 下载 exe / zip / vsix
|
||||
# https://github.com/cflmy/marqdo/releases/tag/v0.3.2
|
||||
```
|
||||
|
||||
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "marqdo-wasm"
|
||||
version = "0.3.2"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
||||
repository = "https://github.com/cflmy/marqdo"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
marqdo = { path = "../..", default-features = false, features = ["wasm-core"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,21 @@
|
||||
# Marqdo browser WASM (route C)
|
||||
|
||||
Raw `cdylib` exports — no `wasm-bindgen` CLI required.
|
||||
|
||||
| Export | Role |
|
||||
|--------|------|
|
||||
| `mq_alloc` / `mq_dealloc` | linear memory |
|
||||
| `mq_run` | one-shot `# main` (C1) |
|
||||
| `mq_boot` / `mq_call` | session + handlers (C3) |
|
||||
| `mq_version` | version C string |
|
||||
|
||||
```bash
|
||||
# from repo root (C5 size profile)
|
||||
marqdo wasm build -o examples/browser-hello
|
||||
# or:
|
||||
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-wasm
|
||||
```
|
||||
|
||||
Prints size in KiB; runs `wasm-opt -Oz` when Binaryen is on `PATH`.
|
||||
|
||||
See [doc/design/browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md).
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Browser export surface for Marqdo (ADR 0002 / C1–C3).
|
||||
//!
|
||||
//! Raw `cdylib` ABI (no wasm-bindgen CLI):
|
||||
//! - `mq_alloc` / `mq_dealloc`
|
||||
//! - `mq_run` — one-shot `# main` (C1)
|
||||
//! - `mq_boot` — start session; return value often a `wire` table (C3)
|
||||
//! - `mq_call` — `(name_ptr, name_len, args_ptr, args_len) ->` JSON result (C3)
|
||||
//! - `mq_version`
|
||||
//!
|
||||
//! Packed results: little-endian `u32` length + UTF-8 JSON
|
||||
//! `{ ok, stdout, error, value }`.
|
||||
|
||||
use std::alloc::{alloc, dealloc, Layout};
|
||||
use std::cell::RefCell;
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
|
||||
use marqdo::{run_source, value_as_json, BrowserSession, RunOptions};
|
||||
use serde_json::json;
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<BrowserSession>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Allocate `size` bytes in WASM linear memory (alignment 1).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_alloc(size: usize) -> *mut u8 {
|
||||
if size == 0 {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
let layout = match Layout::from_size_align(size, 1) {
|
||||
Ok(l) => l,
|
||||
Err(_) => return ptr::null_mut(),
|
||||
};
|
||||
unsafe { alloc(layout) }
|
||||
}
|
||||
|
||||
/// Free a buffer previously returned by [`mq_alloc`], [`mq_run`], [`mq_boot`], or [`mq_call`].
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_dealloc(ptr: *mut u8, size: usize) {
|
||||
if ptr.is_null() || size == 0 {
|
||||
return;
|
||||
}
|
||||
let layout = match Layout::from_size_align(size, 1) {
|
||||
Ok(l) => l,
|
||||
Err(_) => return,
|
||||
};
|
||||
unsafe { dealloc(ptr, layout) }
|
||||
}
|
||||
|
||||
/// One-shot run (C1). Does not keep a session.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_run(ptr: *const u8, len: usize) -> *mut u8 {
|
||||
let source = match read_utf8(ptr, len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
pack_json(&run_to_json(&source))
|
||||
}
|
||||
|
||||
/// Boot a session: run `# main`, keep entry env. Replaces any prior session.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_boot(ptr: *const u8, len: usize) -> *mut u8 {
|
||||
let source = match read_utf8(ptr, len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
match BrowserSession::boot(&source) {
|
||||
Ok((sess, value)) => {
|
||||
let stdout = String::new();
|
||||
let value_json = match value_as_json(&value) {
|
||||
Ok(j) => j,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
SESSION.with(|s| *s.borrow_mut() = Some(sess));
|
||||
pack_json(&json!({
|
||||
"ok": true,
|
||||
"stdout": stdout,
|
||||
"error": null,
|
||||
"value": value_json,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
SESSION.with(|s| *s.borrow_mut() = None);
|
||||
pack_json(&err_json(&format!("{e:#}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Call a function in the current session.
|
||||
/// `args` is UTF-8 JSON object of named arguments (may be `{}`).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_call(
|
||||
name_ptr: *const u8,
|
||||
name_len: usize,
|
||||
args_ptr: *const u8,
|
||||
args_len: usize,
|
||||
) -> *mut u8 {
|
||||
let name = match read_utf8(name_ptr, name_len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
let args = match read_utf8(args_ptr, args_len) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
SESSION.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
let Some(sess) = guard.as_mut() else {
|
||||
return pack_json(&err_json("no session — call mq_boot first"));
|
||||
};
|
||||
match sess.call(&name, &args) {
|
||||
Ok(value) => {
|
||||
let stdout = sess.take_stdout();
|
||||
let value_json = match value_as_json(&value) {
|
||||
Ok(j) => j,
|
||||
Err(e) => return pack_json(&err_json(&e)),
|
||||
};
|
||||
pack_json(&json!({
|
||||
"ok": true,
|
||||
"stdout": stdout,
|
||||
"error": null,
|
||||
"value": value_json,
|
||||
}))
|
||||
}
|
||||
Err(e) => pack_json(&err_json(&format!("{e:#}"))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Package version (NUL-terminated C string in static memory — do not free).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_version() -> *const u8 {
|
||||
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr()
|
||||
}
|
||||
|
||||
fn read_utf8(ptr: *const u8, len: usize) -> Result<String, String> {
|
||||
if ptr.is_null() || len == 0 {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let bytes = unsafe { slice::from_raw_parts(ptr, len) };
|
||||
String::from_utf8(bytes.to_vec()).map_err(|e| format!("not utf-8: {e}"))
|
||||
}
|
||||
|
||||
fn run_to_json(source: &str) -> serde_json::Value {
|
||||
let mut opts = RunOptions::default();
|
||||
opts.allow_fs_write = false;
|
||||
opts.allow_exec = false;
|
||||
opts.allow_net = false;
|
||||
opts.sleep_limit_ms = Some(0);
|
||||
|
||||
match run_source(source, &opts) {
|
||||
Ok(cap) => match value_as_json(&cap.value) {
|
||||
Ok(value) => json!({
|
||||
"ok": true,
|
||||
"stdout": cap.stdout,
|
||||
"error": null,
|
||||
"value": value,
|
||||
}),
|
||||
Err(e) => err_json(&e),
|
||||
},
|
||||
Err(e) => err_json(&format!("{e:#}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn err_json(msg: &str) -> serde_json::Value {
|
||||
json!({
|
||||
"ok": false,
|
||||
"stdout": "",
|
||||
"error": msg,
|
||||
"value": null,
|
||||
})
|
||||
}
|
||||
|
||||
fn pack_json(v: &serde_json::Value) -> *mut u8 {
|
||||
let s = v.to_string();
|
||||
let bytes = s.as_bytes();
|
||||
let total = 4 + bytes.len();
|
||||
let out = mq_alloc(total);
|
||||
if out.is_null() {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
unsafe {
|
||||
let len = bytes.len() as u32;
|
||||
ptr::copy_nonoverlapping(len.to_le_bytes().as_ptr(), out, 4);
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), out.add(4), bytes.len());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_hello_json() {
|
||||
let v = run_to_json("# main\n\n> print text=Hello World!\n");
|
||||
assert_eq!(v["ok"], true);
|
||||
assert_eq!(v["stdout"], "Hello World!\n");
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@
|
||||
| [design/ext-agent-plan.md](design/ext-agent-plan.md) | **`## 多步` / `## plan` 锁定设计**(工作簿文件、subtask 执行、修订循环、`step` 默认写回) |
|
||||
| [design/ext-cli.md](design/ext-cli.md) | **`marqdo ext list/add/remove` 官方扩展安装器** |
|
||||
| [design/ext-web.md](design/ext-web.md) | **官方扩展 `ext/web`(页面/库表/绑定/后台;ABI + CLI;设计锁定)** |
|
||||
| [design/web-assets-and-images.md](design/web-assets-and-images.md) | **W8:favicon / Head 资源表 / 图片装配**(一次补齐) |
|
||||
| [design/web-asgi-servers-and-marqdo.md](design/web-asgi-servers-and-marqdo.md) | **Daphne/Uvicorn 等 vs Marqdo**:不能直接托管;反代 + axum `listen` |
|
||||
| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** |
|
||||
| [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** |
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# ADR 0002:浏览器内 Marqdo = WASM 解释器(路线 C)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted** |
|
||||
| 日期 | 2026-09-01 |
|
||||
| 决策者 | chaungming + 协作 |
|
||||
| 相关 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) · [interpreter.md](../roadmap/interpreter.md) · [0001](0001-implementation-language.md) |
|
||||
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
`ext/web` 已把站点装配成「源码以 `.mq.md` 为主、服务端 Rust 解释执行」。作者面仍缺**浏览器内**的同一语言:事件、局部状态、客户端 fetch/WS 回调今天要么手写 JS,要么完全不做。
|
||||
|
||||
候选路线:
|
||||
|
||||
| 代号 | 做法 |
|
||||
|------|------|
|
||||
| **A** | 服务端驱动 + 极薄固定增强(类 HTMX) |
|
||||
| **B** | 把 Marqdo **编译/翻译成 JavaScript** |
|
||||
| **C** | 把 **Rust 解释器/字节码 VM 编成 WASM**,浏览器跑同一套语义 |
|
||||
|
||||
产品叙事目标:**网络项目源码树可以只有 `.mq.md`**(JS/WASM 为生成或发行物,不是第二作者语言)。
|
||||
|
||||
---
|
||||
|
||||
## 决策
|
||||
|
||||
1. **选定路线 C**:浏览器内运行 **与主机同构的 Marqdo 语义**(parse → tree 和/或 bytecode VM),制品为 `marqdo.wasm` + 极薄 JS 宿主桥。
|
||||
2. **不选定 B 作为主路径**:翻译到 JS 易语义漂移,长期要维护两套后端;B 至多作实验,不替代 C。
|
||||
3. **A 不对立**:内容站 / SSR / 表单 POST 仍以服务端 `ext/web` 为主;C 负责「必须在客户端执行的 Marqdo」。
|
||||
4. **同一内核、两套宿主**:`server`(今日 CLI + axum 插件)与 `browser`(DOM / `fetch` / 定时器 / storage);**不是**把 axum、`plugins/web`、SQLite 服务端塞进浏览器。
|
||||
5. **另开设计与路线图**(见相关链接);实现按 **C0→C5** 切片,金样对齐主机行为。
|
||||
6. **与「编译 mq.md → WASM 机器码」区分**:本 ADR 是 **解释器/VM 上 WASM**;把 `.mq.md` 直接编译成独立 wasm 模块仍属 `interpreter.md` Phase III 可选项,**另案**,不替代本决策。
|
||||
|
||||
---
|
||||
|
||||
## 后果
|
||||
|
||||
- 核心库必须可 **feature-gate** 掉 `libloading` / `ureq` / `tiny_http` / TTY `libc` 等,以便 `wasm32-unknown-unknown` 链接。
|
||||
- 新增公共 API:`run_source`(内存源码 + 可选导入图),供 WASM 与测试共用。
|
||||
- 浏览器侧宿主 API 以表驱动「交互装配」暴露(对称于 `样式装配`);`ext/**` 仍不直接调 `host_*`。
|
||||
- 发行物可包含 `.wasm` / 生成的 loader;**作者仓库可不提交手写业务 JS**。
|
||||
- view 断点 / 静态文档站调试可复用同一 WASM 解释器(与 `next-phase.md` 所述一致)。
|
||||
|
||||
---
|
||||
|
||||
## 否决 / 非目标(本 ADR)
|
||||
|
||||
| 方案 / 目标 | 原因 |
|
||||
|-------------|------|
|
||||
| 以 B(编译到 JS)为主交付 | 语义双轨;与「一种语言」冲突 |
|
||||
| 浏览器内完整复刻 `plugins/web` 服务器 | 协议与权限模型不同;服务端仍 axum |
|
||||
| 浏览器 `dlopen` 原生插件 | WASM 无 POSIX 动态库模型 |
|
||||
| v1 消灭一切 JS 字节 | 胶水与发行 loader 允许存在;禁止的是**业务手写 JS** |
|
||||
| 用 Daphne/ASGI 托管 Marqdo | 已否决,见 [web-asgi-servers-and-marqdo.md](../design/web-asgi-servers-and-marqdo.md) |
|
||||
@@ -0,0 +1,48 @@
|
||||
# ADR 0003:浏览器异步 I/O(fetch / 定时)— 效应表 + 续体回调
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted** |
|
||||
| 日期 | 2026-09-01 |
|
||||
| 决策者 | chaungming + 协作 |
|
||||
| 相关 | [0002-browser-marqdo-wasm.md](0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) |
|
||||
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
Marqdo 调用面今日以**同步**为主。浏览器 `fetch` / `setTimeout` 是异步的;若在 WASM 里阻塞等待,会卡死 UI,且 `wasm32-unknown-unknown` 无真实阻塞 HTTP。
|
||||
|
||||
C3 已有:`mq_call` 返回 Map(如 `set_text`)由官方 bridge 执行。C4 在同一通道上扩展异步效应。
|
||||
|
||||
---
|
||||
|
||||
## 决策
|
||||
|
||||
1. **不**在语言内核引入 async/await 关键字或假同步 `fetch`。
|
||||
2. 处理器返回值可含**效应字段**(与 `set_text` 并列),由 **JS bridge** 执行:
|
||||
- `fetch`: `{ url, method?, then, headers?, body? }`
|
||||
- `after`: `{ ms, then }`(定时续体)
|
||||
3. 异步完成后 bridge 调用 `mq_call(then, payload)`:
|
||||
- fetch 成功/失败:`{ ok, status, body, error? }`
|
||||
- after:`{ ok: true }`
|
||||
4. 能力默认关网络语义仍由**返回效应**显式开启(站点作者主动返回 `fetch`);CORS / 鉴权仍是浏览器与服务端责任。
|
||||
5. 服务端 `lib/net` / `plugins/web` **不变**;本 ADR 仅浏览器 WASM 宿主。
|
||||
|
||||
---
|
||||
|
||||
## 后果
|
||||
|
||||
- 作者用表格/Map 声明「请求谁、完成后调谁」,无手写业务 JS。
|
||||
- Bridge 必须串行处理效应(先 `set_text`,再调度 `fetch`/`after`)。
|
||||
- 深层 Promise 链靠多次 `then` 回调;不在 C4 做通用 async 运行时。
|
||||
|
||||
---
|
||||
|
||||
## 否决
|
||||
|
||||
| 方案 | 原因 |
|
||||
|------|------|
|
||||
| WASM 内同步阻塞 `fetch` | 卡死主线程;平台不支持 |
|
||||
| 编译期把 Marqdo 译成 async JS | 回到路线 B |
|
||||
| 在核心加 `await` 关键字 | 违反 Markup-as-Syntax / 关键字纪律 |
|
||||
@@ -0,0 +1,310 @@
|
||||
# 浏览器 Marqdo(WASM 解释器)设计
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted(设计锁定)** · 实现见路线图 C0–C5 |
|
||||
| 日期 | 2026-09-01 |
|
||||
| ADR | [0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) |
|
||||
| 路线图 | [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) |
|
||||
| 相关 | [ext-web.md](ext-web.md) · [bytecode.md](bytecode.md) · [web-assets-and-images.md](web-assets-and-images.md) · [table-cell-expressions.md](table-cell-expressions.md) |
|
||||
|
||||
---
|
||||
|
||||
## 0. 一句话
|
||||
|
||||
**源码只有 `.mq.md`;浏览器跑与 CLI 同构的 Marqdo VM(WASM);JS 只做宿主桥与加载器,不做业务语言。**
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标与非目标
|
||||
|
||||
### 1.1 目标
|
||||
|
||||
| # | 目标 |
|
||||
|---|------|
|
||||
| G1 | 浏览器内执行合法 `.mq.md`(至少 `# main` + 打印/绑定/分支/循环/表/调用) |
|
||||
| G2 | 与主机 **tree**(及后续 **bytecode**)金样在共享子集上 stdout/返回值一致 |
|
||||
| G3 | 作者用 GFM 表声明交互(选择器 / 事件 / 调用),对称于 `样式装配` |
|
||||
| G4 | 仓库源码树可不含业务 `.js`;允许提交或由工具生成 `marqdo.wasm` + 官方 loader |
|
||||
| G5 | `import lib/…` 在浏览器可用(嵌入式 `lib/` 或打包进 wasm) |
|
||||
|
||||
### 1.2 非目标(本波 / C0–C3)
|
||||
|
||||
| # | 非目标 |
|
||||
|---|--------|
|
||||
| N1 | 在浏览器复刻 axum、`web_listen`、SQLite 服务端、admin UI |
|
||||
| N2 | `plugin.load` 加载原生 `.so` / 浏览器内 dlopen |
|
||||
| N3 | 把整站 `plugins/web` ABI 原样搬进 WASM |
|
||||
| N4 | 把 `.mq.md` 编译成独立机器码 WASM(异于「解释器上 WASM」) |
|
||||
| N5 | 强制内容站必须加载 WASM(纯 SSR 站可继续零客户端逻辑) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Page (HTML shell from ext/web SSR or static) │
|
||||
│ ┌──────────────┐ ┌─────────────────────────────────┐ │
|
||||
│ │ DOM / CSS │ │ Official JS loader (thin) │ │
|
||||
│ └──────▲───────┘ │ - WebAssembly.instantiate │ │
|
||||
│ │ bridge │ - marqdo_run_source / on_event │ │
|
||||
│ │ └──────────────┬──────────────────┘ │
|
||||
│ │ │ │
|
||||
│ │ ┌──────────▼──────────┐ │
|
||||
│ │ │ marqdo.wasm │ │
|
||||
│ │ │ parse → load → │ │
|
||||
│ └──────────────│ Interpreter | Vm │ │
|
||||
│ host_dom_* │ HostContext(browser)│ │
|
||||
│ host_fetch_* │ embedded lib/ │ │
|
||||
│ └─────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
|
||||
Server (unchanged):
|
||||
marqdo run / plugins/web (axum) — SSR, DB, auth, full site
|
||||
```
|
||||
|
||||
**原则:** 一套语言语义;**HostContext 分型**(`native` vs `browser`),不是两套语法。
|
||||
|
||||
---
|
||||
|
||||
## 3. 与现有流水线对齐
|
||||
|
||||
主机今日(见 `src/lib.rs`):
|
||||
|
||||
```
|
||||
path → fs::read → load_module → Interpreter|Vm → HostContext(native)
|
||||
```
|
||||
|
||||
浏览器目标:
|
||||
|
||||
```
|
||||
source: &str (+ optional import map)
|
||||
→ load_module_from_memory
|
||||
→ Interpreter|Vm (capture stdout)
|
||||
→ HostContext(browser caps)
|
||||
→ { ok, stdout, value_json, error }
|
||||
```
|
||||
|
||||
公共库 API(C0/C1 必须落地):
|
||||
|
||||
| API | 职责 |
|
||||
|-----|------|
|
||||
| `run_source(source, opts) -> Result<RunCapture>` | 无路径入口;cwd/fs_root 虚拟 |
|
||||
| `RunOptions` 浏览器默认 | `allow_fs_write=false`, `allow_exec=false`, `allow_net=false`(net 经显式 bridge 再开) |
|
||||
| `load` 导入 | `lib/**` → `embedded_lib`;用户模块 → JS 注入的 `HashMap<path, source>` |
|
||||
|
||||
后端优先级:
|
||||
|
||||
1. **C1:tree**(与默认 CLI 一致,调试简单)
|
||||
2. **C2+:bytecode** 可选(体积/性能;金样双后端)
|
||||
|
||||
---
|
||||
|
||||
## 4. Cargo / 制品布局
|
||||
|
||||
### 4.1 Feature 门(核心 crate `marqdo`)
|
||||
|
||||
| Feature | 默认(native) | `wasm-core` | 作用 |
|
||||
|---------|----------------|-------------|------|
|
||||
| `cli` | on | off | `main` / clap 仅 bin |
|
||||
| `view` | on | off | `tiny_http` 文档浏览器 |
|
||||
| `net-host` | on | off | `ureq` HTTP 客户端 |
|
||||
| `plugin-host` | on | off | `libloading` 原生插件 |
|
||||
| `exec-host` | on | off | `std::process` / foreign |
|
||||
| `fs-host` | on | off | 真实磁盘读写(可读可后续经 VFS 桥) |
|
||||
| `wasm-core` | off | on | 浏览器子集编译开关 |
|
||||
|
||||
`wasm32-unknown-unknown` 构建:**不得**链接 `libloading`、`ureq`、`tiny_http`、TTY `libc`。
|
||||
|
||||
### 4.2 包
|
||||
|
||||
| 路径 | 角色 |
|
||||
|------|------|
|
||||
| `marqdo`(根) | 核心;feature-gate |
|
||||
| `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` 对齐 |
|
||||
|
||||
发行:`marqdo wasm build`(C2 CLI 糖)或 `wasm-pack build crates/marqdo-wasm`。
|
||||
|
||||
---
|
||||
|
||||
## 5. 宿主能力矩阵
|
||||
|
||||
| 能力 | Native | Browser C1 | Browser C3+ |
|
||||
|------|--------|------------|-------------|
|
||||
| `print` / 捕获 stdout | ✓ | ✓ → 可镜像 `console` | ✓ |
|
||||
| `input` | stdin / preset | **仅 preset / JS 喂入** | 可选 prompt 桥 |
|
||||
| builtins / 表 / 算术 | ✓ | ✓ | ✓ |
|
||||
| `lib/math` `lib/json` `lib/collection` | ✓ | ✓(embedded) | ✓ |
|
||||
| `lib/fs` 真磁盘 | ✓ | ✗ 明确报错 | 可选 OPFS/VFS 桥 |
|
||||
| `lib/net` ureq | ✓ | ✗ | `fetch` 桥(异步模型见 §7) |
|
||||
| `plugin.load` | ✓ | ✗ | ✗(改 L1 浏览器专用) |
|
||||
| `exec` / foreign | ✓ | ✗ | ✗ |
|
||||
| DOM / 事件 | ✗ | stub | **交互装配** |
|
||||
| `sleep` | thread | 0 或 JS timer(异步) | timer |
|
||||
|
||||
错误策略:**显式失败**(诊断字符串含 `unavailable in browser wasm`),禁止静默空成功。
|
||||
|
||||
---
|
||||
|
||||
## 6. 交互装配(C3,对称样式装配)
|
||||
|
||||
### 6.1 作者面(示例)
|
||||
|
||||
```markdown
|
||||
---
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`count` = 0*
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#bump" | click | bump |
|
||||
|
||||
**`wire`**
|
||||
|
||||
## bump
|
||||
*`count` = count + 1*
|
||||
*`label` = > str count*
|
||||
*`patch` = > json.set map=None key="#count" value=label*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
```
|
||||
|
||||
`# main` 的返回值是 **wire 表**(`@` 行向记录列表)。Loader 调用 `mq_boot`,再 `wireEvents`。
|
||||
|
||||
### 6.2 桥约定
|
||||
|
||||
| 步骤 | API |
|
||||
|------|-----|
|
||||
| 启动 | `mq_boot(source)` → `{ ok, value }`;`value` = wire 列表或 `{ wire: [...] }` |
|
||||
| 事件 | Loader `addEventListener` → `mq_call(fn, {"event":"click"})` |
|
||||
| 回写 | 返回 Map 可含 `set_text`: `{ "#sel": "text" }`(仅 `textContent`) |
|
||||
|
||||
行键名认:`选择器`/`selector`、`事件`/`event`、`调用`/`call`。
|
||||
|
||||
含 `/` 的 CSS 等单元格仍 **引号优先**(见 [table-cell-expressions.md](table-cell-expressions.md))。
|
||||
|
||||
L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表即可验收。
|
||||
|
||||
---
|
||||
|
||||
## 7. 异步模型(C4)
|
||||
|
||||
锁定:[ADR 0003](../adr/0003-browser-async-effects.md)。
|
||||
|
||||
处理器返回 Map 可含(与 `set_text` 并列):
|
||||
|
||||
| 字段 | 含义 | 完成后 `mq_call` 实参 |
|
||||
|------|------|----------------------|
|
||||
| `fetch` | `{ url, method?, then, headers?, body? }` | `{ ok, status, body, error? }` |
|
||||
| `after` | `{ ms, then }` | `{ ok: true }` |
|
||||
|
||||
Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**在 WASM 内阻塞。
|
||||
|
||||
示例见 `examples/browser-hello/fetch.mq.md`。
|
||||
|
||||
---
|
||||
|
||||
## 8. 安全
|
||||
|
||||
| 项 | 规则 |
|
||||
|----|------|
|
||||
| 默认能力 | 无磁盘写、无 exec、无任意 net |
|
||||
| 源码来源 | 同源或构建时嵌入;不默认 `eval` 远程不可信脚本除非站点显式开启 |
|
||||
| DOM | 仅经装配表/白名单 API;不暴露任意 `innerHTML` 字符串执行第三方脚本 |
|
||||
| CSRF / Cookie | 浏览器 Marqdo **不替代**服务端鉴权;cookie 仍走 HTTP |
|
||||
|
||||
---
|
||||
|
||||
## 9. 与 `ext/web` 分工
|
||||
|
||||
| 层 | 负责 |
|
||||
|----|------|
|
||||
| 服务端 `plugins/web` | 路由、DB、会话、SSR HTML、样式/头/图装配 |
|
||||
| 页面壳 | `头装配` 挂 `module` → `marqdo-bridge.js`;`static` 提供 `.wasm` |
|
||||
| 浏览器 L1 | `客户端挂载` / `client_embed`;效应约定见 ADR 0003 |
|
||||
| 核心 / crate | `run_source`、`BrowserSession`、`marqdo-wasm` ABI |
|
||||
|
||||
挂载示例:
|
||||
|
||||
```markdown
|
||||
`头` =
|
||||
|
||||
| 关系 | 地址 |
|
||||
|------|------|
|
||||
| module | /static/marqdo-bridge.js |
|
||||
|
||||
*p = > page.头装配 表=头*
|
||||
```
|
||||
|
||||
```bash
|
||||
marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
|
||||
# app.static dir=static
|
||||
```
|
||||
|
||||
业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-hello/`)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 测试与验收
|
||||
|
||||
| 级 | 内容 |
|
||||
|----|------|
|
||||
| 单元 | `run_source("…# main\n> print…")` native 与 wasm 同测 |
|
||||
| 金样子集 | `tests/structure/hello.mq.md` 等无 fs/net/plugin 的样例 |
|
||||
| 浏览器冒烟 | `examples/browser-hello`:按钮点击 → Marqdo 函数 → 改 DOM 文本 |
|
||||
| 回归 | CI:`cargo test` native;另 job `wasm-pack build` / `cargo check --target wasm32-unknown-unknown --no-default-features --features wasm-core` |
|
||||
|
||||
---
|
||||
|
||||
## 11. 文档与技能同步
|
||||
|
||||
- ADR 0002、本文、路线图 C0–C5。
|
||||
- `.cursor/skills/marqdo/SKILL.md`:补充「浏览器 WASM / 交互装配 / 引号 CSS」。
|
||||
- `CHANGELOG`:Unreleased 记录设计锁定与各 C 完成项。
|
||||
|
||||
---
|
||||
|
||||
## 12. 风险
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|------|------|
|
||||
| wasm 体积过大 | `release-wasm` profile(`opt-level=z` + LTO + strip);`marqdo wasm build` 打印 KiB,有则跑 `wasm-opt -Oz` |
|
||||
| 异步拖垮语言 | ADR 0003 效应表;不阻塞 WASM |
|
||||
| Feature-gate 伤 native | 默认 features = 今日行为;CI 全绿再合 |
|
||||
| 作者误以浏览器替代服务器安全 | 文档强调鉴权在服务端 |
|
||||
| 会话要 bytecode | **未做**:`BrowserSession` 固定 tree(缺 entry-env invoke);`run_source` 已支持 bytecode |
|
||||
|
||||
---
|
||||
|
||||
## 14. C5 硬化(已落地)
|
||||
|
||||
| 项 | 状态 |
|
||||
|----|------|
|
||||
| `profile.release-wasm` + `marqdo wasm build` 体积报告 | done(~0.9 MiB) |
|
||||
| 可选 `wasm-opt` | done |
|
||||
| `run_source` bytecode 金样 | done |
|
||||
| 规范 bridge + 构建拷贝 | done(`crates/marqdo-wasm/js/`) |
|
||||
| Node ABI 冒烟 | done(`tests/wasm`) |
|
||||
| 站点 `头装配` / L1 `client_embed` | done |
|
||||
| 会话 bytecode / view 断点复用 | **非本版目标** |
|
||||
|
||||
---
|
||||
|
||||
## 15. 决策摘要
|
||||
|
||||
| 问题 | 答案 |
|
||||
|------|------|
|
||||
| 路线? | **C**:解释器/VM → WASM |
|
||||
| 作者语言? | 仅 `.mq.md` |
|
||||
| JS 角色? | Loader + 宿主桥 |
|
||||
| 服务端? | 保留;不塞进浏览器 |
|
||||
| 第一步实现? | C0 门控可编译 + C1 `run_source` 打印闭环 |
|
||||
+11
-4
@@ -52,14 +52,21 @@ Future optional ext domains get their own subdirs (e.g. `ext/web/`, `ext/quantum
|
||||
| `web` | `web/web.mq.md`, `web/网页.mq.md`, **`native/libweb.so`** — 见 [ext-web.md](ext-web.md) · [roadmap](../roadmap/ext-web.md) |
|
||||
| `quantum` | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **`native/libquantum.so`** — 见 [ext-quantum.md](ext-quantum.md) · [roadmap](../roadmap/ext-quantum.md) |
|
||||
|
||||
`add agent` copies the built native plugin into `MARQDO_EXT/native/`. Build it first:
|
||||
`add agent` / `add web` / `add quantum` **先定位原生插件**,再复制 `.mq.md`:
|
||||
|
||||
1. 在 `CARGO_TARGET_DIR`、`target/{debug,release}`、源码 `ext` 旁的 `target/`、可执行文件旁等路径查找 `lib{name}.so`(或 `.dll` / `.dylib`)
|
||||
2. 找不到则自动执行 `cargo build -p marqdo_plugin_{name}`,再安装到 `MARQDO_EXT/native/`
|
||||
3. 写入 `{name}.plugin` 绝对路径提示,供 `plugin.native_path` 解析
|
||||
|
||||
这样不会出现「只装了 `.mq.md`、运行时报 native plugin not found」的半安装状态。
|
||||
|
||||
```bash
|
||||
cargo build -p marqdo_plugin_agent
|
||||
marqdo ext add agent
|
||||
# 推荐:在仓库根目录
|
||||
marqdo ext add web
|
||||
# 等价于找到或编好 libweb.so 后拷入 ~/.marqdo/ext/native/
|
||||
```
|
||||
|
||||
Without install, runtime resolves the plugin via `plugin.native_path name=agent` (see [ext-abi.md](ext-abi.md)): `MARQDO_AGENT_PLUGIN` → `CARGO_TARGET_DIR/{debug,release}/` → cwd `target/…` → beside `marqdo` binary → `MARQDO_EXT/native/`.
|
||||
Without a prior install, runtime still resolves via `plugin.native_path name=web` (see [ext-abi.md](ext-abi.md)): `MARQDO_WEB_PLUGIN` → `CARGO_TARGET_DIR/{debug,release}/` → cwd `target/…` → beside `marqdo` binary → `MARQDO_EXT/native/`.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted · W0–W7 + P3 完结**(SQLite/Postgres 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / RBAC / 上传相册 / SEO·RSS·sitemap;Postgres 等见 §9) |
|
||||
| 日期 | 2026-08-11 |
|
||||
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) |
|
||||
| 状态 | **Accepted · W0–W7 + P3 + W8(站点图标/Head/图片装配)完结**(SQLite/Postgres 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / RBAC / 上传相册 / SEO·RSS·sitemap / **favicon·头资源·图片装配**;Postgres 等见 §9) |
|
||||
| 日期 | 2026-08-11(W8:2026-08-29) |
|
||||
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) |
|
||||
| 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) |
|
||||
| 本文目的 | 锁定**作者面**与**类 API**;指导实现 |
|
||||
|
||||
|
||||
@@ -268,7 +268,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
|
||||
| **首列表头 `@` / `行` / `row`** | **行向** `List` of `Map`(标记列不进入字段;任意数据行数) |
|
||||
| 重复表头 | 诊断错误 |
|
||||
|
||||
**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。
|
||||
**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本;含 `/` 的 CSS 比率等请用引号 `"1/5"`,裸 `1/5` 为除法)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。
|
||||
|
||||
```markdown
|
||||
*`k` = secret *
|
||||
|
||||
@@ -44,10 +44,11 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|
||||
| `` `api_key` `` | 变量引用 |
|
||||
| `` `a` + `b` `` | 普通表达式 |
|
||||
| `True` / `假` / `None` | 布尔 / 空 |
|
||||
| `"https://…"` / `".marqdo/x"` | 引号字符串(可含 `/`、插值) |
|
||||
| `"https://…"` / `".marqdo/x"` / `"1/5"` / `"16/9"` | 引号字符串(可含 `/`、插值;**CSS 比率等含 `/` 的值请用引号**,勿依赖空格消歧) |
|
||||
| `https://api.openai.com/v1` | **路径折叠**:无空格的 `Text/Text/…` 除法链收成整段文本(同调用实参) |
|
||||
| `gpt-4o-mini` | **连字符散文**:不拆成减法(同调用实参) |
|
||||
| `` /about ``、`` /chat/completions `` | 以 `/` 开头的路径散文 → 整段文本 |
|
||||
| `1/5` | **整数除法**(同表达式 / 调用实参;今日整除得 `0`)——要文本请写 `"1/5"` |
|
||||
| 空单元格 | 空文本 `""` |
|
||||
|
||||
### 2.2 表头仍是键名文本
|
||||
@@ -111,9 +112,10 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|
||||
|--------|------|
|
||||
| 纯中文/英文词、整数 | **不变** |
|
||||
| `gpt-4o-mini`、URL、`/path` | **不变**(折叠规则与调用实参一致) |
|
||||
| 真正要做除法 / 减法 | 用空格或括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 |
|
||||
| 真正要做除法 / 减法 | 裸写 `1/5` 或空格/括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 |
|
||||
| CSS / 含 `/` 的散文值 | **引号优先**:`"1/5"`、`"16/9"`、`"image/png"`(不靠空格把算术「关掉」) |
|
||||
|
||||
破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧。
|
||||
破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧;含 `/` 的**文本**一律用引号。
|
||||
|
||||
---
|
||||
|
||||
@@ -132,6 +134,7 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|
||||
|----|------|
|
||||
| 金样 | 横表单元格 `` `var` `` 读环境;竖表旧金样全绿 |
|
||||
| 路径 | `https://…`、`/chat/completions`、`gpt-4o-mini` 仍为文本 |
|
||||
| 含 `/` 文本 | 表单元格用引号:`"1/5"`、`"16/9"`;裸 `1/5` 为除法 |
|
||||
| 扩展 | `ext/ai/llm` 构造可用表写入运行时字段,去掉无必要的 `json.set` 链 |
|
||||
| 文档 | 本页 + roadmap T5 + markdown-mapping §9 同步 |
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
| 中 | 静态类型 / 可维护 AST | 长期改解释器不疼 |
|
||||
| 中 | CLI 与打包 | 单二进制或 `npx`/等价体验 |
|
||||
| 低 | 极致性能 | v0 样例很小 |
|
||||
| 低 | 浏览器内运行 | 可后置 |
|
||||
| 低 | 浏览器内运行 | **已后置落地规划**:见 [ADR 0002](../adr/0002-browser-marqdo-wasm.md)(WASM 解释器) |
|
||||
|
||||
非准则:跟风、先写再选、与「生成 OKF」强绑某一云厂商。
|
||||
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
# `ext/web` — 站点图标、Head 资源与图片装配
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted · W8 已落地** |
|
||||
| 日期 | 2026-08-29 |
|
||||
| 父设计 | [ext-web.md](ext-web.md) · [web-net-capabilities.md](web-net-capabilities.md) |
|
||||
| 相关 | [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md)(静态仍由嵌入式 `listen` 提供) |
|
||||
| 硬约束 | `ext/**` 不调 `host_*`;作者面禁止袋胶水;中英库文件分文件 |
|
||||
|
||||
---
|
||||
|
||||
## 0. 一句话
|
||||
|
||||
把 **浏览器默认图标(`/favicon.ico`)**、**`<head>` 里的 link/script**、**正文/品牌图片** 都做成与 `样式装配` 同构的能力:**GFM 表即数据,装配即函数**;由 `plugins/web` ABI 渲染/挂路由,`ext/web` 只做 L1 包装。
|
||||
|
||||
---
|
||||
|
||||
## 1. 动机与现状缺口
|
||||
|
||||
### 1.1 已有
|
||||
|
||||
| 能力 | 说明 |
|
||||
|------|------|
|
||||
| `app.static` / `应用.静态` | 目录挂到 `/static`(或自定义 mount) |
|
||||
| `page.meta` / `页面.元数据` | `title` / `description` / `canonical` / `og:*` → `<head>` |
|
||||
| `app.upload` + `gallery` | **运行时**用户上传媒体,不是站点品牌资源 |
|
||||
|
||||
### 1.2 缺口(本设计一次补齐)
|
||||
|
||||
| # | 缺口 | 影响 |
|
||||
|---|------|------|
|
||||
| G1 | 浏览器默认请求 **`GET /favicon.ico`**,静态挂在 `/static` 时根路径 404 | 标签页无图标 |
|
||||
| G2 | `page.meta` 未知键一律变成 `<meta name="…">`,**不能**正确写出 `<link rel="icon">` | 作者写 `icon` 无效 |
|
||||
| G3 | 无 **Head 资源表**(stylesheet / preload / script / manifest / apple-touch-icon) | 只能手写进 `intro` 或改插件 |
|
||||
| G4 | 无 **图片装配**(表 → `<figure>`/`<img>`),与样式装配不对齐 | logo / 头图 / 插图只能拼 HTML 字符串 |
|
||||
| G5 | 无 **站点级图标表 → 根路径文件服务 + 默认 head 注入** | 多页站点要在每页重复声明 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 设计原则
|
||||
|
||||
1. **配置即数据、装配即函数** — 与 `web_style` / `应用.装配` 同构。
|
||||
2. **应用层管「可达性」**(磁盘文件 → HTTP 路径);**页面层管「声明」**(`<head>` / 正文 HTML)。
|
||||
3. **站点图标可自动注入所有页面**,页面仍可用 `头装配` / `元数据` 覆盖或追加。
|
||||
4. **约定优于配置**:若已 `静态` 且目录内存在 `favicon.ico`(或 `favicon.png` / `favicon.svg`),未显式配置时仍挂 `GET /favicon.ico`(及对应静态 URL 由作者自选)。
|
||||
5. **中英分文件**:`web.mq.md` ↔ `网页.mq.md`,禁止混排。
|
||||
|
||||
---
|
||||
|
||||
## 3. 作者面 API(一次交付全集)
|
||||
|
||||
### 3.1 模块级装配(返回字符串,可与主题拼装)
|
||||
|
||||
| EN | ZH | FFI | 输入 | 输出 |
|
||||
|----|----|-----|------|------|
|
||||
| `make_style`(已有) | `样式装配` | `web_style` | 样式表 | CSS 文本 |
|
||||
| **`make_images`** | **`图片装配`** | **`web_images`** | 图片表 | HTML 片段 |
|
||||
| **`make_head`** | **`头资源装配`** | **`web_head`** | Head 表 | 供调试/预览的 HTML 片段(可选;页面方法主路径不强制调用) |
|
||||
|
||||
### 3.2 `# page` / `# 页面`
|
||||
|
||||
| EN | ZH | FFI | 作用 |
|
||||
|----|----|-----|------|
|
||||
| `meta`(增强) | `元数据` | `web_page_meta` | 认 `icon` / `favicon` / `apple-touch-icon` → `<link>`,不再误写成 `<meta name>` |
|
||||
| **`head`** | **`头装配`** | **`web_page_head`** | 挂 Head 资源表到 `page.head`,渲染时写入 `<head>` |
|
||||
| **`images`** | **`图片装配`**(方法) | **`web_page_images`** | 图片表 → HTML,写入 `page.images_html`,渲染进主区 |
|
||||
|
||||
### 3.3 `# app` / `# 应用`
|
||||
|
||||
| EN | ZH | FFI | 作用 |
|
||||
|----|----|-----|------|
|
||||
| **`icons`** | **`图标`** | **`web_app_icons`** | 站点图标表:根路径文件服务 + 默认 head 链接注入全站 |
|
||||
| `static`(增强) | `静态`(增强) | `web_app_static` | 约定:目录内 `favicon.ico|png|svg` → 自动注册 `/favicon.ico`(可被 `icons` 显式行覆盖) |
|
||||
|
||||
---
|
||||
|
||||
## 4. 表形约定
|
||||
|
||||
单元格仍为**字面量**;列名中英等价(任选一套,勿混列名语义)。
|
||||
|
||||
### 4.1 站点图标表(`app.icons` / `应用.图标`)
|
||||
|
||||
| 列(ZH) | 列(EN) | 必填 | 说明 |
|
||||
|----------|----------|------|------|
|
||||
| `路径` | `path` | ✅* | 磁盘路径(相对进程 cwd 或入口目录解析规则与 `static` 一致) |
|
||||
| `关系` | `rel` | | 默认 `icon`;常用 `icon` / `apple-touch-icon` / `mask-icon` |
|
||||
| `类型` | `type` | | 缺省按扩展名推断 |
|
||||
| `尺寸` | `sizes` | | 如 `16x16`、`180x180`、`any` |
|
||||
| `地址` | `url` / `href` | | 对外 URL。缺省:首个 `rel=icon` 且扩展名为 `.ico` → `/favicon.ico`;否则 `/icons/{文件名}` |
|
||||
|
||||
\* 若仅提供 `地址` 指向已由 `静态` 提供的 URL、不落盘服务,则 `路径` 可空(只注入 head,不挂新路由)。
|
||||
|
||||
**Listen 行为**
|
||||
|
||||
1. 规范化为数组 `{path, rel, type, sizes, url}`。
|
||||
2. 对每个非空 `path`:注册 **`GET {url}`**,读文件返回,`Content-Type` = `type` 或推断;`Cache-Control` 可用 `public, max-age=86400`。
|
||||
3. 若存在至少一个 `rel` 含 `icon` 的行,保证浏览器默认路径:若没有任何 `url=/favicon.ico`,则把**第一行 icon** 额外挂到 `/favicon.ico`(同一文件,可选)。
|
||||
4. 将图标行转为默认 head 链接列表,存入 `app.site_head`,listen 时写入 `AppState`,渲染任意页面前 **merge**(页面自有 `head` / meta 图标 **追加且可同 href 去重**)。
|
||||
|
||||
**`static` 约定自动图标**
|
||||
|
||||
在 `listen` 解析完 `static_dir` 后:若 `app.icons` 为空,且 `{static_dir}/favicon.ico` 或 `.png` / `.svg` 存在,则等价注册:
|
||||
|
||||
```text
|
||||
path = {static_dir}/favicon.{ico|png|svg}
|
||||
rel = icon
|
||||
url = /favicon.ico
|
||||
```
|
||||
|
||||
(文件仍可通过 `/static/favicon.*` 访问;根路径额外可达。)
|
||||
|
||||
### 4.2 Head 资源表(`page.head` / `页面.头装配`)
|
||||
|
||||
| 列(ZH) | 列(EN) | 说明 |
|
||||
|----------|----------|------|
|
||||
| `关系` | `rel` | `icon` / `apple-touch-icon` / `stylesheet` / `preload` / `modulepreload` / `manifest` / `canonical` / **`script`** / **`module`** |
|
||||
| `地址` | `href` / `src` / `url` | 资源 URL |
|
||||
| `类型` | `type` | MIME 或 `module` |
|
||||
| `尺寸` | `sizes` | icons |
|
||||
| `媒体` | `media` | CSS media |
|
||||
| `作为` | `as` | preload `as` |
|
||||
| `跨域` | `crossorigin` | 空 / `anonymous` / `use-credentials` |
|
||||
|
||||
**渲染规则**
|
||||
|
||||
| `rel` | 输出 |
|
||||
|-------|------|
|
||||
| `script` | `<script src="…"></script>`(`type` 非空则写出) |
|
||||
| `module` | `<script type="module" src="…"></script>` |
|
||||
| 其他 | `<link rel="…" href="…" …>`(按列附加 `type`/`sizes`/`media`/`as`/`crossorigin`) |
|
||||
|
||||
空 `地址` 的行跳过。
|
||||
|
||||
### 4.3 元数据表增强(`page.meta`)
|
||||
|
||||
| 键 | 行为 |
|
||||
|----|------|
|
||||
| `title` / `description` / `canonical` / `og:*` | **不变** |
|
||||
| **`icon`** / **`favicon`** | `<link rel="icon" href="{值}"/>`(可选若值含空格后 MIME:本切片仅 href) |
|
||||
| **`apple-touch-icon`** | `<link rel="apple-touch-icon" href="{值}"/>` |
|
||||
| 其他 | 仍为 `<meta name="…" content="…"/>` |
|
||||
|
||||
### 4.4 图片表(`make_images` / `page.images`)
|
||||
|
||||
| 列(ZH) | 列(EN) | 说明 |
|
||||
|----------|----------|------|
|
||||
| `源` | `src` | 必填,图片 URL |
|
||||
| `替代` | `alt` | `alt` 文本,默认空 |
|
||||
| `标题` | `title` | `title` 属性 |
|
||||
| `类` | `class` | 加在 `<figure>`(无 figure 时加在 `<img>`) |
|
||||
| `链接` | `href` / `link` | 非空则用 `<a>` 包裹 `<img>` |
|
||||
| `宽度` | `width` | 像素,可选 |
|
||||
| `高度` | `height` | 像素,可选 |
|
||||
| `加载` | `loading` | `lazy` / `eager`;默认 `lazy`(首行可写 `eager`) |
|
||||
| `图注` | `caption` | 非空则 `<figcaption>` |
|
||||
| `槽` | `slot` | 预留:`main`(默认)。本切片只支持主区 |
|
||||
|
||||
**输出 HTML(多行)**
|
||||
|
||||
```html
|
||||
<div class="mq-images" data-slot="main">
|
||||
<figure class="mq-img …">…</figure>
|
||||
…
|
||||
</div>
|
||||
```
|
||||
|
||||
单行且无图注/类时仍包在 `div.mq-images` 内,保证主题可统一选中。
|
||||
|
||||
**`page.images`**:调用 `web_images` 逻辑,结果写入 `page.images_html`。
|
||||
|
||||
**渲染位置**:`render_page` 主区中,在 `intro` **之前**插入 `images_html`(品牌图/头图常见需求);`render_fragment` 的 main 槽同样插入。
|
||||
|
||||
路径与 MIME 单元格若含 `/`,须写成引号字面量(T5 单元格表达式会把裸 `/` 当除法):`"/favicon.ico"`、`"image/png"`。
|
||||
|
||||
---
|
||||
|
||||
## 5. 插件 / 状态形状
|
||||
|
||||
### 5.1 页面对象新增字段
|
||||
|
||||
```json
|
||||
{
|
||||
"meta": { "title": "…", "icon": "/favicon.ico" },
|
||||
"head": [
|
||||
{ "rel": "stylesheet", "href": "/static/print.css", "media": "print" }
|
||||
],
|
||||
"images_html": "<div class=\"mq-images\">…</div>"
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 应用对象新增字段
|
||||
|
||||
```json
|
||||
{
|
||||
"static_dir": "public",
|
||||
"static_mount": "/static",
|
||||
"icons": [
|
||||
{
|
||||
"path": "public/favicon.ico",
|
||||
"rel": "icon",
|
||||
"type": "image/x-icon",
|
||||
"sizes": "32x32",
|
||||
"url": "/favicon.ico"
|
||||
}
|
||||
],
|
||||
"site_head": [
|
||||
{ "rel": "icon", "href": "/favicon.ico", "type": "image/x-icon", "sizes": "32x32" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`site_head` 由 `web_app_icons`(及 static 约定)生成,作者不必手写。
|
||||
|
||||
### 5.3 `AppState` / `listen` 签名
|
||||
|
||||
新增:
|
||||
|
||||
- `icon_routes: Vec<IconRoute { url, path, content_type }>`
|
||||
- `site_head: Vec<HeadLink>`
|
||||
|
||||
在 `home` / 动态与静态 `route` 渲染前:`merge_site_head(&mut page, &state.site_head)`。
|
||||
|
||||
---
|
||||
|
||||
## 6. MIME 推断
|
||||
|
||||
| 扩展名 | Content-Type |
|
||||
|--------|----------------|
|
||||
| `.ico` | `image/x-icon` |
|
||||
| `.png` | `image/png` |
|
||||
| `.svg` | `image/svg+xml` |
|
||||
| `.webp` | `image/webp` |
|
||||
| `.jpg` / `.jpeg` | `image/jpeg` |
|
||||
| `.gif` | `image/gif` |
|
||||
| `.webmanifest` / `.json` | `application/manifest+json` |
|
||||
| 其他 | `application/octet-stream` |
|
||||
|
||||
---
|
||||
|
||||
## 7. 作者示例(中文)
|
||||
|
||||
```markdown
|
||||
## 站点图标
|
||||
|
||||
|路径|关系|类型|尺寸|地址|
|
||||
|---|---|---|---|---|
|
||||
|public/favicon.ico|icon|image/x-icon|32x32|/favicon.ico|
|
||||
|public/apple-touch-icon.png|apple-touch-icon|image/png|180x180|/static/apple-touch-icon.png|
|
||||
|
||||
## 头资源
|
||||
|
||||
|关系|地址|类型|媒体|
|
||||
|---|---|---|---|
|
||||
|icon|/favicon.ico|image/x-icon|
|
||||
|stylesheet|/static/print.css|text/css|print|
|
||||
|script|/static/live.js||
|
||||
|
||||
## 品牌图
|
||||
|
||||
|源|替代|类|链接|宽度|加载|
|
||||
|---|---|---|---|---|---|
|
||||
|/static/logo.svg|Marqdo|brand-logo|/|48|eager|
|
||||
|
||||
# main
|
||||
|
||||
*page = > 网页.页面 标题="博客"*
|
||||
*page = > page.头装配 表=`头资源`*
|
||||
*page = > page.图片装配 表=`品牌图`*
|
||||
*page = > page.元数据 元数据=`seo表`*
|
||||
|
||||
*app = > 网页.应用 页面=`page` …*
|
||||
*app = > app.静态 目录="public" 挂载="/static"*
|
||||
*app = > app.图标 表=`站点图标`*
|
||||
> app.监听
|
||||
```
|
||||
|
||||
英文对称:`web.page` / `head` / `images` / `meta`;`web.app` / `static` / `icons`;模块 `web.make_images`。
|
||||
|
||||
---
|
||||
|
||||
## 8. 实现清单(本切片必须全部完成)
|
||||
|
||||
| # | 项 | 归属 |
|
||||
|---|----|------|
|
||||
| I1 | `assets.rs`:表解析、MIME、`web_images` HTML、`web_head` HTML、图标规范化 | `plugins/web` |
|
||||
| I2 | `web_page_head` / `web_page_images` / `web_images` / `web_head` / `web_app_icons` FFI + 注册 | `plugins/web` |
|
||||
| I3 | `head_html`:meta 图标键 + `page.head` + 合并 `site_head` | `render.rs` |
|
||||
| I4 | `images_html` 插入主区;fragment main 同理 | `render.rs` |
|
||||
| I5 | `listen`:图标文件路由 + static 约定 favicon + `AppState` 注入 | `http.rs` / `lib.rs` |
|
||||
| I6 | `ext/web/web.mq.md` + `网页.mq.md` L1 方法与叙述 | `ext/web` |
|
||||
| I7 | 金样:离线装配 + live `GET /favicon.ico` + HTML 含 link/img | `tests/ext/` |
|
||||
| I8 | `examples/marqdo-blog`:真实 favicon + logo 装配 + README | `examples/` |
|
||||
| I9 | 更新 [web-net-capabilities.md](web-net-capabilities.md)、[ext-web.md](ext-web.md)、[doc/README.md](../README.md)、CHANGELOG Unreleased;Skill 专节一句 | 文档 |
|
||||
|
||||
**非目标(本切片不做)**
|
||||
|
||||
- 服务端图片缩放 / WebP 转码
|
||||
- CDN 签名 URL
|
||||
- 把上传相册(`gallery`)与品牌图混为一谈
|
||||
- 进程内 TLS(仍见反代文档)
|
||||
|
||||
---
|
||||
|
||||
## 9. 验收标准
|
||||
|
||||
1. `marqdo run tests/ext/web-assets-smoke.mq.md` 离线:icons/head/images 字段与 HTML 片段断言通过。
|
||||
2. Live:`GET /favicon.ico` → 200 + 正确 Content-Type;首页 HTML 含 `rel="icon"` 与 `mq-images`。
|
||||
3. `examples/marqdo-blog`:`curl /favicon.ico` 与页面源码可见图标与 logo。
|
||||
4. 旧金样(`web-static-smoke`、`web-content-smoke` 等)不回归。
|
||||
5. `ext/**` 无 `host_*`。
|
||||
|
||||
---
|
||||
|
||||
## 10. 与能力矩阵的关系
|
||||
|
||||
在 [web-net-capabilities.md](web-net-capabilities.md) **类 D** 增补:
|
||||
|
||||
| # | 能力 | 状态 |
|
||||
|---|------|------|
|
||||
| **D10** | 站点图标 / `/favicon.ico` / apple-touch-icon | ✅ 本设计 |
|
||||
| **D11** | Head 资源表(link / script / preload / manifest) | ✅ 本设计 |
|
||||
| **D12** | 图片装配(GFM → figure/img)+ 主区注入 | ✅ 本设计 |
|
||||
|
||||
波次标签:**W8(站点资源与图片装配)** — 在 W7+P3 完结之上的内容站体验补齐,不推翻既有边界。
|
||||
@@ -166,6 +166,9 @@
|
||||
| D7 | **评论系统**(表单 + 审核 + 反垃圾) | ✅ 约定:表+表单+where(W6);反垃圾属应用层 | `ext/web` | P2 ✅ |
|
||||
| D8 | **草稿/发布/定时**(状态字段 + 过滤查询) | ✅ 约定:`status` + where(W6) | `ext/web` + db where | P2 ✅ |
|
||||
| D9 | **图片/附件库**(依赖 A5 上传 + 相册页) | ✅ **已实现(P3)**:`app.gallery` HTML 相册 + A5 上传/下载 | `ext/web` + `plugins/web` | P3 ✅ |
|
||||
| **D10** | **站点图标 / favicon**(`/favicon.ico` + apple-touch-icon) | ✅ **已实现(W8)**:`app.icons` / `应用.图标`;`static` 约定 `favicon.*`;设计 [web-assets-and-images.md](web-assets-and-images.md) | `plugins/web` + `ext/web` | W8 ✅ |
|
||||
| **D11** | **Head 资源表**(link / script / preload / manifest) | ✅ **已实现(W8)**:`page.head` / `页面.头装配`;`meta` 认 `icon`/`favicon` | `plugins/web` + `ext/web` | W8 ✅ |
|
||||
| **D12** | **图片装配**(GFM → figure/img + 主区注入) | ✅ **已实现(W8)**:`make_images` / `网页.图片装配`;`page.images` | `plugins/web` + `ext/web` | W8 ✅ |
|
||||
|
||||
---
|
||||
|
||||
@@ -184,6 +187,7 @@
|
||||
| **W6** | 进阶 | 全文搜索(FTS5) + 迁移机制 + 评论系统 + 草稿/发布 + WS 广播 | B6 B9 ✅;WS 广播 + access_log ✅;D7/D8 用表+where ✅ |
|
||||
| **W7** | 完结打磨 | Cache-Control、自定义 404/500、301 重定向、sitemap/robots、init 唯一/索引、HTTPS 反代文档 | A6 A7 A9 A10 B7 D2 ✅ |
|
||||
| **P3** | 真·网络扩展补齐 | 审计时间戳、外键、RBAC 门禁、媒体相册、下载 ETag | B10 C8 D9 + ETag/FK ✅ |
|
||||
| **W8** | 站点资源与图片装配 | favicon 根路由、Head 资源表、图片装配、meta 图标键 | D10 D11 D12 ✅ |
|
||||
|
||||
### 4.2 边界判定要点(严格遵守既有约束)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# 路线图:浏览器 Marqdo(WASM)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Completed**(路线 C 首版功能完备) |
|
||||
| 日期 | 2026-09-01 |
|
||||
| ADR | [0002](../adr/0002-browser-marqdo-wasm.md) · [0003](../adr/0003-browser-async-effects.md) |
|
||||
| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) |
|
||||
|
||||
| 阶段 | 内容 | 状态 |
|
||||
|------|------|------|
|
||||
| **C0** | feature 门控;`wasm32` check | **done** |
|
||||
| **C1** | `run_source` + `mq_run` | **done** |
|
||||
| **C2** | loader + `marqdo wasm build`(含 bridge 拷贝) | **done** |
|
||||
| **C3** | session wire + `set_text` | **done** |
|
||||
| **C4** | `fetch` / `after` 效应 | **done** |
|
||||
| **C5** | `release-wasm` 体积;冒烟;站点挂载文档 / L1 | **done** |
|
||||
|
||||
## 交付物
|
||||
|
||||
| 产物 | 路径 |
|
||||
|------|------|
|
||||
| ABI crate | `crates/marqdo-wasm` |
|
||||
| 官方 bridge | `crates/marqdo-wasm/js/marqdo-bridge.js` |
|
||||
| CLI | `marqdo wasm build -o DIR` |
|
||||
| 示例 | `examples/browser-hello/` |
|
||||
| 冒烟 | `tests/wasm/smoke.mjs` · `tests/wasm_smoke.rs` |
|
||||
| L1 | `web.client_embed` / `网页.客户端挂载` |
|
||||
|
||||
## 明确非目标(本版不做)
|
||||
|
||||
- 浏览器会话 bytecode(缺 entry-env invoke;一发 `run_source` 已支持 bytecode)
|
||||
- 把 axum / SQLite 服务端搬进 WASM
|
||||
- 业务手写 JS 框架
|
||||
|
||||
## 进度
|
||||
|
||||
| 日期 | 记录 |
|
||||
|------|------|
|
||||
| 2026-09-01 | C0–C5 完结并 push;收口 bridge 规范路径 + 冒烟 + 挂载 L1 |
|
||||
@@ -109,7 +109,8 @@ Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对
|
||||
|
||||
- 更完整表达式文法、错误模型、外联围栏 FFI
|
||||
- 生成 OKF 依赖目录
|
||||
- (可选)另一后端:编译到 Python/WASM——**另开 ADR**,不替代自研语义
|
||||
- (可选)另一后端:编译到 Python/WASM——**另开 ADR**,不替代自研语义
|
||||
- **浏览器内运行(路线 C)**:解释器/VM 上 WASM(**非**把 `.mq.md` 译成 JS)——已锁定 [ADR 0002](../adr/0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](browser-wasm.md)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ flowchart LR
|
||||
|
||||
### 风险与边界
|
||||
|
||||
- 静态 `gh-pages` **无法**真断点(无常驻 VM);调试仅 **live view**(或未来 WASM 解释器)。
|
||||
- 静态 `gh-pages` **无法**真断点(无常驻 VM);调试仅 **live view**(或 [浏览器 WASM 解释器](browser-wasm.md) C5)。
|
||||
- 字节码调试可晚于树遍历一个迭代。
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# browser-hello(WASM C1–C3)
|
||||
|
||||
浏览器内跑 Marqdo(路线 C)。
|
||||
|
||||
```bash
|
||||
# 仓库根目录
|
||||
cargo build -p marqdo --release
|
||||
./target/release/marqdo wasm build -o examples/browser-hello
|
||||
|
||||
cd examples/browser-hello
|
||||
python3 -m http.server 8765
|
||||
```
|
||||
|
||||
| 页 | 说明 |
|
||||
|----|------|
|
||||
| [/](http://127.0.0.1:8765/) | C1:编辑源码 → `mq_run` 打印 |
|
||||
| [/interact.html](http://127.0.0.1:8765/interact.html) | C3:`counter.mq.md` 交互表 → 点击改 DOM |
|
||||
| [/fetch.html](http://127.0.0.1:8765/fetch.html) | C4:`fetch` / `after` 效应续体 |
|
||||
|
||||
- `marqdo-bridge.js`:官方宿主桥(`boot` / `call` / `wireEvents` / `applyEffects`)
|
||||
- 业务源码只有 `.mq.md`;异步见 [ADR 0003](../../doc/adr/0003-browser-async-effects.md)
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: browser counter (C3)
|
||||
description: wire table + shared entry env; click updates DOM via set_text
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`count` = 0*
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#bump" | click | bump |
|
||||
| 2 | "#reset" | click | reset |
|
||||
|
||||
**`wire`**
|
||||
|
||||
## bump
|
||||
*`count` = count + 1*
|
||||
*`label` = > str count*
|
||||
*`patch` = > json.set map=None key="#count" value=label*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
|
||||
## reset
|
||||
*`count` = 0*
|
||||
*`patch` = > json.set map=None key="#count" value="0"*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
@@ -0,0 +1,79 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hans">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Marqdo · fetch / after (C4)</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #1a1f1c;
|
||||
--paper: #e8efe6;
|
||||
--accent: #2f6f4e;
|
||||
--muted: #5a6b60;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
|
||||
color: var(--ink);
|
||||
background:
|
||||
radial-gradient(800px 420px at 0% 100%, #d5e4d8 0%, transparent 55%),
|
||||
linear-gradient(165deg, #f3f7f2, var(--paper));
|
||||
padding: 2rem clamp(1rem, 4vw, 3rem);
|
||||
}
|
||||
h1 {
|
||||
font-family: "IBM Plex Serif", "Noto Serif SC", serif;
|
||||
font-weight: 600;
|
||||
font-size: clamp(1.6rem, 3vw, 2.2rem);
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
.lead { color: var(--muted); margin: 0 0 1.25rem; max-width: 38rem; }
|
||||
#status {
|
||||
font-family: "IBM Plex Mono", ui-monospace, monospace;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.45;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
min-height: 4rem;
|
||||
margin: 1rem 0 1.25rem;
|
||||
padding: 0.85rem 1rem;
|
||||
background: rgba(255,255,255,0.55);
|
||||
border: 1px solid #b7c7bb;
|
||||
}
|
||||
button {
|
||||
margin-right: 0.5rem;
|
||||
margin-bottom: 0.4rem;
|
||||
padding: 0.55rem 1.1rem;
|
||||
border: 0;
|
||||
background: var(--accent);
|
||||
color: #f5faf6;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.secondary { background: #3a4740; }
|
||||
button:disabled { opacity: 0.5; cursor: wait; }
|
||||
pre {
|
||||
margin-top: 1.5rem;
|
||||
width: min(42rem, 100%);
|
||||
padding: 0.9rem 1rem;
|
||||
background: #122018;
|
||||
color: #d7eadc;
|
||||
overflow: auto;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.err { color: #ffb4a8; }
|
||||
a { color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">C4:返回 <code>fetch</code> / <code>after</code> 效应,由官方 bridge 续体回调(ADR 0003)。业务只在 <code>fetch.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./">打印</a></p>
|
||||
<div id="status">idle</div>
|
||||
<button id="load" type="button" disabled>请求 UUID</button>
|
||||
<button id="ping" class="secondary" type="button" disabled>延迟 pong</button>
|
||||
<pre id="log">loading…</pre>
|
||||
<script type="module" src="./fetch.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
applyDomPatch,
|
||||
boot,
|
||||
loadWasm,
|
||||
readCString,
|
||||
wireEvents,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
async function main() {
|
||||
const log = document.getElementById("log");
|
||||
const loadBtn = document.getElementById("load");
|
||||
const pingBtn = document.getElementById("ping");
|
||||
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
log.classList.add("err");
|
||||
log.textContent = String(e);
|
||||
return;
|
||||
}
|
||||
|
||||
const srcRes = await fetch("./fetch.mq.md");
|
||||
if (!srcRes.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = `failed to load fetch.mq.md (${srcRes.status})`;
|
||||
return;
|
||||
}
|
||||
const source = await srcRes.text();
|
||||
const result = boot(exports, source);
|
||||
if (!result.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = result.error || "boot failed";
|
||||
return;
|
||||
}
|
||||
|
||||
const n = wireEvents(exports, result.value, {
|
||||
onError: (err) => {
|
||||
log.classList.add("err");
|
||||
log.textContent = err;
|
||||
},
|
||||
});
|
||||
applyDomPatch({ set_text: { "#status": "idle" } });
|
||||
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
log.classList.remove("err");
|
||||
log.textContent = `marqdo-wasm ${ver} · wired ${n} · ADR 0003 effects\nsource: fetch.mq.md`;
|
||||
loadBtn.disabled = false;
|
||||
pingBtn.disabled = false;
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: browser fetch (C4)
|
||||
description: return fetch/after effects; bridge continues via mq_call
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#load" | click | load |
|
||||
| 2 | "#ping" | click | ping |
|
||||
|
||||
**`wire`**
|
||||
|
||||
## load
|
||||
*`patch` = > json.set map=None key="#status" value="loading…"*
|
||||
*`ret` = > json.set map=None key="set_text" value=patch*
|
||||
*`req` = > json.set map=None key="url" value="https://httpbin.org/uuid"*
|
||||
*`req` = > json.set map=req key="then" value="on_uuid"*
|
||||
**> json.set map=ret key="fetch" value=req**
|
||||
|
||||
## on_uuid
|
||||
+ `ok`
|
||||
+ `status`
|
||||
+ `body`=""
|
||||
+ `error`=""
|
||||
|
||||
1. ok
|
||||
*`p` = > json.set map=None key="#status" value=body*
|
||||
**> json.set map=None key="set_text" value=p**
|
||||
2. *
|
||||
*`msg` = "fetch failed"*
|
||||
*`p` = > json.set map=None key="#status" value=msg*
|
||||
**> json.set map=None key="set_text" value=p**
|
||||
|
||||
## ping
|
||||
*`patch` = > json.set map=None key="#status" value="wait 600ms…"*
|
||||
*`ret` = > json.set map=None key="set_text" value=patch*
|
||||
*`t` = > json.set map=None key="ms" value=600*
|
||||
*`t` = > json.set map=t key="then" value="on_ping"*
|
||||
**> json.set map=ret key="after" value=t**
|
||||
|
||||
## on_ping
|
||||
+ `ok`=True
|
||||
|
||||
*`p` = > json.set map=None key="#status" value="pong"*
|
||||
**> json.set map=None key="set_text" value=p**
|
||||
@@ -0,0 +1,82 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hans">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Marqdo browser hello (WASM C1)</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #1a1f1c;
|
||||
--paper: #e8efe6;
|
||||
--accent: #2f6f4e;
|
||||
--muted: #5a6b60;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
|
||||
color: var(--ink);
|
||||
background:
|
||||
radial-gradient(1200px 600px at 10% -10%, #c5dcc8 0%, transparent 55%),
|
||||
linear-gradient(165deg, #f3f7f2, var(--paper));
|
||||
padding: 2rem clamp(1rem, 4vw, 3rem);
|
||||
}
|
||||
h1 {
|
||||
font-family: "IBM Plex Serif", "Noto Serif SC", serif;
|
||||
font-weight: 600;
|
||||
font-size: clamp(1.6rem, 3vw, 2.2rem);
|
||||
margin: 0 0 0.35rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.lead { color: var(--muted); margin: 0 0 1.5rem; max-width: 36rem; }
|
||||
label { display: block; font-size: 0.85rem; color: var(--muted); margin-bottom: 0.35rem; }
|
||||
textarea {
|
||||
width: min(40rem, 100%);
|
||||
min-height: 10rem;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border: 1px solid #b7c7bb;
|
||||
border-radius: 2px;
|
||||
background: rgba(255,255,255,0.7);
|
||||
font-family: "IBM Plex Mono", ui-monospace, monospace;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
button {
|
||||
margin-top: 0.85rem;
|
||||
padding: 0.55rem 1.1rem;
|
||||
border: 0;
|
||||
background: var(--accent);
|
||||
color: #f5faf6;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled { opacity: 0.5; cursor: wait; }
|
||||
pre {
|
||||
margin-top: 1.25rem;
|
||||
width: min(40rem, 100%);
|
||||
padding: 0.9rem 1rem;
|
||||
background: #122018;
|
||||
color: #d7eadc;
|
||||
overflow: auto;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.err { color: #ffb4a8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">浏览器内 WASM 解释器(路线 C / C1):源码是 <code>.mq.md</code>,无业务手写 JS。<a href="./interact.html">交互示例 (C3)</a></p>
|
||||
<label for="src">程序</label>
|
||||
<textarea id="src"># main
|
||||
|
||||
> print text=Hello from browser WASM!
|
||||
</textarea>
|
||||
<div>
|
||||
<button id="run" disabled>运行</button>
|
||||
</div>
|
||||
<pre id="out">loading wasm…</pre>
|
||||
<script type="module" src="./loader.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hans">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Marqdo · 交互装配 (C3)</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #1a1f1c;
|
||||
--paper: #e8efe6;
|
||||
--accent: #2f6f4e;
|
||||
--muted: #5a6b60;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
|
||||
color: var(--ink);
|
||||
background:
|
||||
radial-gradient(900px 500px at 90% 0%, #cfe0d2 0%, transparent 50%),
|
||||
linear-gradient(165deg, #f3f7f2, var(--paper));
|
||||
padding: 2rem clamp(1rem, 4vw, 3rem);
|
||||
}
|
||||
h1 {
|
||||
font-family: "IBM Plex Serif", "Noto Serif SC", serif;
|
||||
font-weight: 600;
|
||||
font-size: clamp(1.6rem, 3vw, 2.2rem);
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
.lead { color: var(--muted); margin: 0 0 1.5rem; max-width: 36rem; }
|
||||
#count {
|
||||
font-family: "IBM Plex Serif", serif;
|
||||
font-size: 4rem;
|
||||
line-height: 1;
|
||||
margin: 1rem 0 1.25rem;
|
||||
letter-spacing: -0.04em;
|
||||
}
|
||||
button {
|
||||
margin-right: 0.5rem;
|
||||
padding: 0.55rem 1.1rem;
|
||||
border: 0;
|
||||
background: var(--accent);
|
||||
color: #f5faf6;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.secondary { background: #3a4740; }
|
||||
pre {
|
||||
margin-top: 1.5rem;
|
||||
width: min(40rem, 100%);
|
||||
padding: 0.9rem 1rem;
|
||||
background: #122018;
|
||||
color: #d7eadc;
|
||||
overflow: auto;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.err { color: #ffb4a8; }
|
||||
a { color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">C3:GFM 交互表装配事件;点击由 WASM 会话里的 Marqdo 函数处理并回写 DOM。<a href="./fetch.html">fetch (C4)</a> · <a href="./">打印示例</a></p>
|
||||
<div id="count">0</div>
|
||||
<button id="bump" type="button" disabled>加一</button>
|
||||
<button id="reset" class="secondary" type="button" disabled>清零</button>
|
||||
<pre id="log">loading…</pre>
|
||||
<script type="module" src="./interact.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
applyDomPatch,
|
||||
boot,
|
||||
loadWasm,
|
||||
readCString,
|
||||
wireEvents,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
async function main() {
|
||||
const log = document.getElementById("log");
|
||||
const bump = document.getElementById("bump");
|
||||
const reset = document.getElementById("reset");
|
||||
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
log.classList.add("err");
|
||||
log.textContent = String(e);
|
||||
return;
|
||||
}
|
||||
|
||||
const srcRes = await fetch("./counter.mq.md");
|
||||
if (!srcRes.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = `failed to load counter.mq.md (${srcRes.status})`;
|
||||
return;
|
||||
}
|
||||
const source = await srcRes.text();
|
||||
const result = boot(exports, source);
|
||||
if (!result.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = result.error || "boot failed";
|
||||
return;
|
||||
}
|
||||
|
||||
const n = wireEvents(exports, result.value, {
|
||||
onError: (err) => {
|
||||
log.classList.add("err");
|
||||
log.textContent = err;
|
||||
},
|
||||
});
|
||||
// Ensure initial display matches Marqdo state.
|
||||
applyDomPatch({ set_text: { "#count": "0" } });
|
||||
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
log.classList.remove("err");
|
||||
log.textContent = `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: counter.mq.md`;
|
||||
bump.disabled = false;
|
||||
reset.disabled = false;
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
loadWasm,
|
||||
readCString,
|
||||
runSource,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
const DEFAULT_SRC = `# main
|
||||
|
||||
> print text=Hello from browser WASM!
|
||||
`;
|
||||
|
||||
async function main() {
|
||||
const out = document.getElementById("out");
|
||||
const btn = document.getElementById("run");
|
||||
const src = document.getElementById("src");
|
||||
if (!src.value.trim()) src.value = DEFAULT_SRC;
|
||||
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
out.classList.add("err");
|
||||
out.textContent = String(e);
|
||||
return;
|
||||
}
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
out.classList.remove("err");
|
||||
out.textContent = `marqdo-wasm ${ver} ready.\n`;
|
||||
btn.disabled = false;
|
||||
|
||||
btn.addEventListener("click", () => {
|
||||
try {
|
||||
const result = runSource(exports, src.value);
|
||||
out.classList.toggle("err", !result.ok);
|
||||
out.textContent = result.ok
|
||||
? (result.stdout || "(empty stdout)") +
|
||||
(result.value != null && result.value !== "None"
|
||||
? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}`
|
||||
: "")
|
||||
: result.error || "error";
|
||||
} catch (e) {
|
||||
out.classList.add("err");
|
||||
out.textContent = String(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -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;
|
||||
}
|
||||
@@ -18,7 +18,8 @@ cargo run -- examples/marqdo-blog/index.mq.md
|
||||
- `/about` — 关于页
|
||||
- `/admin` — 会话门禁后台,登录 `admin` / `marqdo`,可增删改文章与标签
|
||||
- `/live` — WebSocket 回显端点
|
||||
- `/static/*` — 静态资源(`public/` 下的 `live.js`)
|
||||
- `/static/*` — 静态资源(`public/` 下的 `live.js`、favicon、logo)
|
||||
- `/favicon.ico` — 站点图标(`应用.图标` 表装配)
|
||||
|
||||
## 设计亮点(文档即代码)
|
||||
|
||||
@@ -29,6 +30,9 @@ cargo run -- examples/marqdo-blog/index.mq.md
|
||||
每个 `## 段`(基础/顶栏/侧栏/主体/卡片/页脚/表单/响应式)导出一张样式表,
|
||||
`## 全局` 用 `网页.样式装配` 函数把每张表装配成 CSS 文本,再 `text.str_join` 拼成完整样式表,
|
||||
最后经 `页面.样式` 注入页面。样式保持可读的数据表格,不写胶水代码。
|
||||
- **图标 / 头资源 / 图片装配**(W8):`应用.图标` 表挂 `/favicon.ico` 与 SVG;
|
||||
`页面.头装配` 写 apple-touch-icon;`页面.图片装配` 把 logo 表注入主区(`mq-images`)。
|
||||
含 `/` 的路径与 MIME 单元格需加引号(如 `"/static/logo.svg"`、`"image/png"`)。
|
||||
- **页面 = 组件装配 + 主体绑定**(`index.mq.md`):
|
||||
导航/侧栏/页脚用 `|组件|样式|` 表装配,文章列表用 `|属性|值|` 绑定 SQLite 字段。
|
||||
- **动态路由**:`/post/{slug}` 的 `slug` 注入查询条件,`页面.详情` 把首行渲染成文章。
|
||||
|
||||
@@ -64,6 +64,25 @@ import db:db/index.mq.md
|
||||
|----|--------|------|
|
||||
| 1 | admin | marqdo |
|
||||
|
||||
`站点图标` =
|
||||
|
||||
| 路径 | 关系 | 类型 | 尺寸 | 地址 |
|
||||
|------|------|------|------|------|
|
||||
| "public/favicon.png" | icon | "image/png" | 32x32 | "/favicon.ico" |
|
||||
| "public/favicon.svg" | icon | "image/svg+xml" | any | "/static/favicon.svg" |
|
||||
|
||||
`头资源` =
|
||||
|
||||
| 关系 | 地址 | 类型 |
|
||||
|------|------|------|
|
||||
| apple-touch-icon | "/static/favicon.png" | "image/png" |
|
||||
|
||||
`品牌图` =
|
||||
|
||||
| 源 | 替代 | 类 | 链接 | 宽度 | 加载 |
|
||||
|----|------|----|------|------|------|
|
||||
| "/static/logo.svg" | Marqdo | brand-logo | "/" | 40 | eager |
|
||||
|
||||
*store = > db.打开*
|
||||
|
||||
*首页CSS = > theme.全局*
|
||||
@@ -73,6 +92,8 @@ import db:db/index.mq.md
|
||||
*page = > page.主体装配 主体=`列表`*
|
||||
*page = > page.排序 排序="-created_at"*
|
||||
*page = > page.样式 样式=`首页CSS`*
|
||||
*page = > page.头装配 表=`头资源`*
|
||||
*page = > page.图片装配 表=`品牌图`*
|
||||
|
||||
*about = > 网页.页面 标题="关于" 引言="<h1>关于本站</h1><p>一个用 Marqdo 的 web 扩展库(ext/web)写成的博客系统。</p><p>它演示了:GFM 表格装配导航与侧栏、SQLite 驱动的主体绑定、动态路由 /post/{slug}、标签归档、以及受 session 保护的后台 CRUD。</p>"*
|
||||
*about = > about.组件装配 组件=`首页`*
|
||||
@@ -104,6 +125,7 @@ import db:db/index.mq.md
|
||||
*app = > app.路由 路径="/tags" 页面=tags*
|
||||
*app = > app.路由 路径="/tag/{slug}" 页面=tagged*
|
||||
*app = > app.静态 目录="public" 挂载="/static"*
|
||||
*app = > app.图标 表=`站点图标`*
|
||||
*app = > app.路由实时 路径="/live" 回显=True*
|
||||
*app = > app.鉴权 用户表=`管理员` 会话时长=3600*
|
||||
> `app`.监听
|
||||
@@ -0,0 +1,2 @@
|
||||
‰PNG
|
||||
|
||||
|
After Width: | Height: | Size: 8 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#1a5f4a"/><text x="16" y="22" text-anchor="middle" font-size="16" font-family="Georgia,serif" fill="#f4f7f5">M</text></svg>
|
||||
|
After Width: | Height: | Size: 226 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#1a5f4a"/><text x="16" y="22" text-anchor="middle" font-size="16" font-family="Georgia,serif" fill="#f4f7f5">M</text></svg>
|
||||
|
After Width: | Height: | Size: 226 B |
@@ -18,6 +18,10 @@ curl -s "$BASE/" | grep -q '@media (max-width: 860px)' && ok "响应式媒体查
|
||||
echo "== 静态 =="
|
||||
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/static/live.js")
|
||||
[ "$code" = "200" ] && ok "GET /static/live.js -> $code" || bad "static -> $code"
|
||||
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/favicon.ico")
|
||||
[ "$code" = "200" ] && ok "GET /favicon.ico -> $code" || bad "favicon -> $code"
|
||||
curl -s "$BASE/" | grep -q 'rel="icon"' && ok "head icon link" || bad "head icon 缺失"
|
||||
curl -s "$BASE/" | grep -q 'mq-images' && ok "图片装配 logo" || bad "mq-images 缺失"
|
||||
|
||||
echo "== 动态路由 =="
|
||||
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/hello-marqdo")
|
||||
|
||||
+60
-4
@@ -24,12 +24,35 @@ Load the ABI v2 `web` plugin once.
|
||||
Assemble a GFM style table into a CSS string. Two shapes are accepted:
|
||||
`|选择器|属性|值|` rule rows (arbitrary selectors; rows sharing a selector are
|
||||
merged, and a leading `|媒体|` column groups rows into `@media` blocks), or
|
||||
`|属性|值|` property rows wrapped as `.name { … }`. Styles stay as data tables,
|
||||
`make_style` turns them into CSS — 样式即数据、装配即函数.
|
||||
`|属性|值|` property rows wrapped as `.name { … }`. Selectors starting with
|
||||
`@keyframes name` emit keyframe blocks (`属性` = stop `from`/`to`/`N%`,
|
||||
`值` = `prop: val` or use `@keyframes name from` + normal 属性/值). Quote CSS
|
||||
values that contain `/` (e.g. `"16/9"`, `"1/5"`); bare `1/5` is integer division.
|
||||
Styles stay as data tables, `make_style` turns them into CSS — 样式即数据、装配即函数.
|
||||
|
||||
> ensure_plugin
|
||||
**> web_style name=`name` table=`table`**
|
||||
|
||||
## make_images
|
||||
+ `table`
|
||||
|
||||
Assemble a GFM image table into an HTML fragment (`div.mq-images` of
|
||||
`<figure class="mq-img">` / `<img>`). Columns: `src`/`alt`/`title`/`class`/
|
||||
`href`/`width`/`height`/`loading`/`caption` (ZH: `源`/`替代`/`标题`/`类`/
|
||||
`链接`/`宽度`/`高度`/`加载`/`图注`). Images stay as data — 图片即数据、装配即函数.
|
||||
|
||||
> ensure_plugin
|
||||
**> web_images table=`table`**
|
||||
|
||||
## make_head
|
||||
+ `table`
|
||||
|
||||
Assemble a Head resource table into HTML (`<link>` / `<script>`). Useful for
|
||||
preview; prefer `page.head` to attach resources to a page.
|
||||
|
||||
> ensure_plugin
|
||||
**> web_head table=`table`**
|
||||
|
||||
# page
|
||||
+ `title`="Marqdo Web"
|
||||
+ `intro`=""
|
||||
@@ -93,10 +116,33 @@ of a list of cards. Set on the dynamic post page so `/post/{slug}` shows one pos
|
||||
## meta
|
||||
+ `meta`
|
||||
|
||||
SEO / OpenGraph metadata as a data table (`|key|value|`). Keys such as `title`, `description`, `canonical`, `og:type` become `<head>` tags at render time.
|
||||
SEO / OpenGraph metadata as a data table (`|key|value|`). Keys such as `title`, `description`, `canonical`, `og:type` become `<head>` tags at render time. Special keys `icon` / `favicon` / `apple-touch-icon` emit `<link rel="…">` (not `<meta name>`).
|
||||
|
||||
**> web_page_meta page=`self` meta=`meta`**
|
||||
|
||||
## head
|
||||
+ `table`
|
||||
|
||||
Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|` or ZH `|关系|地址|类型|…|`). `rel=script` / `module` become `<script>`; other rows become `<link>`. Merges with any existing `head` on the page.
|
||||
|
||||
**> web_page_head page=`self` table=`table`**
|
||||
|
||||
## client_embed
|
||||
+ `bridge`="/static/marqdo-bridge.js"
|
||||
|
||||
Return an HTML snippet that loads the official browser Marqdo bridge (`marqdo-bridge.js`, route C).
|
||||
Run `marqdo wasm build -o static` first, and prefer a `head` table row with `rel=module`.
|
||||
Author `.mq.md` wire/`fetch` effects: [browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md).
|
||||
|
||||
**"<script type=\"module\" src=\"" + bridge + "\"></script>"**
|
||||
|
||||
## images
|
||||
+ `table`
|
||||
|
||||
Assemble an image table (`|src|alt|title|class|href|width|height|loading|caption|`) into HTML and attach it as `images_html` (rendered in main before intro). Same table shape as module-level `make_images`.
|
||||
|
||||
**> web_page_images page=`self` table=`table`**
|
||||
|
||||
## paginate
|
||||
+ `offset`=0
|
||||
+ `limit`=10
|
||||
@@ -429,10 +475,20 @@ Register `GET|POST /_form/{id}` for listen when the form is not already embedded
|
||||
+ `dir`
|
||||
+ `mount`=/static
|
||||
|
||||
Serve files from `dir` under `mount` (default `/static`). Path is resolved from the process working directory at listen time.
|
||||
Serve files from `dir` under `mount` (default `/static`). Path is resolved from the process working directory at listen time. If `dir` contains `favicon.ico` / `favicon.png` / `favicon.svg` and `icons` was not set, listen also serves `GET /favicon.ico` and injects a default `<link rel="icon">` on every page.
|
||||
|
||||
**> web_app_static app=`self` dir=`dir` mount=`mount`**
|
||||
|
||||
## icons
|
||||
+ `table`
|
||||
|
||||
Register site icons from a GFM table (`|path|rel|type|sizes|url|` or ZH
|
||||
`|路径|关系|类型|尺寸|地址|`). Listen serves each file at `url` (default
|
||||
`/favicon.ico` for `.ico` icons, else `/icons/{filename}`), and injects matching
|
||||
`<link>` tags into every page via `site_head`. See [web-assets-and-images.md](../../doc/design/web-assets-and-images.md).
|
||||
|
||||
**> web_app_icons app=`self` table=`table`**
|
||||
|
||||
## configure
|
||||
+ `cors`=None
|
||||
+ `security`=None
|
||||
|
||||
+53
-2
@@ -24,11 +24,32 @@ import sys:lib/sys.mq.md
|
||||
把 GFM 样式表装配成一段 CSS 文本。支持两种表形:
|
||||
`|选择器|属性|值|` 规则行(选择器任意,同一选择器多行合并成一条规则;
|
||||
加 `|媒体|` 列即可分组进 `@media` 块),或 `|属性|值|` 属性行(按 `.名 { … }` 包裹)。
|
||||
选择器以 `@keyframes 名` 开头时输出关键帧块(`属性` 为停点 `from`/`to`/`N%`,
|
||||
`值` 写 `opacity: 0` 等声明;也可用 `@keyframes 名 from` + 普通属性/值)。
|
||||
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1/5"`),否则按表达式除法求值。
|
||||
样式即数据、装配即函数 —— 主题模块据此把样式表拼成完整样式表。
|
||||
|
||||
> 确保插件
|
||||
**> web_style name=`名` table=`表`**
|
||||
|
||||
## 图片装配
|
||||
+ `表`
|
||||
|
||||
把 GFM 图片表装配成 HTML 片段(`div.mq-images` 内若干 `<figure class="mq-img">`)。
|
||||
列:`源`/`替代`/`标题`/`类`/`链接`/`宽度`/`高度`/`加载`/`图注`。
|
||||
图片即数据、装配即函数。
|
||||
|
||||
> 确保插件
|
||||
**> web_images table=`表`**
|
||||
|
||||
## 头资源装配
|
||||
+ `表`
|
||||
|
||||
把 Head 资源表装配成 HTML(`<link>` / `<script>`)。预览用;挂到页面请用 `页面.头装配`。
|
||||
|
||||
> 确保插件
|
||||
**> web_head table=`表`**
|
||||
|
||||
# 页面
|
||||
+ `标题`="站点"
|
||||
+ `引言`=""
|
||||
@@ -84,10 +105,33 @@ import sys:lib/sys.mq.md
|
||||
## 元数据
|
||||
+ `元数据`
|
||||
|
||||
SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`canonical`、`og:type` 等会在渲染时写入 `<head>`。
|
||||
SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`canonical`、`og:type` 等会在渲染时写入 `<head>`。特殊键 `icon` / `favicon` / `apple-touch-icon` 会写成 `<link rel="…">`(不会误写成 `<meta name>`)。
|
||||
|
||||
**> web_page_meta page=`self` meta=`元数据`**
|
||||
|
||||
## 头装配
|
||||
+ `表`
|
||||
|
||||
把 Head 资源表(`|关系|地址|类型|尺寸|媒体|作为|跨域|`)挂到页面的 `head`。`关系=script` / `module` 生成 `<script>`,其余生成 `<link>`。与已有 `head` 合并。
|
||||
|
||||
**> 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)。
|
||||
|
||||
**"<script type=\"module\" src=\"" + 桥 + "\"></script>"**
|
||||
|
||||
## 图片装配
|
||||
+ `表`
|
||||
|
||||
把图片表装配为 HTML,写入 `images_html`(渲染时插在主区引言之前)。表形与模块级 `网页.图片装配` 相同。
|
||||
|
||||
**> web_page_images page=`self` table=`表`**
|
||||
|
||||
## 分页
|
||||
+ `偏移`=0
|
||||
+ `上限`=10
|
||||
@@ -411,10 +455,17 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
+ `目录`
|
||||
+ `挂载`=/static
|
||||
|
||||
将 `目录` 下的文件挂到 `挂载`(默认 `/static`)。路径在 `监听` 时相对进程工作目录解析。
|
||||
将 `目录` 下的文件挂到 `挂载`(默认 `/static`)。路径在 `监听` 时相对进程工作目录解析。若目录内有 `favicon.ico` / `favicon.png` / `favicon.svg` 且未配置 `图标`,则额外提供 `GET /favicon.ico` 并为每页注入默认 `<link rel="icon">`。
|
||||
|
||||
**> web_app_static app=`self` dir=`目录` mount=`挂载`**
|
||||
|
||||
## 图标
|
||||
+ `表`
|
||||
|
||||
用 GFM 表注册站点图标(`|路径|关系|类型|尺寸|地址|`)。`监听` 时按 `地址` 提供文件(`.ico` 默认 `/favicon.ico`,否则 `/icons/{文件名}`),并通过 `site_head` 向全站页面注入对应 `<link>`。设计见 [web-assets-and-images.md](../../doc/design/web-assets-and-images.md)。
|
||||
|
||||
**> web_app_icons app=`self` table=`表`**
|
||||
|
||||
## 装配
|
||||
+ `跨域`=None
|
||||
+ `安全`=None
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
//! Site icons, `<head>` link/script assembly, and image HTML assembly.
|
||||
//! Tables stay data; assembly is a function — 配置即数据、装配即函数.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::table::normalize_ref;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HeadLink {
|
||||
pub rel: String,
|
||||
pub href: String,
|
||||
pub type_: String,
|
||||
pub sizes: String,
|
||||
pub media: String,
|
||||
pub as_: String,
|
||||
pub crossorigin: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct IconRoute {
|
||||
pub url: String,
|
||||
pub path: PathBuf,
|
||||
pub content_type: String,
|
||||
}
|
||||
|
||||
fn cell_str(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Null => String::new(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pick<'a>(m: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
|
||||
keys.iter().find_map(|k| m.get(*k))
|
||||
}
|
||||
|
||||
fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
|
||||
pick(m, keys)
|
||||
.map(|v| normalize_ref(&cell_str(v)))
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
}
|
||||
|
||||
/// Infer Content-Type from file extension.
|
||||
pub fn mime_for_path(path: &str) -> &'static str {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if lower.ends_with(".ico") {
|
||||
"image/x-icon"
|
||||
} else if lower.ends_with(".png") {
|
||||
"image/png"
|
||||
} else if lower.ends_with(".svg") {
|
||||
"image/svg+xml"
|
||||
} else if lower.ends_with(".webp") {
|
||||
"image/webp"
|
||||
} else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
|
||||
"image/jpeg"
|
||||
} else if lower.ends_with(".gif") {
|
||||
"image/gif"
|
||||
} else if lower.ends_with(".webmanifest") || lower.ends_with(".json") {
|
||||
"application/manifest+json"
|
||||
} else if lower.ends_with(".css") {
|
||||
"text/css; charset=utf-8"
|
||||
} else if lower.ends_with(".js") || lower.ends_with(".mjs") {
|
||||
"text/javascript; charset=utf-8"
|
||||
} else {
|
||||
"application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
fn rows_of(table: &Value) -> Vec<Map<String, Value>> {
|
||||
match table {
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.filter_map(|v| v.as_object().cloned())
|
||||
.collect(),
|
||||
Value::Object(m) => {
|
||||
// Columnar GFM: { 关系: […], 地址: […] }
|
||||
let keys: Vec<String> = m.keys().cloned().collect();
|
||||
if keys.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let len = m
|
||||
.values()
|
||||
.filter_map(|v| v.as_array().map(|a| a.len()))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if len == 0 {
|
||||
return vec![m.clone()];
|
||||
}
|
||||
let mut out = Vec::with_capacity(len);
|
||||
for i in 0..len {
|
||||
let mut row = Map::new();
|
||||
for k in &keys {
|
||||
if let Some(Value::Array(a)) = m.get(k) {
|
||||
row.insert(k.clone(), a.get(i).cloned().unwrap_or(Value::Null));
|
||||
} else if i == 0 {
|
||||
row.insert(k.clone(), m.get(k).cloned().unwrap_or(Value::Null));
|
||||
}
|
||||
}
|
||||
out.push(row);
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize a Head resource table → list of HeadLink.
|
||||
pub fn as_head_links(table: &Value) -> Vec<HeadLink> {
|
||||
let mut out = Vec::new();
|
||||
for m in rows_of(table) {
|
||||
let rel = row_str(&m, &["关系", "rel", "Rel"]);
|
||||
let href = row_str(
|
||||
&m,
|
||||
&["地址", "href", "src", "url", "Href", "Src", "URL"],
|
||||
);
|
||||
if href.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rel = if rel.is_empty() {
|
||||
"stylesheet".into()
|
||||
} else {
|
||||
rel
|
||||
};
|
||||
out.push(HeadLink {
|
||||
rel,
|
||||
href,
|
||||
type_: row_str(&m, &["类型", "type", "Type"]),
|
||||
sizes: row_str(&m, &["尺寸", "sizes", "Sizes"]),
|
||||
media: row_str(&m, &["媒体", "media", "Media"]),
|
||||
as_: row_str(&m, &["作为", "as", "As"]),
|
||||
crossorigin: row_str(&m, &["跨域", "crossorigin", "crossOrigin"]),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn head_links_to_json(links: &[HeadLink]) -> Value {
|
||||
Value::Array(
|
||||
links
|
||||
.iter()
|
||||
.map(|l| {
|
||||
json!({
|
||||
"rel": l.rel,
|
||||
"href": l.href,
|
||||
"type": l.type_,
|
||||
"sizes": l.sizes,
|
||||
"media": l.media,
|
||||
"as": l.as_,
|
||||
"crossorigin": l.crossorigin,
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
|
||||
let Some(arr) = v.as_array() else {
|
||||
return as_head_links(v);
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for item in arr {
|
||||
let Some(m) = item.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let href = row_str(m, &["href", "src", "url", "地址"]);
|
||||
if href.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push(HeadLink {
|
||||
rel: row_str(m, &["rel", "关系"]),
|
||||
href,
|
||||
type_: row_str(m, &["type", "类型"]),
|
||||
sizes: row_str(m, &["sizes", "尺寸"]),
|
||||
media: row_str(m, &["media", "媒体"]),
|
||||
as_: row_str(m, &["as", "作为"]),
|
||||
crossorigin: row_str(m, &["crossorigin", "跨域"]),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Render HeadLink list to HTML (link / script tags).
|
||||
pub fn render_head_links(links: &[HeadLink]) -> String {
|
||||
let mut s = String::new();
|
||||
for l in links {
|
||||
let rel = l.rel.trim().to_ascii_lowercase();
|
||||
if rel == "script" || rel == "module" {
|
||||
let mut tag = String::from("<script");
|
||||
if rel == "module" || l.type_ == "module" {
|
||||
tag.push_str(" type=\"module\"");
|
||||
} else if !l.type_.is_empty() {
|
||||
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
|
||||
}
|
||||
if !l.crossorigin.is_empty() {
|
||||
tag.push_str(&format!(" crossorigin=\"{}\"", esc(&l.crossorigin)));
|
||||
}
|
||||
tag.push_str(&format!(" src=\"{}\"></script>", esc(&l.href)));
|
||||
s.push_str(&tag);
|
||||
continue;
|
||||
}
|
||||
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&l.href));
|
||||
if !l.type_.is_empty() {
|
||||
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
|
||||
}
|
||||
if !l.sizes.is_empty() {
|
||||
tag.push_str(&format!(" sizes=\"{}\"", esc(&l.sizes)));
|
||||
}
|
||||
if !l.media.is_empty() {
|
||||
tag.push_str(&format!(" media=\"{}\"", esc(&l.media)));
|
||||
}
|
||||
if !l.as_.is_empty() {
|
||||
tag.push_str(&format!(" as=\"{}\"", esc(&l.as_)));
|
||||
}
|
||||
if !l.crossorigin.is_empty() {
|
||||
tag.push_str(&format!(" crossorigin=\"{}\"", esc(&l.crossorigin)));
|
||||
}
|
||||
tag.push_str("/>");
|
||||
s.push_str(&tag);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Module-level preview: assemble head table → HTML string.
|
||||
pub fn make_head_html(table: &Value) -> String {
|
||||
render_head_links(&as_head_links(table))
|
||||
}
|
||||
|
||||
/// Normalize icons table → (icons json array, site_head links, file routes).
|
||||
pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>) {
|
||||
let mut icons = Vec::new();
|
||||
let mut head = Vec::new();
|
||||
let mut routes = Vec::new();
|
||||
let mut saw_favicon_url = false;
|
||||
|
||||
for m in rows_of(table) {
|
||||
let path = row_str(&m, &["路径", "path", "file", "Path"]);
|
||||
let mut rel = row_str(&m, &["关系", "rel", "Rel"]);
|
||||
if rel.is_empty() {
|
||||
rel = "icon".into();
|
||||
}
|
||||
let mut type_ = row_str(&m, &["类型", "type", "Type"]);
|
||||
let sizes = row_str(&m, &["尺寸", "sizes", "Sizes"]);
|
||||
let mut url = row_str(&m, &["地址", "url", "href", "Href", "URL"]);
|
||||
|
||||
if type_.is_empty() && !path.is_empty() {
|
||||
type_ = mime_for_path(&path).to_string();
|
||||
}
|
||||
if url.is_empty() {
|
||||
if !path.is_empty() {
|
||||
let name = Path::new(&path)
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("icon");
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if rel.to_ascii_lowercase().contains("icon") && lower.ends_with(".ico") {
|
||||
url = "/favicon.ico".into();
|
||||
} else {
|
||||
url = format!("/icons/{name}");
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if url == "/favicon.ico" {
|
||||
saw_favicon_url = true;
|
||||
}
|
||||
|
||||
icons.push(json!({
|
||||
"path": path,
|
||||
"rel": rel,
|
||||
"type": type_,
|
||||
"sizes": sizes,
|
||||
"url": url,
|
||||
}));
|
||||
|
||||
if !url.is_empty() {
|
||||
head.push(HeadLink {
|
||||
rel: rel.clone(),
|
||||
href: url.clone(),
|
||||
type_: type_.clone(),
|
||||
sizes: sizes.clone(),
|
||||
media: String::new(),
|
||||
as_: String::new(),
|
||||
crossorigin: String::new(),
|
||||
});
|
||||
}
|
||||
|
||||
if !path.is_empty() && !url.is_empty() {
|
||||
routes.push(IconRoute {
|
||||
url: url.clone(),
|
||||
path: PathBuf::from(&path),
|
||||
content_type: if type_.is_empty() {
|
||||
mime_for_path(&path).to_string()
|
||||
} else {
|
||||
type_.clone()
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure browser default path if we have an icon file but no /favicon.ico.
|
||||
if !saw_favicon_url {
|
||||
if let Some(first) = icons.iter().find(|v| {
|
||||
v.get("rel")
|
||||
.and_then(|r| r.as_str())
|
||||
.map(|r| r.to_ascii_lowercase().contains("icon"))
|
||||
.unwrap_or(false)
|
||||
&& v.get("path")
|
||||
.and_then(|p| p.as_str())
|
||||
.map(|p| !p.is_empty())
|
||||
.unwrap_or(false)
|
||||
}) {
|
||||
let path = first.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let type_ = first
|
||||
.get("type")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_else(|| mime_for_path(path));
|
||||
routes.push(IconRoute {
|
||||
url: "/favicon.ico".into(),
|
||||
path: PathBuf::from(path),
|
||||
content_type: type_.to_string(),
|
||||
});
|
||||
head.insert(
|
||||
0,
|
||||
HeadLink {
|
||||
rel: "icon".into(),
|
||||
href: "/favicon.ico".into(),
|
||||
type_: type_.to_string(),
|
||||
sizes: first
|
||||
.get("sizes")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
media: String::new(),
|
||||
as_: String::new(),
|
||||
crossorigin: String::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
(Value::Array(icons), head, routes)
|
||||
}
|
||||
|
||||
/// Convention: if static_dir has favicon.ico|png|svg and icons empty, register defaults.
|
||||
pub fn convention_favicon(static_dir: &Path) -> Option<(Vec<HeadLink>, Vec<IconRoute>)> {
|
||||
for name in ["favicon.ico", "favicon.png", "favicon.svg"] {
|
||||
let p = static_dir.join(name);
|
||||
if p.is_file() {
|
||||
let ct = mime_for_path(name).to_string();
|
||||
let head = vec![HeadLink {
|
||||
rel: "icon".into(),
|
||||
href: "/favicon.ico".into(),
|
||||
type_: ct.clone(),
|
||||
sizes: String::new(),
|
||||
media: String::new(),
|
||||
as_: String::new(),
|
||||
crossorigin: String::new(),
|
||||
}];
|
||||
let routes = vec![IconRoute {
|
||||
url: "/favicon.ico".into(),
|
||||
path: p,
|
||||
content_type: ct,
|
||||
}];
|
||||
return Some((head, routes));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Merge site_head into a page value (dedupe by href+rel).
|
||||
pub fn merge_site_head(page: &mut Value, site_head: &[HeadLink]) {
|
||||
if site_head.is_empty() {
|
||||
return;
|
||||
}
|
||||
let obj = match page.as_object_mut() {
|
||||
Some(o) => o,
|
||||
None => return,
|
||||
};
|
||||
let mut existing = obj
|
||||
.get("head")
|
||||
.map(head_links_from_json)
|
||||
.unwrap_or_default();
|
||||
for link in site_head {
|
||||
let dup = existing.iter().any(|e| {
|
||||
e.href == link.href && e.rel.eq_ignore_ascii_case(&link.rel)
|
||||
});
|
||||
if !dup {
|
||||
existing.push(link.clone());
|
||||
}
|
||||
}
|
||||
obj.insert("head".into(), head_links_to_json(&existing));
|
||||
}
|
||||
|
||||
/// GFM image table → HTML fragment.
|
||||
pub fn make_images_html(table: &Value) -> String {
|
||||
let mut figures = String::new();
|
||||
for m in rows_of(table) {
|
||||
let src = row_str(&m, &["源", "src", "Src", "url", "URL"]);
|
||||
if src.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let alt = row_str(&m, &["替代", "alt", "Alt"]);
|
||||
let title = row_str(&m, &["标题", "title", "Title"]);
|
||||
let class = row_str(&m, &["类", "class", "Class"]);
|
||||
let href = row_str(&m, &["链接", "href", "link", "Href", "Link"]);
|
||||
let width = row_str(&m, &["宽度", "width", "Width"]);
|
||||
let height = row_str(&m, &["高度", "height", "Height"]);
|
||||
let mut loading = row_str(&m, &["加载", "loading", "Loading"]);
|
||||
if loading.is_empty() {
|
||||
loading = "lazy".into();
|
||||
}
|
||||
let caption = row_str(&m, &["图注", "caption", "Caption"]);
|
||||
|
||||
let mut img = format!("<img src=\"{}\" alt=\"{}\"", esc(&src), esc(&alt));
|
||||
if !title.is_empty() {
|
||||
img.push_str(&format!(" title=\"{}\"", esc(&title)));
|
||||
}
|
||||
if !width.is_empty() {
|
||||
img.push_str(&format!(" width=\"{}\"", esc(&width)));
|
||||
}
|
||||
if !height.is_empty() {
|
||||
img.push_str(&format!(" height=\"{}\"", esc(&height)));
|
||||
}
|
||||
img.push_str(&format!(" loading=\"{}\"/>", esc(&loading)));
|
||||
|
||||
let inner = if href.is_empty() {
|
||||
img
|
||||
} else {
|
||||
format!("<a href=\"{}\">{}</a>", esc(&href), img)
|
||||
};
|
||||
|
||||
let fig_class = if class.is_empty() {
|
||||
"mq-img".into()
|
||||
} else {
|
||||
format!("mq-img {}", class)
|
||||
};
|
||||
figures.push_str(&format!("<figure class=\"{}\">{}", fig_class, inner));
|
||||
if !caption.is_empty() {
|
||||
figures.push_str(&format!("<figcaption>{}</figcaption>", esc(&caption)));
|
||||
}
|
||||
figures.push_str("</figure>");
|
||||
}
|
||||
if figures.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
format!("<div class=\"mq-images\" data-slot=\"main\">{figures}</div>")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn images_basic() {
|
||||
let t = json!([
|
||||
{"源": "/a.png", "替代": "A", "类": "logo", "加载": "eager"}
|
||||
]);
|
||||
let h = make_images_html(&t);
|
||||
assert!(h.contains("mq-images"));
|
||||
assert!(h.contains("src=\"/a.png\""));
|
||||
assert!(h.contains("loading=\"eager\""));
|
||||
assert!(h.contains("class=\"mq-img logo\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_script_and_icon() {
|
||||
let t = json!([
|
||||
{"关系": "icon", "地址": "/favicon.ico", "类型": "image/x-icon"},
|
||||
{"关系": "script", "地址": "/static/a.js"}
|
||||
]);
|
||||
let h = make_head_html(&t);
|
||||
assert!(h.contains("rel=\"icon\""));
|
||||
assert!(h.contains("<script src=\"/static/a.js\"></script>"));
|
||||
}
|
||||
}
|
||||
+102
-27
@@ -26,6 +26,34 @@ use crate::sitemap;
|
||||
use crate::storage;
|
||||
use crate::upload;
|
||||
|
||||
fn with_site_head(base: &Value, site_head: &[crate::assets::HeadLink]) -> Value {
|
||||
let mut page = base.clone();
|
||||
crate::assets::merge_site_head(&mut page, site_head);
|
||||
page
|
||||
}
|
||||
|
||||
fn serve_icon_file(path: PathBuf, content_type: String) -> Response {
|
||||
match std::fs::read(&path) {
|
||||
Ok(bytes) => {
|
||||
let ct = HeaderValue::from_str(&content_type)
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
|
||||
(
|
||||
StatusCode::OK,
|
||||
[
|
||||
(header::CONTENT_TYPE, ct),
|
||||
(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("public, max-age=86400"),
|
||||
),
|
||||
],
|
||||
bytes,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(_) => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct UploadRoute {
|
||||
pub field: String,
|
||||
@@ -58,6 +86,8 @@ pub struct AppState {
|
||||
/// Optional assembled pages for 404 / 500.
|
||||
page_404: Option<Value>,
|
||||
page_500: Option<Value>,
|
||||
/// Default `<head>` links from `app.icons` / static favicon convention.
|
||||
site_head: Vec<crate::assets::HeadLink>,
|
||||
}
|
||||
|
||||
fn collect_page_forms(
|
||||
@@ -107,6 +137,8 @@ pub fn listen(
|
||||
gates: Vec<(String, Vec<String>)>,
|
||||
gallery_routes: HashMap<String, Value>,
|
||||
middleware: &Middleware,
|
||||
mut site_head: Vec<crate::assets::HeadLink>,
|
||||
mut icon_routes: Vec<crate::assets::IconRoute>,
|
||||
) -> Result<Value, String> {
|
||||
let mut form_owners = HashMap::new();
|
||||
collect_page_forms(page, &mut forms, &mut form_owners);
|
||||
@@ -120,6 +152,20 @@ pub fn listen(
|
||||
});
|
||||
session::reset(session_ttl);
|
||||
rate_limit::reset();
|
||||
|
||||
// Convention: static_dir/favicon.* → /favicon.ico when no explicit icons.
|
||||
if icon_routes.is_empty() {
|
||||
if let Some(dir) = static_dir.as_ref() {
|
||||
if let Some((head, routes)) = crate::assets::convention_favicon(dir) {
|
||||
site_head = head;
|
||||
icon_routes = routes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve relative icon paths: try as-is absolute, else leave for entry_dir resolve in lib.
|
||||
// (Absolute paths preferred; relative already joined in web_listen.)
|
||||
|
||||
let state = Arc::new(AppState {
|
||||
page: page.clone(),
|
||||
db_url: db_url.map(|s| s.to_string()),
|
||||
@@ -133,6 +179,7 @@ pub fn listen(
|
||||
download_routes: download_routes.clone(),
|
||||
page_404: page_404.clone(),
|
||||
page_500: page_500.clone(),
|
||||
site_head: site_head.clone(),
|
||||
});
|
||||
|
||||
let mut app = Router::new()
|
||||
@@ -165,6 +212,7 @@ pub fn listen(
|
||||
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap, Path(params): Path<HashMap<String, String>>| {
|
||||
let mut p = page_for_render.clone();
|
||||
inject_params(&mut p, ¶ms);
|
||||
let p = with_site_head(&p, &st.site_head);
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf))).into_response();
|
||||
append_set_cookie(&mut resp, set_cookie);
|
||||
@@ -188,7 +236,8 @@ pub fn listen(
|
||||
&path,
|
||||
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap| {
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let mut resp = Html(render::render_page(&page_for_render, st.db_url.as_deref(), Some(&csrf)))
|
||||
let p = with_site_head(&page_for_render, &st.site_head);
|
||||
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf)))
|
||||
.into_response();
|
||||
append_set_cookie(&mut resp, set_cookie);
|
||||
resp
|
||||
@@ -293,6 +342,36 @@ pub fn listen(
|
||||
app = app.nest_service(&mount, svc);
|
||||
}
|
||||
|
||||
// Root / custom icon file routes (favicon.ico, /icons/…).
|
||||
for ir in icon_routes {
|
||||
let url = ir.url.clone();
|
||||
if !url.starts_with('/') {
|
||||
return Err(format!("icon url `{url}` must start with /"));
|
||||
}
|
||||
if !ir.path.is_file() {
|
||||
return Err(format!(
|
||||
"icon file `{}` not found for `{url}`",
|
||||
ir.path.display()
|
||||
));
|
||||
}
|
||||
eprintln!(
|
||||
"marqdo web icon: {} → {} ({})",
|
||||
url,
|
||||
ir.path.display(),
|
||||
ir.content_type
|
||||
);
|
||||
let path = ir.path.clone();
|
||||
let ct = ir.content_type.clone();
|
||||
app = app.route(
|
||||
&url,
|
||||
get(move || {
|
||||
let path = path.clone();
|
||||
let ct = ct.clone();
|
||||
async move { serve_icon_file(path, ct) }
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let mut redir_paths: Vec<String> = redirects.keys().cloned().collect();
|
||||
redir_paths.sort();
|
||||
for path in redir_paths {
|
||||
@@ -435,7 +514,8 @@ fn rss_feed(st: &AppState, _path: &str, cfg: &Value) -> Response {
|
||||
|
||||
async fn home(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let html = render::render_page(&st.page, st.db_url.as_deref(), Some(&csrf));
|
||||
let page = with_site_head(&st.page, &st.site_head);
|
||||
let html = render::render_page(&page, st.db_url.as_deref(), Some(&csrf));
|
||||
let mut resp = Html(html).into_response();
|
||||
append_set_cookie(&mut resp, set_cookie);
|
||||
resp
|
||||
@@ -1131,16 +1211,6 @@ fn flash_html(flash: Option<&str>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_cell(s: &str, max: usize) -> String {
|
||||
let mut it = s.chars();
|
||||
let head: String = it.by_ref().take(max).collect();
|
||||
if it.next().is_some() {
|
||||
format!("{head}…")
|
||||
} else {
|
||||
head
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) -> String {
|
||||
let tables = st
|
||||
.db_url
|
||||
@@ -1190,7 +1260,7 @@ fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) ->
|
||||
<style>
|
||||
:root {{ --ink:#1c1917; --muted:#78716c; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; --ok:#166534; --err:#b91c1c; --side:#f5f5f4; }}
|
||||
* {{ box-sizing:border-box; }}
|
||||
body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; background:var(--paper); color:var(--ink); min-height:100vh; display:grid; grid-template-columns:14rem 1fr; }}
|
||||
body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; background:var(--paper); color:var(--ink); min-height:100vh; display:grid; grid-template-columns:14rem minmax(0,1fr); }}
|
||||
@media (max-width:720px) {{ body {{ grid-template-columns:1fr; }} .admin-nav {{ border-right:0; border-bottom:1px solid var(--line); }} }}
|
||||
.admin-nav {{ background:var(--side); border-right:1px solid var(--line); padding:1.1rem 1rem 1.5rem; }}
|
||||
.admin-nav .brand {{ display:block; font-weight:600; font-size:1.05rem; margin-bottom:1rem; color:var(--ink); }}
|
||||
@@ -1200,7 +1270,7 @@ body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; backgro
|
||||
.admin-nav .nav-label {{ margin:1.1rem 0 .35rem; font-size:.75rem; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); }}
|
||||
.admin-nav .nav-foot {{ margin-top:1.5rem; font-size:.9rem; }}
|
||||
.admin-nav .muted {{ color:var(--muted); font-size:.9rem; }}
|
||||
.admin-main {{ padding:1.25rem 1.5rem 2rem; max-width:56rem; }}
|
||||
.admin-main {{ padding:1.25rem 1.5rem 2rem; min-width:0; width:100%; max-width:none; overflow-x:auto; }}
|
||||
.admin-main h1 {{ margin:0 0 .35rem; font-size:1.65rem; }}
|
||||
.crumbs {{ color:var(--muted); font-size:.85rem; margin-bottom:1rem; }}
|
||||
.crumbs a {{ color:var(--muted); }}
|
||||
@@ -1210,21 +1280,23 @@ body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; backgro
|
||||
.btn:hover {{ filter:brightness(1.05); }}
|
||||
.btn-muted {{ background:#78716c; }}
|
||||
.btn-ghost {{ background:transparent; color:var(--accent)!important; border:1px solid var(--line); }}
|
||||
table.data {{ width:100%; border-collapse:collapse; background:#fff; border:1px solid var(--line); border-radius:6px; overflow:hidden; }}
|
||||
table.data th,table.data td {{ border-bottom:1px solid var(--line); padding:.55rem .7rem; text-align:left; vertical-align:top; font-size:.92rem; }}
|
||||
table.data th {{ background:#f5f5f4; font-weight:600; }}
|
||||
.table-wrap {{ width:100%; overflow-x:auto; -webkit-overflow-scrolling:touch; border:1px solid var(--line); border-radius:6px; background:#fff; }}
|
||||
table.data {{ width:100%; min-width:100%; border-collapse:collapse; background:#fff; }}
|
||||
table.data th,table.data td {{ border-bottom:1px solid var(--line); padding:.55rem .7rem; text-align:left; vertical-align:top; font-size:.92rem; word-break:break-word; overflow-wrap:anywhere; white-space:pre-wrap; }}
|
||||
table.data th {{ background:#f5f5f4; font-weight:600; white-space:nowrap; }}
|
||||
table.data tr:last-child td {{ border-bottom:0; }}
|
||||
table.data .actions {{ white-space:nowrap; }}
|
||||
table.data .actions {{ white-space:nowrap; overflow-wrap:normal; word-break:normal; }}
|
||||
.empty {{ background:#fff; border:1px dashed var(--line); border-radius:6px; padding:2rem 1.25rem; text-align:center; color:var(--muted); }}
|
||||
.empty strong {{ display:block; color:var(--ink); margin-bottom:.35rem; font-size:1.05rem; }}
|
||||
.flash {{ padding:.65rem .85rem; border-radius:4px; margin:0 0 1rem; }}
|
||||
.flash.ok {{ background:#ecfdf5; color:var(--ok); border:1px solid #a7f3d0; }}
|
||||
.flash.err {{ background:#fef2f2; color:var(--err); border:1px solid #fecaca; }}
|
||||
.danger {{ color:var(--err); }}
|
||||
.site-form {{ max-width:28rem; margin-top:.5rem; }}
|
||||
.site-form {{ max-width:min(48rem,100%); width:100%; margin-top:.5rem; }}
|
||||
.site-form form {{ display:grid; gap:.85rem; }}
|
||||
.site-form label {{ display:grid; gap:.25rem; font-size:.9rem; }}
|
||||
.site-form input,.site-form textarea {{ padding:.5rem .6rem; border:1px solid var(--line); border-radius:4px; font:inherit; background:#fff; }}
|
||||
.site-form input,.site-form textarea {{ padding:.5rem .6rem; border:1px solid var(--line); border-radius:4px; font:inherit; background:#fff; width:100%; box-sizing:border-box; }}
|
||||
.site-form textarea {{ min-height:8rem; resize:vertical; field-sizing:content; }}
|
||||
.site-form input[readonly] {{ background:#f5f5f4; color:var(--muted); }}
|
||||
.site-form .err {{ color:var(--err); font-size:.85rem; }}
|
||||
.site-form .actions {{ display:flex; gap:.75rem; align-items:center; flex-wrap:wrap; }}
|
||||
@@ -1283,14 +1355,14 @@ async fn admin_home(
|
||||
"<div class=\"empty\"><strong>No tables</strong>Initialize a table via <code>db.init</code> / <code>数据库.初始化</code>.</div>",
|
||||
);
|
||||
} else {
|
||||
inner.push_str("<table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
|
||||
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
|
||||
for t in &tables {
|
||||
inner.push_str(&format!(
|
||||
"<tr><td><a href=\"/admin/{t}\">{t}</a></td><td class=\"actions\"><a class=\"btn\" href=\"/admin/{t}/new\">New</a></td></tr>",
|
||||
t = esc(t)
|
||||
));
|
||||
}
|
||||
inner.push_str("</tbody></table>");
|
||||
inner.push_str("</tbody></table></div>");
|
||||
}
|
||||
Html(admin_shell(&st, "Admin", None, &inner)).into_response()
|
||||
}
|
||||
@@ -1353,7 +1425,7 @@ async fn admin_table(
|
||||
esc(&table)
|
||||
));
|
||||
} else {
|
||||
inner.push_str("<table class=\"data\"><thead><tr>");
|
||||
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr>");
|
||||
for c in &cols {
|
||||
inner.push_str(&format!("<th>{}</th>", esc(c)));
|
||||
}
|
||||
@@ -1370,7 +1442,8 @@ async fn admin_table(
|
||||
other => other.to_string(),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
inner.push_str(&format!("<td>{}</td>", esc(&truncate_cell(&cell, 80))));
|
||||
// Show full cell text; CSS wraps / table-wrap scrolls when needed.
|
||||
inner.push_str(&format!("<td>{}</td>", esc(&cell)));
|
||||
}
|
||||
let id = m
|
||||
.get("id")
|
||||
@@ -1388,7 +1461,7 @@ async fn admin_table(
|
||||
}
|
||||
inner.push_str("</tr>");
|
||||
}
|
||||
inner.push_str("</tbody></table>");
|
||||
inner.push_str("</tbody></table></div>");
|
||||
}
|
||||
Html(admin_shell(&st, &table, Some(&table), &inner)).into_response()
|
||||
}
|
||||
@@ -1638,7 +1711,8 @@ fn sitemap_response(st: &AppState, cfg: &Value) -> Response {
|
||||
async fn fallback_404(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let html = if let Some(ref page) = st.page_404 {
|
||||
render::render_page(page, st.db_url.as_deref(), Some(&csrf))
|
||||
let page = with_site_head(page, &st.site_head);
|
||||
render::render_page(&page, st.db_url.as_deref(), Some(&csrf))
|
||||
} else {
|
||||
"<!doctype html><html><head><title>404</title></head><body><h1>404 Not Found</h1></body></html>"
|
||||
.to_string()
|
||||
@@ -1652,7 +1726,8 @@ async fn fallback_404(State(st): State<Arc<AppState>>, headers: axum::http::Head
|
||||
#[allow(dead_code)]
|
||||
fn error_500(st: &AppState, csrf: Option<&str>, msg: &str) -> Response {
|
||||
let html = if let Some(ref page) = st.page_500 {
|
||||
render::render_page(page, st.db_url.as_deref(), csrf)
|
||||
let page = with_site_head(page, &st.site_head);
|
||||
render::render_page(&page, st.db_url.as_deref(), csrf)
|
||||
} else {
|
||||
format!(
|
||||
"<!doctype html><html><head><title>500</title></head><body><h1>500</h1><p>{}</p></body></html>",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Marqdo web plugin (C ABI v2): SQLite, page assemble, HTTP listen.
|
||||
|
||||
mod assets;
|
||||
mod compose;
|
||||
mod db;
|
||||
mod db_pg;
|
||||
@@ -373,6 +374,93 @@ web_ffi!(web_page_meta, |args: &Value| {
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_head, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("head"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
let links = crate::assets::as_head_links(&table);
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
let mut existing = obj
|
||||
.get("head")
|
||||
.map(crate::assets::head_links_from_json)
|
||||
.unwrap_or_default();
|
||||
for link in links {
|
||||
let dup = existing
|
||||
.iter()
|
||||
.any(|e| e.href == link.href && e.rel.eq_ignore_ascii_case(&link.rel));
|
||||
if !dup {
|
||||
existing.push(link);
|
||||
}
|
||||
}
|
||||
obj.insert("head".into(), crate::assets::head_links_to_json(&existing));
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_head, |args: &Value| {
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("head"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
Ok(Value::String(crate::assets::make_head_html(&table)))
|
||||
});
|
||||
|
||||
web_ffi!(web_images, |args: &Value| {
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("images"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
Ok(Value::String(crate::assets::make_images_html(&table)))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_images, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("images"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
let html = crate::assets::make_images_html(&table);
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
let prev = obj
|
||||
.get("images_html")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let combined = if prev.is_empty() {
|
||||
html
|
||||
} else if html.is_empty() {
|
||||
prev
|
||||
} else {
|
||||
format!("{prev}{html}")
|
||||
};
|
||||
obj.insert("images_html".into(), json!(combined));
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_app_icons, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("icons"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
let (icons, site_head, _routes) = crate::assets::normalize_icons(&table);
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
obj.insert("icons".into(), icons);
|
||||
obj.insert(
|
||||
"site_head".into(),
|
||||
crate::assets::head_links_to_json(&site_head),
|
||||
);
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_page_paginate, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let offset = args
|
||||
@@ -1424,6 +1512,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
gallery_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
site_head,
|
||||
icon_routes,
|
||||
) = if args.get("page").is_some() || args.get("host").is_some() {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let db_url = db_url_of(args).ok();
|
||||
@@ -1478,6 +1568,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
HashMap::new(),
|
||||
middleware::Middleware::default(),
|
||||
cookie_secure,
|
||||
Vec::<crate::assets::HeadLink>::new(),
|
||||
Vec::<crate::assets::IconRoute>::new(),
|
||||
)
|
||||
} else {
|
||||
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
|
||||
@@ -1684,6 +1776,20 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
.get("cookie_secure")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let (site_head, icon_routes) = if let Some(icons) = app.get("icons") {
|
||||
let (_icons_json, head, routes) = crate::assets::normalize_icons(icons);
|
||||
// Prefer precomputed site_head if present (same content).
|
||||
let head = app
|
||||
.get("site_head")
|
||||
.map(crate::assets::head_links_from_json)
|
||||
.filter(|h| !h.is_empty())
|
||||
.unwrap_or(head);
|
||||
(head, routes)
|
||||
} else if let Some(sh) = app.get("site_head") {
|
||||
(crate::assets::head_links_from_json(sh), Vec::new())
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
(
|
||||
page,
|
||||
db_url,
|
||||
@@ -1709,6 +1815,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
gallery_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
site_head,
|
||||
icon_routes,
|
||||
)
|
||||
};
|
||||
let static_dir = static_dir.map(|p| {
|
||||
@@ -1718,6 +1826,32 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
entry_dir().join(p)
|
||||
}
|
||||
});
|
||||
let icon_routes: Vec<crate::assets::IconRoute> = icon_routes
|
||||
.into_iter()
|
||||
.map(|mut r| {
|
||||
if !r.path.is_absolute() {
|
||||
let joined = entry_dir().join(&r.path);
|
||||
if joined.is_file() {
|
||||
r.path = joined;
|
||||
} else if let Some(ref sd) = static_dir {
|
||||
let name = r
|
||||
.path
|
||||
.file_name()
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| r.path.clone());
|
||||
let in_static = sd.join(&name);
|
||||
if in_static.is_file() {
|
||||
r.path = in_static;
|
||||
} else {
|
||||
r.path = joined;
|
||||
}
|
||||
} else {
|
||||
r.path = joined;
|
||||
}
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect();
|
||||
http::listen(
|
||||
&page,
|
||||
db_url.as_deref(),
|
||||
@@ -1743,6 +1877,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
gates,
|
||||
gallery_routes,
|
||||
&middleware,
|
||||
site_head,
|
||||
icon_routes,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -1816,6 +1952,23 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
"page,meta",
|
||||
web_page_meta as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_head",
|
||||
"page,table",
|
||||
web_page_head as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_images",
|
||||
"page,table",
|
||||
web_page_images as PluginFn,
|
||||
),
|
||||
("web_head", "table", web_head as PluginFn),
|
||||
("web_images", "table", web_images as PluginFn),
|
||||
(
|
||||
"web_app_icons",
|
||||
"app,table",
|
||||
web_app_icons as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_paginate",
|
||||
"page,offset,limit,path",
|
||||
|
||||
@@ -376,6 +376,18 @@ fn head_html(args: &Value, default_title: &str) -> String {
|
||||
"canonical" => {
|
||||
s.push_str(&format!("<link rel=\"canonical\" href=\"{}\"/>", esc(&val)));
|
||||
}
|
||||
"icon" | "favicon" => {
|
||||
s.push_str(&format!(
|
||||
"<link rel=\"icon\" href=\"{}\"/>",
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
"apple-touch-icon" | "apple_touch_icon" => {
|
||||
s.push_str(&format!(
|
||||
"<link rel=\"apple-touch-icon\" href=\"{}\"/>",
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
k if k.starts_with("og:") => {
|
||||
s.push_str(&format!(
|
||||
"<meta property=\"{}\" content=\"{}\"/>",
|
||||
@@ -393,6 +405,10 @@ fn head_html(args: &Value, default_title: &str) -> String {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(head) = args.get("head") {
|
||||
let links = crate::assets::head_links_from_json(head);
|
||||
s.push_str(&crate::assets::render_head_links(&links));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
@@ -476,6 +492,11 @@ pub fn render_page_ex(
|
||||
};
|
||||
|
||||
let mut main_html = String::new();
|
||||
if let Some(images) = args.get("images_html").and_then(|v| v.as_str()) {
|
||||
if !images.is_empty() {
|
||||
main_html.push_str(images);
|
||||
}
|
||||
}
|
||||
if !intro.is_empty() {
|
||||
main_html.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
@@ -579,6 +600,11 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
|
||||
_ => {
|
||||
let (intro, items, _total) = resolve_main(args, db_url);
|
||||
let mut body = String::new();
|
||||
if let Some(images) = args.get("images_html").and_then(|v| v.as_str()) {
|
||||
if !images.is_empty() {
|
||||
body.push_str(images);
|
||||
}
|
||||
}
|
||||
if !intro.is_empty() {
|
||||
body.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
|
||||
+238
-109
@@ -310,13 +310,16 @@ pub fn normalize_slot(name: &str) -> String {
|
||||
|
||||
/// Style table → CSS text.
|
||||
///
|
||||
/// Three table shapes are supported:
|
||||
/// Table shapes:
|
||||
/// 1. Rule rows `|媒体|选择器|属性|值|` — rows grouped by `媒体` emit
|
||||
/// `@media { … }` blocks; rows sharing a selector are merged into one rule.
|
||||
/// 2. Rule rows `|选择器|属性|值|` — each row emits `selector { prop: value; }`,
|
||||
/// rows sharing a selector are merged into one rule. `selector` may be any
|
||||
/// CSS selector (`aside.side`, `ul.side-nav a:hover`).
|
||||
/// 3. Plain property rows `|属性|值|` — emitted as `.name { prop: value; }`.
|
||||
/// 4. **`@keyframes`** — selector `@keyframes name` (optional stop in the
|
||||
/// selector: `@keyframes name from`) or stop in the `属性` column:
|
||||
/// `|@keyframes fade|from|opacity: 0|` → nested keyframe rules.
|
||||
///
|
||||
/// Examples (rule shape):
|
||||
/// ```text
|
||||
@@ -327,8 +330,9 @@ pub fn normalize_slot(name: &str) -> String {
|
||||
/// | 选择器 | 属性 | 值 |
|
||||
/// |--------|------|-----|
|
||||
/// | aside.side | padding | 2rem 1.25rem |
|
||||
/// | aside.side | background | #f5f5f4 |
|
||||
/// | ul.side-nav a:hover | color | var(--accent) |
|
||||
/// | @keyframes pulse | 0% | opacity: 0 |
|
||||
/// | @keyframes pulse | 100% | opacity: 1 |
|
||||
/// | @keyframes pulse from | opacity | 0 |
|
||||
/// ```
|
||||
pub fn as_css_named(name: &str, table: &Value) -> String {
|
||||
let name = normalize_ref(name);
|
||||
@@ -338,9 +342,6 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
|
||||
let mut out = String::new();
|
||||
match table {
|
||||
Value::Object(m) => {
|
||||
// Column-first table object: `{选择器:[…], 属性:[…], 值:[…], 媒体:[…]}`
|
||||
// (how GFM tables reach the plugin). Row-major maps (one rule per map)
|
||||
// are handled too: if 选择器 is a scalar, treat it as a single row.
|
||||
let sels = pick(m, SEL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let props = pick(m, PROP_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let vals = pick(m, VAL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
@@ -359,117 +360,201 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
// Group by media then selector; or plain `.name { … }` when no selectors.
|
||||
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
for (media, sel, p, v) in rows {
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let decl = format!(" {p}: {v};");
|
||||
if !media.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((media.clone(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else if !sel.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((String::new(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else {
|
||||
plain.push(decl);
|
||||
}
|
||||
}
|
||||
for (media, rules) in by_media {
|
||||
if media.is_empty() {
|
||||
for (sel, decls) in rules {
|
||||
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
|
||||
}
|
||||
} else {
|
||||
let inner = rules
|
||||
.iter()
|
||||
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
|
||||
}
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
out.push_str(&format!(".{} {{\n{}\n}}\n", name, plain.join("\n")));
|
||||
}
|
||||
emit_css_rows(&rows, &name, &mut out);
|
||||
}
|
||||
Value::Array(rows) => {
|
||||
// Group rule rows by media query and selector; plain rows as `.name { … }`.
|
||||
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
for row in rows {
|
||||
let Some(m) = row.as_object() else { continue };
|
||||
let media = pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default();
|
||||
let sel = pick(m, SEL_KEYS).map(cell_str).unwrap_or_default();
|
||||
let p = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default();
|
||||
let v = pick(m, VAL_KEYS).map(cell_str).unwrap_or_default();
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let decl = format!(" {p}: {v};");
|
||||
if !media.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((media.clone(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else if !sel.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((String::new(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else {
|
||||
plain.push(decl);
|
||||
}
|
||||
}
|
||||
for (media, rules) in by_media {
|
||||
if media.is_empty() {
|
||||
for (sel, decls) in rules {
|
||||
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
|
||||
}
|
||||
} else {
|
||||
let inner = rules
|
||||
.iter()
|
||||
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
|
||||
}
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
out.push_str(&format!(".{} {{\n{}\n}}\n", name, plain.join("\n")));
|
||||
}
|
||||
let rows: Vec<(String, String, String, String)> = rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let m = row.as_object()?;
|
||||
Some((
|
||||
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
|
||||
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
|
||||
pick(m, PROP_KEYS).map(cell_str).unwrap_or_default(),
|
||||
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
emit_css_rows(&rows, &name, &mut out);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parse `@keyframes name` or `@keyframes name stop` from a selector cell.
|
||||
fn parse_keyframes_sel(sel: &str) -> Option<(String, Option<String>)> {
|
||||
let t = sel.trim();
|
||||
if t.len() < 10 || !t[..10].eq_ignore_ascii_case("@keyframes") {
|
||||
return None;
|
||||
}
|
||||
let rest = t[10..].trim();
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// First token = animation name; optional second = keyframe stop.
|
||||
let mut parts = rest.split_whitespace();
|
||||
let anim = parts.next()?.to_string();
|
||||
let stop = parts.next().map(|s| s.to_string());
|
||||
Some((anim, stop))
|
||||
}
|
||||
|
||||
fn is_keyframe_stop(s: &str) -> bool {
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if t.eq_ignore_ascii_case("from") || t.eq_ignore_ascii_case("to") {
|
||||
return true;
|
||||
}
|
||||
// 0%, 50%, 100.5%, etc.
|
||||
let stripped = t.trim_end_matches('%');
|
||||
!stripped.is_empty()
|
||||
&& stripped
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_digit() || c == '.')
|
||||
&& t.ends_with('%')
|
||||
}
|
||||
|
||||
fn keyframe_decl_lines(css_prop: &str, value: &str) -> Vec<String> {
|
||||
// Value may be a full declaration (`opacity: 0`) or bare value when the
|
||||
// CSS property lived in the selector form `@keyframes name from` + 属性.
|
||||
let v = value.trim().trim_end_matches(';').trim();
|
||||
if v.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
if v.contains(':') {
|
||||
v.split(';')
|
||||
.map(|p| p.trim())
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(|p| format!(" {p};"))
|
||||
.collect()
|
||||
} else if !css_prop.is_empty() && !is_keyframe_stop(css_prop) {
|
||||
// `@keyframes name from` + 属性=opacity + 值=0
|
||||
vec![format!(" {css_prop}: {v};")]
|
||||
} else {
|
||||
// Bare value — prefer `opacity: 0` in the 值 column.
|
||||
vec![format!(" {v};")]
|
||||
}
|
||||
}
|
||||
|
||||
fn push_keyframe(
|
||||
groups: &mut Vec<(String, Vec<(String, Vec<String>)>)>,
|
||||
anim: &str,
|
||||
stop: &str,
|
||||
decls: Vec<String>,
|
||||
) {
|
||||
if anim.is_empty() || stop.is_empty() || decls.is_empty() {
|
||||
return;
|
||||
}
|
||||
let anim_group = match groups.iter_mut().find(|(n, _)| n == anim) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
groups.push((anim.to_string(), Vec::new()));
|
||||
&mut groups.last_mut().unwrap().1
|
||||
}
|
||||
};
|
||||
match anim_group.iter_mut().find(|(s, _)| s == stop) {
|
||||
Some((_, d)) => d.extend(decls),
|
||||
None => anim_group.push((stop.to_string(), decls)),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_css_rows(rows: &[(String, String, String, String)], class_name: &str, out: &mut String) {
|
||||
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut by_keyframes: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
|
||||
for (media, sel, p, v) in rows {
|
||||
let media = media.trim();
|
||||
let sel = sel.trim();
|
||||
let p = p.trim();
|
||||
let v = v.trim();
|
||||
|
||||
if let Some((anim, stop_in_sel)) = parse_keyframes_sel(sel) {
|
||||
let stop_from_sel = stop_in_sel.is_some();
|
||||
let (stop, prop_for_decl) = match stop_in_sel {
|
||||
Some(s) => (s, p.to_string()),
|
||||
None => {
|
||||
// 属性 = keyframe stop (from / to / N%); 值 = declaration(s)
|
||||
if !is_keyframe_stop(p) {
|
||||
continue;
|
||||
}
|
||||
(p.to_string(), String::new())
|
||||
}
|
||||
};
|
||||
let decls = if stop_from_sel {
|
||||
keyframe_decl_lines(&prop_for_decl, v)
|
||||
} else {
|
||||
keyframe_decl_lines("", v)
|
||||
};
|
||||
let decls = if decls.is_empty() && !v.is_empty() && !prop_for_decl.is_empty() {
|
||||
keyframe_decl_lines(&prop_for_decl, v)
|
||||
} else {
|
||||
decls
|
||||
};
|
||||
push_keyframe(&mut by_keyframes, &anim, &stop, decls);
|
||||
continue;
|
||||
}
|
||||
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let decl = format!(" {p}: {v};");
|
||||
if !media.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((media.to_string(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, sel, decl);
|
||||
} else if !sel.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((String::new(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, sel, decl);
|
||||
} else {
|
||||
plain.push(decl);
|
||||
}
|
||||
}
|
||||
|
||||
for (media, rules) in by_media {
|
||||
if media.is_empty() {
|
||||
for (sel, decls) in rules {
|
||||
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
|
||||
}
|
||||
} else {
|
||||
let inner = rules
|
||||
.iter()
|
||||
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
|
||||
}
|
||||
}
|
||||
for (anim, stops) in by_keyframes {
|
||||
out.push_str(&format!("@keyframes {} {{\n", anim));
|
||||
for (stop, decls) in stops {
|
||||
out.push_str(&format!(" {} {{\n", stop));
|
||||
out.push_str(&decls.join("\n"));
|
||||
out.push('\n');
|
||||
out.push_str(" }\n");
|
||||
}
|
||||
out.push_str("}\n");
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
out.push_str(&format!(".{} {{\n{}\n}}\n", class_name, plain.join("\n")));
|
||||
}
|
||||
}
|
||||
|
||||
/// Push `decl` under `sel` into a `(selector, declarations)` group list,
|
||||
/// merging declarations when the selector already exists.
|
||||
fn push_rule(groups: &mut Vec<(String, Vec<String>)>, sel: &str, decl: String) {
|
||||
@@ -614,3 +699,47 @@ fn meta_text(v: &Value) -> String {
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod css_tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn keyframes_stop_in_prop() {
|
||||
let t = json!([
|
||||
{"选择器": "@keyframes pulse", "属性": "0%", "值": "opacity: 0"},
|
||||
{"选择器": "@keyframes pulse", "属性": "100%", "值": "opacity: 1"},
|
||||
]);
|
||||
let css = as_css_named("anim", &t);
|
||||
assert!(css.contains("@keyframes pulse {"), "{css}");
|
||||
assert!(css.contains("0% {"), "{css}");
|
||||
assert!(css.contains("opacity: 0;"), "{css}");
|
||||
assert!(css.contains("100% {"), "{css}");
|
||||
assert!(!css.contains("0%: opacity"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframes_stop_in_selector() {
|
||||
let t = json!([
|
||||
{"选择器": "@keyframes fade from", "属性": "opacity", "值": "0"},
|
||||
{"选择器": "@keyframes fade to", "属性": "opacity", "值": "1"},
|
||||
]);
|
||||
let css = as_css_named("anim", &t);
|
||||
assert!(css.contains("@keyframes fade {"), "{css}");
|
||||
assert!(css.contains("from {"), "{css}");
|
||||
assert!(css.contains("opacity: 0;"), "{css}");
|
||||
assert!(css.contains("to {"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_still_works() {
|
||||
let t = json!([
|
||||
{"媒体": "(max-width: 800px)", "选择器": ".x", "属性": "color", "值": "red"},
|
||||
]);
|
||||
let css = as_css_named("x", &t);
|
||||
assert!(css.contains("@media (max-width: 800px)"), "{css}");
|
||||
assert!(css.contains(".x {"), "{css}");
|
||||
assert!(css.contains("color: red;"), "{css}");
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ ext/llm — OpenAI-compatible chat. Design: doc/design/ext-llm.md
|
||||
|
||||
ext/agent — agent framework + native plugin. Design: doc/design/ext-agent.md
|
||||
|
||||
ext/web — HTTP / SQLite·Postgres site helpers + native plugin. **W0–W7 + P3 complete** (middleware, CRUD+FTS, security, SEO/RSS, upload/gallery, RBAC, sitemap). Design: doc/design/ext-web.md · capabilities: doc/design/web-net-capabilities.md · example: examples/marqdo-blog/
|
||||
ext/web — HTTP / SQLite·Postgres site helpers + native plugin. **W0–W7 + P3 + W8** (middleware, CRUD+FTS, security, SEO/RSS, upload/gallery, RBAC, sitemap, favicon/head/images). **Browser embed (v0.3.2+)**: `web.client_embed` mounts WASM client scripts — build with `marqdo wasm build`; examples: examples/browser-hello/. Design: doc/design/ext-web.md · capabilities: doc/design/web-net-capabilities.md · WASM: doc/adr/0002-browser-marqdo-wasm.md · example: examples/marqdo-blog/
|
||||
|
||||
ext/quantum — circuits, draw, noise, formula matrix custom gates, Q7 density/viz, Q8 themed SVG (`theme=dark|light|bw`). Design: doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ ext/llm(大模型)— OpenAI 兼容聊天。设计:doc/design/ext-llm.md
|
||||
|
||||
ext/agent(智能体)— 智能体框架 + 原生插件。设计:doc/design/ext-agent.md
|
||||
|
||||
ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件。设计:doc/design/ext-web.md
|
||||
ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件。**W0–W7 + P3 + W8**。**浏览器挂载(v0.3.2+)**:`网页.客户端挂载` / `web.client_embed`;先 `marqdo wasm build`;示例 examples/browser-hello/。设计:doc/design/ext-web.md · WASM:doc/adr/0002-browser-marqdo-wasm.md
|
||||
|
||||
ext/quantum(量子)— 电路、绘图、噪声、公式矩阵自定义门、Q7 密度/高级图、Q8 主题 SVG(`主题=dark|light|bw`)。设计:doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation a
|
||||
|
||||
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
|
||||
|
||||
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [`.cursor/skills/marqdo-release/SKILL.md`](../../.cursor/skills/marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
|
||||
|
||||
## Hard rules (do not violate)
|
||||
|
||||
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
|
||||
@@ -154,6 +156,7 @@ Import **one language file** — never mix EN/ZH API names in the same `.mq.md`:
|
||||
|
||||
- Authors use **GFM tables + `#` classes** — no `json.parse` / `json.set` glue, no hand-built part JSON.
|
||||
- Table cells stay **literal strings**; path text like `` `posts`.`title` `` is resolved by web classes.
|
||||
- **Quote path/MIME cells** that contain `/` (T5 cell expressions treat bare `/` as division): `"/static/logo.svg"`, `"image/png"`.
|
||||
- **`ext/**` never calls `host_*`** — hot path is native `plugins/web` ABI.
|
||||
- HTTPS: terminate at reverse proxy; set `cookie_secure=True` on auth (no in-process TLS).
|
||||
|
||||
@@ -164,17 +167,18 @@ index.mq.md # entry + home page table + listen
|
||||
pages/ # sub-pages
|
||||
components/ # reusable |属性|值|样式| tables
|
||||
styles/ # CSS modules
|
||||
public/ # static + favicon.ico|png|svg
|
||||
db/ # schema + open/init
|
||||
data/ # sqlite runtime (gitignore)
|
||||
```
|
||||
|
||||
**Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`.
|
||||
|
||||
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.render` → `app` with `route` / `static` / `configure` / `listen`.
|
||||
**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`.
|
||||
|
||||
**Shipped surface (W0–W7 + P3):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads.
|
||||
**Shipped surface (W0–W7 + P3 + W8):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`).
|
||||
|
||||
Design: [ext-web.md](../../doc/design/ext-web.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
|
||||
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
|
||||
|
||||
Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md).
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//! 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;
|
||||
use crate::Backend;
|
||||
|
||||
/// Persistent Marqdo program for the browser host bridge.
|
||||
///
|
||||
/// Session calls (`call`) use the **tree** interpreter so entry bindings persist
|
||||
/// across handlers (C3). One-shot [`crate::run_source`] may still use bytecode.
|
||||
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)> {
|
||||
Self::boot_with(source, Backend::Tree)
|
||||
}
|
||||
|
||||
/// Like [`Self::boot`]. `Backend::Bytecode` is rejected for sessions (no shared entry env yet).
|
||||
pub fn boot_with(source: &str, backend: Backend) -> Result<(Self, Value)> {
|
||||
if source.trim().is_empty() {
|
||||
bail!("source is empty");
|
||||
}
|
||||
if backend != Backend::Tree {
|
||||
bail!("browser session requires tree backend (bytecode has no entry-env invoke yet)");
|
||||
}
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_mq_load_returns_fetch_effect() {
|
||||
let src = std::fs::read_to_string("examples/browser-hello/fetch.mq.md")
|
||||
.expect("fetch.mq.md");
|
||||
let (mut sess, wire) = BrowserSession::boot(&src).expect("boot");
|
||||
assert!(matches!(wire, Value::List(_)));
|
||||
let v = sess.call("load", "{}").expect("load");
|
||||
let j = value_as_json(&v).unwrap();
|
||||
assert_eq!(j["set_text"]["#status"], "loading…");
|
||||
assert_eq!(j["fetch"]["then"], "on_uuid");
|
||||
assert!(j["fetch"]["url"].as_str().unwrap().contains("httpbin"));
|
||||
let done = sess
|
||||
.call(
|
||||
"on_uuid",
|
||||
r#"{"ok":true,"status":200,"body":"{\"uuid\":\"x\"}"}"#,
|
||||
)
|
||||
.expect("on_uuid");
|
||||
let jd = value_as_json(&done).unwrap();
|
||||
assert!(jd["set_text"]["#status"].as_str().unwrap().contains("uuid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_rejects_bytecode_backend() {
|
||||
let err = BrowserSession::boot_with("# main\n\n> print text=x\n", Backend::Bytecode)
|
||||
.err()
|
||||
.expect("err");
|
||||
assert!(err.to_string().contains("tree backend"));
|
||||
}
|
||||
}
|
||||
+54
-4
@@ -194,6 +194,11 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
let base = PathBuf::from(h);
|
||||
candidates.push(base.join("native").join(&name));
|
||||
candidates.push(base.join(&name));
|
||||
// MARQDO_EXT_SOURCE often points at repo `ext/`; native libs live in sibling target/.
|
||||
if let Some(repo) = base.parent() {
|
||||
candidates.push(repo.join("target").join("debug").join(&name));
|
||||
candidates.push(repo.join("target").join("release").join(&name));
|
||||
}
|
||||
}
|
||||
// Honor CARGO_TARGET_DIR (sandbox / custom target roots) before cwd/target.
|
||||
if let Ok(td) = env::var("CARGO_TARGET_DIR") {
|
||||
@@ -205,6 +210,15 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
candidates.push(cwd.join("target").join("debug").join(&name));
|
||||
candidates.push(cwd.join("target").join("release").join(&name));
|
||||
candidates.push(cwd.join("ext").join("native").join(&name));
|
||||
// Walk up looking for a Cargo workspace target/ (run from a subdir).
|
||||
let mut dir = cwd.clone();
|
||||
for _ in 0..6 {
|
||||
candidates.push(dir.join("target").join("debug").join(&name));
|
||||
candidates.push(dir.join("target").join("release").join(&name));
|
||||
if !dir.pop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(exe) = env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
@@ -213,6 +227,7 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
candidates.push(dir.join(&name));
|
||||
// target/debug/deps → target/debug
|
||||
candidates.push(dir.join("..").join(&name));
|
||||
candidates.push(dir.join("..").join("release").join(&name));
|
||||
}
|
||||
}
|
||||
for p in &candidates {
|
||||
@@ -221,8 +236,35 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
}
|
||||
}
|
||||
bail!(
|
||||
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_{short}`, or `marqdo ext add {short}`, or set {env_key})"
|
||||
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_{short}`, or set {env_key})"
|
||||
)
|
||||
}
|
||||
|
||||
/// Locate a built native plugin, or `cargo build -p …` once then look again.
|
||||
fn ensure_native_plugin(crate_name: &str) -> Result<PathBuf> {
|
||||
let short = native_short_name(crate_name);
|
||||
if let Ok(p) = find_native_plugin(short) {
|
||||
return Ok(p);
|
||||
}
|
||||
println!(
|
||||
"native plugin for `{short}` not found; building `{crate_name}` (debug)…"
|
||||
);
|
||||
let status = std::process::Command::new("cargo")
|
||||
.args(["build", "-p", crate_name])
|
||||
.status()
|
||||
.with_context(|| format!("spawn cargo build -p {crate_name}"))?;
|
||||
if !status.success() {
|
||||
bail!(
|
||||
"cargo build -p {crate_name} failed (status {status}); build the plugin then re-run `marqdo ext add {short}`"
|
||||
);
|
||||
}
|
||||
find_native_plugin(short).with_context(|| {
|
||||
format!(
|
||||
"built `{crate_name}` but still cannot find {}; set {} to the .so/.dll path",
|
||||
native_lib_filename(short),
|
||||
native_env_var(short)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_ext(id: &str) -> Result<()> {
|
||||
@@ -240,6 +282,14 @@ pub fn add_ext(id: &str) -> Result<()> {
|
||||
fs::create_dir_all(&root)
|
||||
.with_context(|| format!("create install root {}", root.display()))?;
|
||||
|
||||
// Preflight native binary *before* copying .mq.md so a missing .so does not
|
||||
// leave a half-installed tree that fails at `plugin.native_path` / load time.
|
||||
let native_src = if let Some(crate_name) = pkg.native_crate {
|
||||
Some(ensure_native_plugin(crate_name)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
for f in pkg.mq_files {
|
||||
let src = find_source_file(f)?;
|
||||
let dest = root.join(f);
|
||||
@@ -252,10 +302,9 @@ pub fn add_ext(id: &str) -> Result<()> {
|
||||
println!("installed {}", dest.display());
|
||||
}
|
||||
|
||||
if let Some(crate_name) = pkg.native_crate {
|
||||
if let (Some(crate_name), Some(src)) = (pkg.native_crate, native_src) {
|
||||
let short = native_short_name(crate_name);
|
||||
let lib_name = native_lib_filename(short);
|
||||
let src = find_native_plugin(short)?;
|
||||
let native_dir = root.join("native");
|
||||
fs::create_dir_all(&native_dir)?;
|
||||
let dest = native_dir.join(&lib_name);
|
||||
@@ -270,7 +319,8 @@ pub fn add_ext(id: &str) -> Result<()> {
|
||||
fs::write(&hint, abs.to_string_lossy().as_bytes())?;
|
||||
println!("wrote {}", hint.display());
|
||||
println!(
|
||||
"hint: import works via install root; set {}={} if load_native needs it",
|
||||
"hint: `plugin.native_path name={short}` resolves via {}; or set {}={}",
|
||||
dest.display(),
|
||||
native_env_var(short),
|
||||
abs.display()
|
||||
);
|
||||
|
||||
+223
-51
@@ -2,7 +2,11 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
|
||||
use crate::host::{fs, json, math, net, sys, time, writeback, HostContext};
|
||||
#[cfg(feature = "exec-host")]
|
||||
use crate::host::{foreign, subtask};
|
||||
#[cfg(feature = "plugin-host")]
|
||||
use crate::host::plugin;
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -648,22 +652,52 @@ pub fn call_host(
|
||||
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
|
||||
HostFn::JsonKeys => json::keys(require(bound, "value")?),
|
||||
HostFn::JsonQuote => json::quote(require(bound, "text")?),
|
||||
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?, bound.get("headers")),
|
||||
HostFn::HttpPost => net::http_post(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
),
|
||||
HostFn::HttpPostSse => net::http_post_sse(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
bound.get("echo"),
|
||||
),
|
||||
HostFn::HttpGet => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_get(ctx, require(bound, "url")?, bound.get("headers"))
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_get unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::HttpPost => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_post(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_post unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::HttpPostSse => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_post_sse(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
bound.get("echo"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_post_sse unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::OpenAiSseParse => {
|
||||
net::openai_sse_parse(require(bound, "text")?, bound.get("echo"))
|
||||
}
|
||||
@@ -671,14 +705,24 @@ pub fn call_host(
|
||||
crate::host::event_bus::publish(require(bound, "event")?);
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
HostFn::HttpRequest => net::http_request(
|
||||
ctx,
|
||||
require(bound, "method")?,
|
||||
require(bound, "url")?,
|
||||
bound.get("body"),
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
),
|
||||
HostFn::HttpRequest => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_request(
|
||||
ctx,
|
||||
require(bound, "method")?,
|
||||
require(bound, "url")?,
|
||||
bound.get("body"),
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_request unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
|
||||
HostFn::Pi => math::pi(),
|
||||
HostFn::EConst => math::e_const(),
|
||||
@@ -756,33 +800,111 @@ pub fn call_host(
|
||||
bound.get("path"),
|
||||
bound.get("grid"),
|
||||
),
|
||||
HostFn::ForeignSetCmd => foreign::set_cmd(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "cmd")?,
|
||||
bound.get("args"),
|
||||
),
|
||||
HostFn::ForeignRun => foreign::run(ctx, require(bound, "code")?, bound.get("stdin")),
|
||||
HostFn::ForeignRunLang => foreign::run_lang(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "source")?,
|
||||
bound.get("stdin"),
|
||||
),
|
||||
HostFn::ForeignLangs => foreign::langs(ctx),
|
||||
HostFn::PluginLoad => plugin::load(ctx, require(bound, "path")?),
|
||||
HostFn::PluginUnload => plugin::unload(ctx),
|
||||
HostFn::PluginList => plugin::list(ctx),
|
||||
HostFn::ForeignSetCmd => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::set_cmd(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "cmd")?,
|
||||
bound.get("args"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignRun => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignRunLang => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::run_lang(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "source")?,
|
||||
bound.get("stdin"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignLangs => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::langs(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Ok(Value::List(Vec::new()))
|
||||
}
|
||||
}
|
||||
HostFn::PluginLoad => {
|
||||
#[cfg(feature = "plugin-host")]
|
||||
{
|
||||
plugin::load(ctx, require(bound, "path")?)
|
||||
}
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("plugin.load unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::PluginUnload => {
|
||||
#[cfg(feature = "plugin-host")]
|
||||
{
|
||||
plugin::unload(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Err("plugin.unload unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::PluginList => {
|
||||
#[cfg(feature = "plugin-host")]
|
||||
{
|
||||
plugin::list(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Ok(Value::List(Vec::new()))
|
||||
}
|
||||
}
|
||||
HostFn::ExtNativePath => {
|
||||
let name = require(bound, "name")?;
|
||||
let s = match name {
|
||||
Value::Text(t) => t.as_str(),
|
||||
_ => return Err("name must be text".into()),
|
||||
};
|
||||
Ok(match crate::ext_cli::installed_native_path(s) {
|
||||
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
|
||||
None => Value::None,
|
||||
})
|
||||
#[cfg(feature = "cli")]
|
||||
{
|
||||
Ok(match crate::ext_cli::installed_native_path(s) {
|
||||
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
|
||||
None => Value::None,
|
||||
})
|
||||
}
|
||||
#[cfg(not(feature = "cli"))]
|
||||
{
|
||||
let _ = s;
|
||||
Ok(Value::None)
|
||||
}
|
||||
}
|
||||
HostFn::MapSet => {
|
||||
super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
|
||||
@@ -899,11 +1021,61 @@ pub fn call_host(
|
||||
bound.get("line"),
|
||||
)
|
||||
}
|
||||
HostFn::SubtaskSpawn => subtask::spawn(ctx, bound),
|
||||
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskWaitAll => subtask::wait_all(ctx),
|
||||
HostFn::SubtaskSpawn => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::spawn(ctx, bound)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskPoll => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::poll(ctx, require(bound, "id")?)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskJoin => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::join(ctx, require(bound, "id")?)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskKill => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::kill(ctx, require(bound, "id")?)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskWaitAll => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::wait_all(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,21 @@ pub mod agent_rt;
|
||||
pub mod collection;
|
||||
mod dispatch;
|
||||
pub mod event_bus;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign;
|
||||
mod fs;
|
||||
pub(crate) mod json;
|
||||
pub mod math;
|
||||
mod net;
|
||||
#[cfg(feature = "plugin-host")]
|
||||
pub mod plugin;
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
#[path = "plugin_stub.rs"]
|
||||
pub mod plugin;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod subtask;
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
#[path = "subtask_stub.rs"]
|
||||
pub mod subtask;
|
||||
mod sys;
|
||||
mod time;
|
||||
@@ -80,6 +89,7 @@ pub struct HostContext {
|
||||
/// Entry-file line of each active user call (for writeback anchoring).
|
||||
pub call_site_lines: Vec<u32>,
|
||||
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
|
||||
#[cfg_attr(not(feature = "exec-host"), allow(dead_code))]
|
||||
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
|
||||
pub subtask_seq: u64,
|
||||
}
|
||||
|
||||
+14
-2
@@ -1,10 +1,14 @@
|
||||
//! HTTP host primitives (HTTP and HTTPS via ureq).
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::io::Write;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::io::{BufRead, BufReader};
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
#[cfg(feature = "net-host")]
|
||||
use crate::host::HostContext;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
@@ -13,6 +17,7 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
|
||||
let Some(h) = headers else {
|
||||
return Ok(Vec::new());
|
||||
@@ -27,6 +32,7 @@ fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn http_exchange(
|
||||
method: &str,
|
||||
url: &str,
|
||||
@@ -84,6 +90,7 @@ fn http_exchange(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn response_map(status: u16, body: String) -> Value {
|
||||
Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
@@ -91,6 +98,7 @@ fn response_map(status: u16, body: String) -> Value {
|
||||
])
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_get(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
@@ -105,6 +113,7 @@ pub fn http_get(
|
||||
Ok(response_map(status, body))
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_post(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
@@ -127,6 +136,7 @@ pub fn http_post(
|
||||
}
|
||||
|
||||
/// Generic request: method + url + optional body / content_type / headers.
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_request(
|
||||
ctx: &HostContext,
|
||||
method: &Value,
|
||||
@@ -630,6 +640,7 @@ pub fn openai_sse_parse(text: &Value, echo: Option<&Value>) -> Result<Value, Str
|
||||
Ok(Value::List(openai_chat_sse_events(text, echo)?))
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn read_sse_body_to_events<R: BufRead>(
|
||||
mut reader: R,
|
||||
echo: bool,
|
||||
@@ -755,6 +766,7 @@ fn read_sse_body_to_events<R: BufRead>(
|
||||
}
|
||||
|
||||
/// POST and consume OpenAI-compatible SSE; return `{status, events}` list of stream maps.
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_post_sse(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
|
||||
+20
-6
@@ -4,6 +4,7 @@ use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use libloading::{Library, Symbol};
|
||||
|
||||
@@ -273,8 +274,10 @@ unsafe extern "C" fn host_query(
|
||||
"cwd" => Ok(serde_json::Value::String(
|
||||
ctx.cwd.to_string_lossy().into_owned(),
|
||||
)),
|
||||
"entry_dir" => Ok(serde_json::Value::String(
|
||||
ctx.entry_path
|
||||
"entry_dir" => {
|
||||
// Script directory: parent of entry file (for_run also sets ctx.cwd to this).
|
||||
let dir = ctx
|
||||
.entry_path
|
||||
.as_ref()
|
||||
.map(|p| {
|
||||
if p.is_dir() {
|
||||
@@ -283,10 +286,21 @@ unsafe extern "C" fn host_query(
|
||||
p.parent().unwrap_or(p).to_path_buf()
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| ctx.cwd.clone())
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
)),
|
||||
.unwrap_or_else(|| ctx.cwd.clone());
|
||||
// Absolutize against the *process* cwd — not ctx.cwd. For a relative
|
||||
// entry like `tests/ext/foo.mq.md`, for_run sets ctx.cwd = `tests/ext`;
|
||||
// joining that again would yield `tests/ext/tests/ext/...`.
|
||||
let abs = if dir.is_absolute() {
|
||||
dir
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join(dir)
|
||||
};
|
||||
Ok(serde_json::Value::String(
|
||||
abs.to_string_lossy().into_owned(),
|
||||
))
|
||||
}
|
||||
"call_lib_path" => (|| {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Stub plugin surface when `plugin-host` is disabled (browser wasm).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub const ABI_VERSION: u32 = 2;
|
||||
pub const ABI_VERSION_MIN: u32 = 1;
|
||||
|
||||
/// Hook: resolve bare `lib.member` (unused without native plugins).
|
||||
pub struct LibPathCall {
|
||||
pub call: fn(*mut (), &str) -> Result<Value, String>,
|
||||
pub data: *mut (),
|
||||
}
|
||||
|
||||
pub fn with_lib_path_call<R>(_hook: LibPathCall, body: impl FnOnce() -> R) -> R {
|
||||
body()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegisteredFn {
|
||||
pub params: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct PluginState;
|
||||
|
||||
impl PluginState {
|
||||
pub fn get(&self, _name: &str) -> Option<&RegisteredFn> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn list_names(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result<Value, String> {
|
||||
Err("plugin.load unavailable in browser wasm".into())
|
||||
}
|
||||
|
||||
pub fn unload(_ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Err("plugin.unload unavailable in browser wasm".into())
|
||||
}
|
||||
|
||||
pub fn list(_ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(Vec::new()))
|
||||
}
|
||||
|
||||
pub fn call_registered(
|
||||
_ctx: &mut HostContext,
|
||||
name: &str,
|
||||
_bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
Err(format!("plugin `{name}` unavailable in browser wasm"))
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Stub subtask surface when `exec-host` is disabled (browser wasm).
|
||||
|
||||
use crate::host::HostContext;
|
||||
|
||||
/// Placeholder handle type so `HostContext.subtasks` still type-checks.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Handle;
|
||||
|
||||
pub fn kill_all(_ctx: &mut HostContext) {}
|
||||
+17
-1
@@ -1,5 +1,6 @@
|
||||
//! System / process host primitives.
|
||||
|
||||
#[cfg(feature = "exec-host")]
|
||||
use std::process::Command;
|
||||
|
||||
use crate::host::HostContext;
|
||||
@@ -97,10 +98,24 @@ pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
|
||||
if ctx.soft_side_effects {
|
||||
return Err(format!("exit {c} (soft mode does not terminate process)"));
|
||||
}
|
||||
std::process::exit(c as i32);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err(format!("exit {c} unavailable in browser wasm"));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::process::exit(c as i32);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Value, String> {
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, cmd, args);
|
||||
return Err("exec unavailable in browser wasm".into());
|
||||
}
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
if !ctx.allow_exec() {
|
||||
return Err("exec denied by host policy".into());
|
||||
}
|
||||
@@ -123,6 +138,7 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
|
||||
.status()
|
||||
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(1) as i64))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+37
-13
@@ -1,7 +1,8 @@
|
||||
//! Time host primitives.
|
||||
|
||||
use std::thread;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use std::time::Duration;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
|
||||
@@ -9,19 +10,34 @@ use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn now_unix() -> Result<Value, String> {
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_unix: {e}"))?
|
||||
.as_secs();
|
||||
Ok(Value::Int(secs as i64))
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
// No wall clock on wasm32-unknown-unknown without JS bridge (C4).
|
||||
return Err("now_unix unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_unix: {e}"))?
|
||||
.as_secs();
|
||||
Ok(Value::Int(secs as i64))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now_ms() -> Result<Value, String> {
|
||||
let ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_ms: {e}"))?
|
||||
.as_millis();
|
||||
Ok(Value::Int(ms as i64))
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err("now_ms unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_ms: {e}"))?
|
||||
.as_millis();
|
||||
Ok(Value::Int(ms as i64))
|
||||
}
|
||||
}
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
@@ -65,7 +81,15 @@ pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
thread::sleep(Duration::from_millis(n));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(n));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = Duration::from_millis(n);
|
||||
// Browser wasm has no blocking sleep; ignore (C0/C1).
|
||||
}
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
+11
-8
@@ -3,7 +3,9 @@
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
use std::io::{self, BufRead, Read, Write};
|
||||
use std::io::{self, BufRead, Write};
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -146,11 +148,11 @@ fn strip_block_indent(line: &str) -> String {
|
||||
}
|
||||
|
||||
pub fn stdin_is_tty() -> bool {
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
{
|
||||
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
#[cfg(not(all(unix, feature = "tty")))]
|
||||
{
|
||||
false
|
||||
}
|
||||
@@ -181,13 +183,13 @@ fn normalize_prompt(prompt: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
struct TermGuard {
|
||||
fd: i32,
|
||||
original: libc::termios,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
impl TermGuard {
|
||||
fn enter_cbreak() -> Result<Self> {
|
||||
let fd = libc::STDIN_FILENO;
|
||||
@@ -206,7 +208,7 @@ impl TermGuard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
impl Drop for TermGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
@@ -215,6 +217,7 @@ impl Drop for TermGuard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
|
||||
let mut out = io::stdout().lock();
|
||||
// CR + clear whole line, then reprint (fixes CJK backspace display desync).
|
||||
@@ -224,7 +227,7 @@ fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
/// Interactive line editor: UTF-8 char backspace + full-line redraw.
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
|
||||
let prompt = normalize_prompt(prompt);
|
||||
let _guard = TermGuard::enter_cbreak()?;
|
||||
@@ -290,7 +293,7 @@ fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[cfg(not(all(unix, feature = "tty")))]
|
||||
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
|
||||
let prompt = normalize_prompt(prompt);
|
||||
print!("{prompt}");
|
||||
|
||||
@@ -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);
|
||||
|
||||
+86
-1
@@ -5,13 +5,16 @@
|
||||
|
||||
pub mod aliases;
|
||||
pub mod ast;
|
||||
pub mod browser_session;
|
||||
pub mod builtin;
|
||||
pub mod bytecode;
|
||||
pub mod capture;
|
||||
#[cfg(feature = "cli")]
|
||||
pub mod catalog;
|
||||
pub mod debug;
|
||||
pub mod diagnostics;
|
||||
pub mod embedded_lib;
|
||||
#[cfg(feature = "cli")]
|
||||
pub mod ext_cli;
|
||||
pub mod foreign;
|
||||
pub mod formula;
|
||||
@@ -23,8 +26,12 @@ pub mod lex;
|
||||
pub mod load;
|
||||
pub mod parse;
|
||||
pub mod value;
|
||||
#[cfg(feature = "net-host")]
|
||||
pub mod version_check;
|
||||
#[cfg(feature = "view")]
|
||||
pub mod view;
|
||||
#[cfg(feature = "cli")]
|
||||
pub mod wasm_cli;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
@@ -36,7 +43,9 @@ use crate::bytecode::{compile_module, Vm};
|
||||
use crate::capture::RunCapture;
|
||||
use crate::interp::Interpreter;
|
||||
use crate::lex::{classify_source, format_lines_dump};
|
||||
use crate::load::load_module;
|
||||
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 {
|
||||
@@ -293,3 +302,79 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run source text in-memory (browser wasm / tests). Imports resolve via embedded `lib/` only.
|
||||
pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
|
||||
if source.trim().is_empty() {
|
||||
bail!("source is empty");
|
||||
}
|
||||
let stdin_lines = crate::input_feed::effective_stdin(source, &opts.stdin_lines);
|
||||
let module = load_module_from_source(source)?;
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let mut host = HostContext::for_capture(None, opts.host_caps());
|
||||
host.set_entry_source(None, source);
|
||||
host.argv = opts.argv.clone();
|
||||
if let Some(root) = &opts.fs_root {
|
||||
host.fs_root = Some(root.clone());
|
||||
}
|
||||
if let Some(lim) = opts.sleep_limit_ms {
|
||||
host.sleep_limit_ms = Some(lim);
|
||||
}
|
||||
let mut interp = Interpreter::with_capture(None, false)
|
||||
.with_stdin(stdin_lines)
|
||||
.with_host(host);
|
||||
let value = interp.run_module(&module)?;
|
||||
let plots = interp.take_plots();
|
||||
Ok(RunCapture {
|
||||
stdout: interp.captured_stdout,
|
||||
value,
|
||||
plots,
|
||||
bindings: interp.entry_bindings,
|
||||
})
|
||||
}
|
||||
Backend::Bytecode => {
|
||||
let program = compile_module(None, &module)?;
|
||||
let mut host = HostContext::for_capture(None, opts.host_caps());
|
||||
host.set_entry_source(None, source);
|
||||
host.argv = opts.argv.clone();
|
||||
if let Some(root) = &opts.fs_root {
|
||||
host.fs_root = Some(root.clone());
|
||||
}
|
||||
if let Some(lim) = opts.sleep_limit_ms {
|
||||
host.sleep_limit_ms = Some(lim);
|
||||
}
|
||||
let mut vm = Vm::with_capture(None)
|
||||
.with_stdin(stdin_lines)
|
||||
.with_host(host);
|
||||
let value = vm.run(&program)?;
|
||||
let plots = vm.take_plots();
|
||||
Ok(RunCapture {
|
||||
stdout: vm.captured_stdout,
|
||||
value,
|
||||
plots,
|
||||
bindings: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_source_hello() {
|
||||
let cap = run_source("# main\n\n> print text=Hello World!\n", &RunOptions::default())
|
||||
.expect("run_source");
|
||||
assert_eq!(cap.stdout, "Hello World!\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_source_hello_bytecode() {
|
||||
let mut opts = RunOptions::default();
|
||||
opts.backend = Backend::Bytecode;
|
||||
let cap = run_source("# main\n\n> print text=Hello World!\n", &opts).expect("bc");
|
||||
assert_eq!(cap.stdout, "Hello World!\n");
|
||||
}
|
||||
}
|
||||
+57
-8
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
|
||||
use crate::ast::{Function, Module};
|
||||
use crate::ast::Module;
|
||||
use crate::diagnostics::Diagnostic;
|
||||
use crate::embedded_lib;
|
||||
use crate::parse::parse_source;
|
||||
@@ -212,14 +212,63 @@ fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Kept for tests / tooling that expect a flat list (local tops only).
|
||||
#[allow(dead_code)]
|
||||
fn merge_top_level(into: &mut Vec<Function>, fun: Function) {
|
||||
if let Some(existing) = into.iter_mut().find(|f| f.name == fun.name) {
|
||||
*existing = fun;
|
||||
} else {
|
||||
into.push(fun);
|
||||
/// Load a module from source text. Imports may only resolve to the embedded
|
||||
/// `lib/…` stdlib (no filesystem / `ext/` for this MVP path).
|
||||
pub fn load_module_from_source(source: &str) -> Result<Module> {
|
||||
let mut visited = HashSet::new();
|
||||
load_module_from_source_inner(source, "<memory>", &mut visited)
|
||||
}
|
||||
|
||||
fn load_module_from_source_inner(
|
||||
source: &str,
|
||||
label: &str,
|
||||
visited: &mut HashSet<PathBuf>,
|
||||
) -> Result<Module> {
|
||||
let key = PathBuf::from(label);
|
||||
if !visited.insert(key.clone()) {
|
||||
bail!("circular import involving {label}");
|
||||
}
|
||||
|
||||
let result = (|| {
|
||||
let mut module = parse_source(source).map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
|
||||
let imports = module.imports.clone();
|
||||
let mut import_modules = HashMap::new();
|
||||
for imp in imports {
|
||||
let dep = load_embedded_import(&imp.path, visited)?;
|
||||
if import_modules.contains_key(&imp.bind) {
|
||||
bail!("duplicate import bind `{}` while loading {label}", imp.bind);
|
||||
}
|
||||
import_modules.insert(imp.bind, dep);
|
||||
}
|
||||
module.import_modules = import_modules;
|
||||
crate::inherit::validate_inheritance(&module)
|
||||
.map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
|
||||
Ok(module)
|
||||
})();
|
||||
|
||||
visited.remove(&key);
|
||||
result
|
||||
}
|
||||
|
||||
fn load_embedded_import(rel: &str, visited: &mut HashSet<PathBuf>) -> Result<Module> {
|
||||
let rel = rel.replace('\\', "/");
|
||||
let rest = if let Some(r) = rel.strip_prefix("lib/") {
|
||||
r.to_string()
|
||||
} else if let Some(r) = rel.strip_prefix("std/") {
|
||||
r.to_string()
|
||||
} else if embedded_lib::read_file(&rel).is_some() {
|
||||
rel.clone()
|
||||
} else {
|
||||
bail!(
|
||||
"import `{rel}` is not an embedded lib/ path — \
|
||||
run_source only resolves embedded stdlib (lib/…); filesystem and ext/ imports are unsupported"
|
||||
);
|
||||
};
|
||||
let Some(dep_source) = embedded_lib::read_file(&rest) else {
|
||||
bail!("embedded lib not found: lib/{rest}");
|
||||
};
|
||||
let label = format!("lib/{rest}");
|
||||
load_module_from_source_inner(&dep_source, &label, visited)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+21
@@ -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)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
//! `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 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([
|
||||
"build",
|
||||
"-p",
|
||||
"marqdo-wasm",
|
||||
"--target",
|
||||
"wasm32-unknown-unknown",
|
||||
"--profile",
|
||||
"release-wasm",
|
||||
])
|
||||
.status()
|
||||
.context("failed to spawn cargo (is it on PATH?)")?;
|
||||
if !status.success() {
|
||||
bail!("cargo build -p marqdo-wasm --profile release-wasm failed with {status}");
|
||||
}
|
||||
|
||||
let mut artifact = find_wasm_artifact()?;
|
||||
std::fs::create_dir_all(out_dir)
|
||||
.with_context(|| format!("create {}", out_dir.display()))?;
|
||||
|
||||
if let Some(optimized) = try_wasm_opt(&artifact)? {
|
||||
artifact = optimized;
|
||||
}
|
||||
|
||||
let dest_wasm = out_dir.join("marqdo_wasm.wasm");
|
||||
std::fs::copy(&artifact, &dest_wasm).with_context(|| {
|
||||
format!(
|
||||
"copy {} → {}",
|
||||
artifact.display(),
|
||||
dest_wasm.display()
|
||||
)
|
||||
})?;
|
||||
let bytes = std::fs::metadata(&dest_wasm)
|
||||
.map(|m| m.len())
|
||||
.unwrap_or(0);
|
||||
println!(
|
||||
"wrote {} ({:.1} KiB)",
|
||||
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(())
|
||||
}
|
||||
|
||||
fn find_bridge_js() -> Result<PathBuf> {
|
||||
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::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
}
|
||||
|
||||
fn try_wasm_opt(input: &Path) -> Result<Option<PathBuf>> {
|
||||
let which = Command::new("wasm-opt").arg("--version").output();
|
||||
let Ok(out) = which else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !out.status.success() {
|
||||
return Ok(None);
|
||||
}
|
||||
let tmp = input.with_extension("opt.wasm");
|
||||
let status = Command::new("wasm-opt")
|
||||
.args(["-Oz", "--enable-bulk-memory"])
|
||||
.arg(input)
|
||||
.arg("-o")
|
||||
.arg(&tmp)
|
||||
.status()
|
||||
.context("wasm-opt spawn failed")?;
|
||||
if !status.success() {
|
||||
let status2 = Command::new("wasm-opt")
|
||||
.args(["-Oz"])
|
||||
.arg(input)
|
||||
.arg("-o")
|
||||
.arg(&tmp)
|
||||
.status()
|
||||
.context("wasm-opt spawn failed")?;
|
||||
if !status2.success() {
|
||||
eprintln!("warning: wasm-opt failed; keeping cargo artifact");
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
println!("wasm-opt: {}", tmp.display());
|
||||
Ok(Some(tmp))
|
||||
}
|
||||
|
||||
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-wasm/marqdo_wasm.wasm"),
|
||||
);
|
||||
candidates.push(
|
||||
PathBuf::from(td).join("wasm32-unknown-unknown/release/marqdo_wasm.wasm"),
|
||||
);
|
||||
}
|
||||
candidates.push(PathBuf::from(
|
||||
"target/wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm",
|
||||
));
|
||||
candidates.push(PathBuf::from(
|
||||
"target/wasm32-unknown-unknown/release/marqdo_wasm.wasm",
|
||||
));
|
||||
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(", ")
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: web assets live server
|
||||
description: Live favicon + head icon + images_html on home page.
|
||||
import web:ext/web/web.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`icons_table` =
|
||||
|
||||
|path|rel|type|url|
|
||||
|---|---|---|---|
|
||||
|"web-fixtures/public/favicon.png"|icon|"image/png"|"/favicon.ico"|
|
||||
|
||||
`head_table` =
|
||||
|
||||
|rel|href|type|
|
||||
|---|---|---|
|
||||
|apple-touch-icon|"/static/favicon.png"|"image/png"|
|
||||
|
||||
`images_table` =
|
||||
|
||||
|src|alt|class|loading|
|
||||
|---|---|---|---|
|
||||
|"/static/favicon.svg"|mark|brand|eager|
|
||||
|
||||
*home = > web.page title="Live assets" intro="<p>assets live</p>"*
|
||||
*home = > `home`.head table=`head_table`*
|
||||
*home = > `home`.images table=`images_table`*
|
||||
|
||||
*app = > web.app page=`home` host=127.0.0.1 port=18092*
|
||||
*app = > `app`.static dir="web-fixtures/public" mount="/static"*
|
||||
*app = > `app`.icons table=`icons_table`*
|
||||
|
||||
> print text=marqdo web assets live starting
|
||||
> `app`.listen
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
title: web assets smoke
|
||||
description: Offline icons / head / images assembly (no listen).
|
||||
import web:ext/web/web.mq.md
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`icons_table` =
|
||||
|
||||
|path|rel|type|sizes|url|
|
||||
|---|---|---|---|---|
|
||||
|"web-fixtures/public/favicon.png"|icon|"image/png"|32x32|"/favicon.ico"|
|
||||
|"web-fixtures/public/favicon.svg"|icon|"image/svg+xml"|any|"/static/favicon.svg"|
|
||||
|
||||
`head_table` =
|
||||
|
||||
|rel|href|type|media|
|
||||
|---|---|---|---|
|
||||
|icon|"/favicon.ico"|"image/png"|
|
||||
|stylesheet|"/static/print.css"|"text/css"|print|
|
||||
|script|"/static/live.js"||
|
||||
|
||||
`images_table` =
|
||||
|
||||
|src|alt|class|href|width|loading|caption|
|
||||
|---|---|---|---|---|---|---|
|
||||
|"/static/logo.svg"|Marqdo|brand-logo|"/"|48|eager|Brand|
|
||||
|
||||
`seo` =
|
||||
|
||||
| 行 | key | value |
|
||||
|----|-----|-------|
|
||||
| 1 | description | asset smoke |
|
||||
| 2 | icon | "/favicon.ico" |
|
||||
| 3 | og:image | "/static/logo.svg" |
|
||||
|
||||
*home = > web.page title="Assets"*
|
||||
*home = > `home`.head table=`head_table`*
|
||||
*home = > `home`.images table=`images_table`*
|
||||
*home = > `home`.meta meta=`seo`*
|
||||
|
||||
*ih = > json.get value=`home` key="images_html"*
|
||||
1. `ih` != ""
|
||||
> print text=images-ok
|
||||
2. *
|
||||
> print text=images-fail
|
||||
|
||||
*hd = > json.get value=`home` key="head"*
|
||||
*n = > len `hd`*
|
||||
1. `n` >= 3
|
||||
> print text=head-ok
|
||||
2. *
|
||||
> print text=head-fail
|
||||
|
||||
*meta = > json.get value=`home` key="meta"*
|
||||
*icon = > json.get value=`meta` key="icon"*
|
||||
1. `icon` == "/favicon.ico"
|
||||
> print text=meta-icon-ok
|
||||
2. *
|
||||
> print text=meta-icon-fail
|
||||
|
||||
*app = > web.app page=`home` host=127.0.0.1 port=18091*
|
||||
*app = > `app`.static dir="web-fixtures/public" mount="/static"*
|
||||
*app = > `app`.icons table=`icons_table`*
|
||||
|
||||
*icons = > json.get value=`app` key="icons"*
|
||||
*ni = > len `icons`*
|
||||
1. `ni` == 2
|
||||
> print text=icons-ok
|
||||
2. *
|
||||
> print text=icons-fail
|
||||
|
||||
*sh = > json.get value=`app` key="site_head"*
|
||||
*ns = > len `sh`*
|
||||
1. `ns` >= 1
|
||||
> print text=site-head-ok
|
||||
2. *
|
||||
> print text=site-head-fail
|
||||
|
||||
*preview = > web.make_images table=`images_table`*
|
||||
1. `preview` != ""
|
||||
> print text=make-images-ok
|
||||
2. *
|
||||
> print text=make-images-fail
|
||||
|
||||
*hprev = > web.make_head table=`head_table`*
|
||||
1. `hprev` != ""
|
||||
> print text=make-head-ok
|
||||
2. *
|
||||
> print text=make-head-fail
|
||||
@@ -0,0 +1,2 @@
|
||||
‰PNG
|
||||
|
||||
|
After Width: | Height: | Size: 8 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#1a5f4a"/><text x="16" y="22" text-anchor="middle" font-size="16" font-family="Georgia,serif" fill="#f4f7f5">M</text></svg>
|
||||
|
After Width: | Height: | Size: 226 B |
+99
-1
@@ -182,7 +182,9 @@ fn structure_collection_cell_expr() {
|
||||
gpt-4o-mini
|
||||
https://api.openai.com/v1
|
||||
/chat/completions
|
||||
sk-live",
|
||||
sk-live
|
||||
1/5
|
||||
16/9",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1542,6 +1544,102 @@ custom-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_assets_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
.args(["build", "-p", "marqdo_plugin_web"])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.status()
|
||||
.expect("build web plugin");
|
||||
assert!(status.success(), "failed to build marqdo_plugin_web");
|
||||
assert_out(
|
||||
"tests/ext/web-assets-smoke.mq.md",
|
||||
"images-ok
|
||||
head-ok
|
||||
meta-icon-ok
|
||||
icons-ok
|
||||
site-head-ok
|
||||
make-images-ok
|
||||
make-head-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_assets_live() {
|
||||
let status = Command::new("cargo")
|
||||
.args(["build", "-p", "marqdo_plugin_web"])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.status()
|
||||
.expect("build web plugin");
|
||||
assert!(status.success(), "failed to build marqdo_plugin_web");
|
||||
|
||||
let script = "tests/ext/web-assets-live-server.mq.md";
|
||||
let bin = env!("CARGO_BIN_EXE_marqdo");
|
||||
let mut child = Command::new(bin)
|
||||
.args(["run", script])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn assets live server");
|
||||
|
||||
let base = "http://127.0.0.1:18092";
|
||||
let ready = std::time::Instant::now();
|
||||
loop {
|
||||
if ready.elapsed().as_secs() > 10 {
|
||||
let _ = child.kill();
|
||||
panic!("assets live server did not start in time");
|
||||
}
|
||||
let out = Command::new("curl")
|
||||
.args([
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
&format!("{base}/"),
|
||||
])
|
||||
.output()
|
||||
.expect("curl probe");
|
||||
if String::from_utf8_lossy(&out.stdout) == "200" {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
|
||||
let out = Command::new("curl")
|
||||
.args([
|
||||
"-s",
|
||||
"-D",
|
||||
"-",
|
||||
"-o",
|
||||
"/tmp/marqdo-favicon.bin",
|
||||
"-w",
|
||||
"\n%{http_code}",
|
||||
&format!("{base}/favicon.ico"),
|
||||
])
|
||||
.output()
|
||||
.expect("curl favicon");
|
||||
let body = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
body.contains("200") && body.to_ascii_lowercase().contains("image/"),
|
||||
"favicon headers={body}"
|
||||
);
|
||||
|
||||
let out = Command::new("curl")
|
||||
.args(["-s", &format!("{base}/")])
|
||||
.output()
|
||||
.expect("curl home");
|
||||
let html = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
html.contains("rel=\"icon\"") && html.contains("mq-images") && html.contains("apple-touch-icon"),
|
||||
"home html missing assets markers: {}",
|
||||
&html[..html.len().min(500)]
|
||||
);
|
||||
|
||||
let _ = child.kill();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_middleware_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
|
||||
@@ -33,3 +33,13 @@ description: Data cells evaluate like call-arg values (`var`, paths, hyphen pros
|
||||
| 1 | user | `secret` |
|
||||
|
||||
> print text=`rec`[^1][^content]
|
||||
|
||||
`ratios` =
|
||||
|
||||
| r |
|
||||
|---|
|
||||
| "1/5" |
|
||||
| "16/9" |
|
||||
|
||||
> print text=`ratios`[^1]
|
||||
> print text=`ratios`[^2]
|
||||
@@ -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");
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Browser WASM integration smoke (Node + wasm artifact).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
fn wasm_artifact() -> Option<PathBuf> {
|
||||
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}");
|
||||
}
|
||||
Reference in new issue
Block a user