Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d591674aa | ||
|
|
e40d21760a | ||
|
|
2445c290c9 | ||
|
|
04890e0c73 | ||
|
|
ab52db2037 | ||
|
|
aac896b044 | ||
|
|
fb037022ba | ||
|
|
a75b7a1c87 | ||
|
|
f2fd4fb34e | ||
|
|
2079577314 |
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)
|
||||
|
||||
|
||||
@@ -92,10 +92,10 @@ jobs:
|
||||
body: |
|
||||
## Marqdo ${{ github.ref_name }}
|
||||
|
||||
### Highlights — v0.3.1
|
||||
- **W8**: favicon / head assets / image assembly (`app.icons`, `page.head`, `make_images`)
|
||||
- Fix: absolute `entry_dir` for relative entry scripts (no nested `tests/ext/tests/ext`)
|
||||
- **`ext/web`**: W0–W7 + P3 + W8; **`ext/quantum`** Q7/Q8; **`ext/agent`** A1–A4
|
||||
### 亮点 / 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,40 @@
|
||||
|
||||
## 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
|
||||
|
||||
Generated
+9
-1
@@ -1018,7 +1018,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo"
|
||||
version = "0.3.1"
|
||||
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.1"
|
||||
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.1)
|
||||
## 现状(v0.3.2)
|
||||
|
||||
- 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/`
|
||||
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
|
||||
@@ -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.1)
|
||||
### 如何使用最新 Marqdo(v0.3.2)
|
||||
|
||||
```bash
|
||||
# 1) 源码安装(跟 tag 或 main)
|
||||
git clone https://github.com/cflmy/marqdo.git && cd marqdo
|
||||
git checkout v0.3.1 # 或留在 main
|
||||
git checkout v0.3.2 # 或留在 main
|
||||
cargo build --release
|
||||
export PATH="$PWD/target/release:$PATH"
|
||||
marqdo version
|
||||
@@ -148,8 +149,12 @@ marqdo ext add llm # 或:大模型
|
||||
marqdo run examples/marqdo-blog/index.mq.md
|
||||
# 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8
|
||||
|
||||
# 5) Windows:也可从 GitHub Releases 下载 exe / zip / vsix
|
||||
# https://github.com/cflmy/marqdo/releases/tag/v0.3.1
|
||||
# 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");
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,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;
|
||||
}
|
||||
+14
-2
@@ -24,8 +24,11 @@ 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`**
|
||||
@@ -124,6 +127,15 @@ Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|cro
|
||||
|
||||
**> 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`
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ import sys:lib/sys.mq.md
|
||||
把 GFM 样式表装配成一段 CSS 文本。支持两种表形:
|
||||
`|选择器|属性|值|` 规则行(选择器任意,同一选择器多行合并成一条规则;
|
||||
加 `|媒体|` 列即可分组进 `@media` 块),或 `|属性|值|` 属性行(按 `.名 { … }` 包裹)。
|
||||
选择器以 `@keyframes 名` 开头时输出关键帧块(`属性` 为停点 `from`/`to`/`N%`,
|
||||
`值` 写 `opacity: 0` 等声明;也可用 `@keyframes 名 from` + 普通属性/值)。
|
||||
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1/5"`),否则按表达式除法求值。
|
||||
样式即数据、装配即函数 —— 主题模块据此把样式表拼成完整样式表。
|
||||
|
||||
> 确保插件
|
||||
@@ -113,6 +116,15 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
|
||||
**> web_page_head page=`self` table=`表`**
|
||||
|
||||
## 客户端挂载
|
||||
+ `桥`="/static/marqdo-bridge.js"
|
||||
|
||||
返回一段用于挂载浏览器 Marqdo(路线 C)的 HTML:加载官方 `marqdo-bridge.js` 模块。
|
||||
请先 `marqdo wasm build -o static`(或站点静态目录),并用 `头装配` 挂 `关系=module` 行;
|
||||
业务 `.mq.md` 与 `wire`/`fetch` 效应见 [browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md)。
|
||||
|
||||
**"<script type=\"module\" src=\"" + 桥 + "\"></script>"**
|
||||
|
||||
## 图片装配
|
||||
+ `表`
|
||||
|
||||
|
||||
+16
-23
@@ -1211,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
|
||||
@@ -1270,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); }}
|
||||
@@ -1280,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); }}
|
||||
@@ -1290,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; }}
|
||||
@@ -1363,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()
|
||||
}
|
||||
@@ -1433,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)));
|
||||
}
|
||||
@@ -1450,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")
|
||||
@@ -1468,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()
|
||||
}
|
||||
|
||||
+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).
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(", ")
|
||||
)
|
||||
}
|
||||
+3
-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",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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