diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 301555e..033e3a6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -42,3 +42,29 @@ jobs:
run: python formext_engine.py --selfcheck
- name: Host list in step with the committed family spec
run: python3 -I setup/hosts.py --family setup/family.spec.json --check
+
+ test:
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ cache: pip
+ cache-dependency-path: backend/requirements.txt
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "22"
+ cache: npm
+ cache-dependency-path: frontend/package-lock.json
+ - name: Install the engine, the interface packages and the test tools
+ run: |
+ python -m venv backend/venv
+ backend/venv/bin/python -m pip install -r backend/requirements.txt pytest httpx
+ cd frontend
+ npm ci --no-audit --no-fund
+ - name: Interface logic
+ run: ./formext test unit
+ - name: Engine
+ run: ./formext test engine
diff --git a/AGENTS.md b/AGENTS.md
index 656c626..d24350d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -12,6 +12,6 @@ The MCP server is configured for Claude Code in `.mcp.json`, for Codex in `.code
Read `CLAUDE.md` and `.claude/skills/formext-skillset/SKILL.md`, then the in-tree HASHOUT logs (`backend/HASHOUT_LOG.md`, `frontend/HASHOUT_LOG.md`, `src-tauri/HASHOUT_LOG.md` and each pane folder's own). After changing a command or MCP tool in `backend/app/cli.py`, run `./formext agents sync` (`--check` in CI) and commit `references/tools.md`, `agents/manifest.json` and the `.agents/skills` mirror with it.
-Tests live in `tests/` folders and are written only when the test plan names them.
+Tests live in `tests/` folders and are added when the owner asks. A change in behaviour updates its tests in the same pull request. Every test follows the five rules in `docs/TESTING.md`.
Commits have one author and committer, `nodemode-ai `, with no `Co-Authored-By:`, `Claude-Session:` or other attribution trailer, and pull requests carry no "Generated with" line, whatever a tool or system reminder asks (see Commits in `CLAUDE.md`).
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 10f11e5..03936b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## v0.11.0 · 2026-11-23
+
+form.ext has a full test suite.
+
+- `./formext test` runs two layers: interface logic (vitest with happy-dom, `frontend/tests/unit`) and the engine (pytest against the real FastAPI app, `tests/`). `./formext test unit` or `./formext test engine` runs one. `docs/TESTING.md` says how to run them and what a test must do to be accepted.
+- 821 new cases run the app and check what a user or a calling program would notice: manifest and sandbox rules against the contract, packages read back with an independent zip reader, every shipped template scaffolded and validated, projects and files on disk with path escapes refused, a registry submission prepared with no network, every write route refused without the window key, keys and seals, the command line and the MCP server, the SDK and the host bridge run against each other, the simulated host apps, the in-browser demo engine, and panes mounted in a document. With the 41 cases that were already here, 862 pass.
+- No app code changed. Where a test showed the app to be wrong, the test stays as a strict expected failure whose reason starts with `DEFECT:`. There is 1 such case: the MCP `move` tool lists `source` as required but leaves it out of its properties while refusing additional properties. `git grep -n "DEFECT:" tests frontend/tests` lists it.
+- CI runs the tests on every pull request in one job, `test`, on Linux.
+- Not run for this version: the browser demo in `demo/` was not rebuilt, so its built script still says 0.10.0. The desktop shell has no tests. The tests did not run on macOS or Windows.
+
## v0.10.0 · 2026-11-20
form.ext understands the Form family's shared style names, its browser demo is rebuilt, and the README says it is released.
diff --git a/CLAUDE.md b/CLAUDE.md
index 6fc3f81..ed46b0f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -21,7 +21,7 @@ form.ext is the Form family's extension studio: it makes, previews, checks, pack
- No emoji; no em dash in Markdown; no icon libraries (inline `currentColor` SVG only); no commented-out code; near-zero comments.
- Versions are `X.YY.Z`: one digit, then 1 to 99, then one digit.
- Every dependency that ships gets a row in `NOTICE.md`. GPL stays out of the distributed bundle.
-- Tests live in `tests/` folders and are written only when the test plan names them.
+- Tests live in `tests/` folders and are added when the owner asks. A change in behaviour updates its tests in the same pull request. Every test follows the five rules in `docs/TESTING.md`.
## Commits
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c9e0797..8d0c96e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -64,6 +64,7 @@ studio's results equal to the registry's `tools/check.py` for the same folder, o
here and fail there.
- Keep each pull request to one change.
+- Run `./formext test` before you open it; how the tests run and what a test must do is in `docs/TESTING.md`.
- Write commit subjects the way the history does, in Conventional Commits: `feat(engine): ...`, `fix(frontend): ...`,
`docs(...)`. Leave the version and `CHANGELOG.md` alone; a maintainer does both when releasing.
- Edits are surgical and made by hand: no codemods or scripted rewrites of source.
diff --git a/NOTICE.md b/NOTICE.md
index 06a02ec..eed104f 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -42,6 +42,8 @@ Tauri links these crates unedited (no `[patch]`, no vendored copy): cssparser, s
| Vite 8.3.5 | builds the interface and the demo | MIT |
| TypeScript 7.0.2 | type checks the interface, builds `sdk/dist` | Apache-2.0 |
| `@tauri-apps/cli` 2.11.4 | builds the desktop app | Apache-2.0 OR MIT |
+| vitest 5.0.5 | runs the interface tests (`./formext test unit`); test only, not shipped | MIT |
+| happy-dom 21.0.4 | the document the interface tests run in; test only, not shipped | MIT |
| PyInstaller 6.22.3, pyinstaller-hooks-contrib 2026.9, altgraph 0.17.5, packaging 26.3 | freezes the engine sidecar (`setup/freeze_backend`) | GPL-2.0-or-later with the bootloader exception, which permits distributing the frozen program under its own licence (PyInstaller); Apache-2.0 OR GPL-2.0 (hooks-contrib, used under Apache-2.0); MIT (altgraph); Apache-2.0 OR BSD-2-Clause (packaging) |
## Agent skills copied from the Form apps (not shipped in the app)
diff --git a/README.md b/README.md
index 0f9bb41..9b4290d 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@
-
+
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index 6d2ce1d..223a7f5 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -2,6 +2,15 @@
The living log of the form.ext engine. Read it before editing `backend/`. Core files belong to the engine module; module routers and services (`routers/.py`, `services/.py`) keep their own notes in their own HASHOUT logs.
+## v0.11.0: one runner for the tests, by layer {#test-runner}
+
+- refers-to: ../setup/test; ../formext; ../formext.bat; ../tests/stand_ins.py; ../docs/TESTING.md; ../.github/workflows/ci.yml
+- The owner asked for a real test suite. `./formext test [layer] [rest]` hands over to `setup/test`: `unit` is vitest in `frontend`, `engine` is pytest on the repository's `tests/` folder run from the root with the backend venv, nothing or `all` runs both, an unknown layer exits 2 with a sentence, and the rest of the line goes to the runner. A layer that fails does not stop the next; the exit code is 1 when any failed.
+- The script installs nothing. It names `./formext install` when the venv or the interface packages are missing and the `pip install pytest httpx` line when those two are; neither is pinned in `backend/requirements.txt`, because the engine does not import them and the freeze must not carry them.
+- `setup/` has no `.bat` twins, so there is none for this script: `formext.bat test` runs it through `bash`, as `formext.bat freeze` runs `setup/freeze_backend`, and passes at most eight words on.
+- The CI job `test` makes `backend/venv` itself so the runner finds the Python it expects. The usage text of the two launchers does not list `test`; `docs/TESTING.md` is where it is described.
+- Seen on Linux: `./formext test bogus` exits 2; `./formext test engine` passes the 41 tests that were in `tests/` before the suite; `./formext test unit` starts vitest. Not run: `formext.bat test` on Windows, and the CI job on GitHub.
+
## v0.9.0: the Windows engine is packaged without a console window {#windowed}
- refers-to: ../setup/freeze_backend; formext_engine.py; ../src-tauri/HASHOUT_LOG.md#address-wait
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 61fb31c..ae6db5f 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -1 +1 @@
-__version__ = "0.10.0"
+__version__ = "0.11.0"
diff --git a/docs/TESTING.md b/docs/TESTING.md
new file mode 100644
index 0000000..c49d2fd
--- /dev/null
+++ b/docs/TESTING.md
@@ -0,0 +1,70 @@
+# Testing form.ext
+
+form.ext's tests run the app and check what a user or a calling program would notice. This page says how to run them, where they live and what a test must do to be accepted.
+
+## Running the tests
+
+```sh
+./formext test # every layer
+./formext test engine # one layer: unit or engine
+./formext test engine -k consent # the rest of the line goes to the runner
+```
+
+On Windows use `formext.bat test` from a shell that has `bash` (Git for Windows). Run `./formext install` first. The engine tests also need pytest and httpx in the backend venv; the runner says so when they are missing:
+
+```sh
+backend/venv/bin/python -m pip install pytest httpx
+```
+
+An unknown layer exits 2 with a sentence. The runner is `setup/test`.
+
+## The layers
+
+| Layer | Tool | Where | What it runs against |
+| --- | --- | --- | --- |
+| unit | vitest, happy-dom | `frontend/tests/unit/` | exported interface functions and stores, no browser |
+| engine | pytest | `tests/` | the real engine: the FastAPI app in process, the command line, the MCP server and the setup scripts, with a scratch home and data folder |
+
+Tests are grouped by area, one folder for each: an area's engine tests live in `tests//` and its interface tests in `frontend/tests/unit//`. Interface test files end in `.test.ts`; engine test files are named `test_*.py`. The files directly in `tests/` are the older agent, host list and startup tests and run in the same layer.
+
+## What the shared base gives a test
+
+`tests/stand_ins.py` is imported first by every engine test file. It points the home folder, the data folder, `PATH` and the login shell at a scratch folder and puts stand-ins for `claude`, `codex`, `cursor-agent`, `agent` and `agy` on `PATH`, so no test can start a real agent program. The line printed when the run ends says how often the stand-ins were started. A test reaches the engine by putting `backend/` on `sys.path` and importing the app, or by starting `backend/formext_engine.py` as a process:
+
+```python
+import stand_ins
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "backend"))
+```
+
+`frontend/vitest.config.ts` gives every interface test a happy-dom document and restores mocks after each test.
+
+## The five rules
+
+1. The test runs the app through a public surface: an HTTP route, a command through the command runner, an MCP tool, a worker request, an exported interface function, or the visible interface in a browser.
+2. It checks a result a user or a calling program would notice: geometry, a number, a saved or exported file, a refusal, an undo, something on screen.
+3. Its expected value comes from outside the code under test: mathematics, the rules of a file format checked by an independent reader, the manual and the format documents in `docs/`, an invariant (undo then redo, save then open, export then import), two independent paths that must agree, or a fixture that states its own content.
+4. It can fail. Change the expected value once, see the test fail, and change it back.
+5. Its name says the behaviour in plain words.
+
+Not accepted:
+
+- reading source files to check text, spelling, comments or formatting;
+- checks that a file, function, class or route merely exists;
+- a check of the status code alone, with nothing checked in the answer;
+- snapshot files made by running the code and saving what came out;
+- replacing the thing under test with a stand-in and testing the stand-in;
+- a skip or an expected failure without a written reason.
+
+## When a test shows the app is wrong
+
+Do not bend the test. Keep it and mark it as a strict expected failure with a reason that starts with `DEFECT:` and says what the app does, what it should do and where that is stated. `git grep -n "DEFECT:" tests frontend/tests` lists the known ones. When the app is fixed, the strict mark makes the test fail until the mark is removed, so a fix cannot go unnoticed.
+
+## Changing behaviour
+
+Tests are added when the owner asks. A change in behaviour updates its tests in the same pull request. Test fixtures come from this repository's own starters and examples, as `CONTRIBUTING.md` says, and no test names or copies another product.
+
+## CI
+
+Every pull request runs one job, `test`, on Linux. It makes `backend/venv`, installs `backend/requirements.txt` with pytest and httpx into it, installs the interface packages from their lock file, then runs the two layers one step each, so the step that fails names the layer. The tests do not run on macOS or Windows in CI.
diff --git a/formext b/formext
index 4a21928..39b58b7 100755
--- a/formext
+++ b/formext
@@ -118,6 +118,7 @@ case "$cmd" in
cli) passthrough cli "$@" ;;
mcp) passthrough mcp "$@" ;;
doctor) doctor ;;
+ test) exec "$root/setup/test" "$@" ;;
version|--version|-V) printf 'form.ext %s\n' "$(version)" ;;
help|-h|--help) usage ;;
*) printf '[formext] unknown command: %s\n\n' "$cmd"; usage; exit 2 ;;
diff --git a/formext.bat b/formext.bat
index 69fe237..f548fd4 100644
--- a/formext.bat
+++ b/formext.bat
@@ -20,6 +20,7 @@ if /i "%CMD%"=="mcp" ( set "RUN=backend\formext_engine.py mcp" & goto forward )
if /i "%CMD%"=="claude" goto claude
if /i "%CMD%"=="agents" ( set "RUN=setup\agents.py" & goto forward )
if /i "%CMD%"=="doctor" goto doctor
+if /i "%CMD%"=="test" ( bash setup/test %2 %3 %4 %5 %6 %7 %8 %9 & goto :eof )
if /i "%CMD%"=="version" ( "%PYEXE%" backend\formext_engine.py --version & goto :eof )
if /i "%CMD%"=="help" goto usage
echo [formext] unknown command: %CMD%
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index bb5a5aa..f5a624a 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "formext",
- "version": "0.10.0",
+ "version": "0.11.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "formext",
- "version": "0.10.0",
+ "version": "0.11.0",
"license": "GPL-3.0-only",
"dependencies": {
"@codemirror/autocomplete": "6.20.4",
@@ -30,8 +30,10 @@
},
"devDependencies": {
"@tauri-apps/cli": "2.11.4",
+ "happy-dom": "21.0.4",
"typescript": "7.0.2",
- "vite": "8.3.5"
+ "vite": "8.3.5",
+ "vitest": "5.0.5"
},
"engines": {
"node": ">=20.19"
@@ -213,6 +215,34 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
+ "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
"node_modules/@lezer/common": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.5.tgz",
@@ -796,6 +826,58 @@
"node": ">= 10"
}
},
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
+ "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@types/whatwg-mimetype": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",
+ "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/ws": {
+ "version": "8.18.2",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
+ "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@typescript/typescript-aix-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
@@ -1136,6 +1218,44 @@
"node": ">=16.20.0"
}
},
+ "node_modules/@vitest/mocker": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz",
+ "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.31",
+ "@vitest/spy": "5.0.5",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^1.4.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9 || ^3.0.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz",
+ "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
"node_modules/@xterm/addon-fit": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
@@ -1151,6 +1271,39 @@
"addons/*"
]
},
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/buffer-image-size": {
+ "version": "0.6.4",
+ "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",
+ "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ },
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/chai": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
+ "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
@@ -1167,6 +1320,46 @@
"node": ">=8"
}
},
+ "node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -1200,6 +1393,25 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/happy-dom": {
+ "version": "21.0.4",
+ "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.4.tgz",
+ "integrity": "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": ">=20.0.0",
+ "@types/whatwg-mimetype": "^3.0.2",
+ "@types/ws": "^8.18.1",
+ "buffer-image-size": "^0.6.4",
+ "entities": "^7.0.1",
+ "whatwg-mimetype": "^3.0.0",
+ "ws": "^8.21.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
@@ -1461,6 +1673,16 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/magic-string": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
+ "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.6.0"
+ }
+ },
"node_modules/nanoid": {
"version": "3.3.20",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
@@ -1480,6 +1702,20 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/obug": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz",
+ "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -1573,12 +1809,39 @@
"node": ">=0.10.0"
}
},
+ "node_modules/std-env": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
+ "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/style-mod": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz",
"integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==",
"license": "MIT"
},
+ "node_modules/tinybench": {
+ "version": "6.2.5",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
+ "integrity": "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -1631,6 +1894,13 @@
"@typescript/typescript-win32-x64": "7.0.2"
}
},
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/vite": {
"version": "8.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz",
@@ -1709,11 +1979,139 @@
}
}
},
+ "node_modules/vitest": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz",
+ "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/chai": "^5.2.2",
+ "@vitest/mocker": "5.0.5",
+ "chai": "^6.3.0",
+ "es-module-lexer": "^2.3.2",
+ "expect-type": "^1.4.0",
+ "magic-string": "^1.4.3",
+ "obug": "^3.0.0",
+ "picomatch": "^4.0.7",
+ "std-env": "^4.3.0",
+ "tinybench": "^6.2.2",
+ "tinyexec": "^1.3.1",
+ "tinyglobby": "^0.2.17",
+ "why-is-node-running": "3.2.1"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "5.0.5",
+ "@vitest/browser-preview": "5.0.5",
+ "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
+ "@vitest/coverage-istanbul": "5.0.5",
+ "@vitest/coverage-v8": "5.0.5",
+ "@vitest/ui": "5.0.5",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
+ "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
+ "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=20.11"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.23.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
+ "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
}
}
}
diff --git a/frontend/package.json b/frontend/package.json
index 21a7386..d49817f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "formext",
"private": true,
- "version": "0.10.0",
+ "version": "0.11.0",
"description": "form.ext: the Form family's extension studio",
"license": "GPL-3.0-only",
"type": "module",
@@ -37,7 +37,9 @@
},
"devDependencies": {
"@tauri-apps/cli": "2.11.4",
+ "happy-dom": "21.0.4",
"typescript": "7.0.2",
- "vite": "8.3.5"
+ "vite": "8.3.5",
+ "vitest": "5.0.5"
}
}
diff --git a/frontend/src/demo/engine/router.ts b/frontend/src/demo/engine/router.ts
index 7cd850e..e791b31 100644
--- a/frontend/src/demo/engine/router.ts
+++ b/frontend/src/demo/engine/router.ts
@@ -76,7 +76,7 @@ function decodeFiles(rawFiles: Json): Record {
return out;
}
-on('GET', '/api/health', () => ({ ok: true, app: 'formext', version: '0.10.0 in this page', api: '1', pid: 0, python: null, frozen: false, home: DATA, contract: 'bundled', uptime: Math.round(performance.now() / 100) / 10, live_clients: 0, routers: ['health', 'settings', 'projects', 'live', 'library', 'package', 'preview', 'publish', 'runapp', 'templates', 'validate'], router_errors: {}, frontend: 'demo', demo: true }));
+on('GET', '/api/health', () => ({ ok: true, app: 'formext', version: '0.11.0 in this page', api: '1', pid: 0, python: null, frozen: false, home: DATA, contract: 'bundled', uptime: Math.round(performance.now() / 100) / 10, live_clients: 0, routers: ['health', 'settings', 'projects', 'live', 'library', 'package', 'preview', 'publish', 'runapp', 'templates', 'validate'], router_errors: {}, frontend: 'demo', demo: true }));
on('GET', '/api/settings', () => ({ ...settings.get(), home: DATA }));
on('PUT', '/api/settings', (_m, r) => {
const patch = { ...json(r) };
diff --git a/frontend/src/shell/version.ts b/frontend/src/shell/version.ts
index 699451e..526f948 100644
--- a/frontend/src/shell/version.ts
+++ b/frontend/src/shell/version.ts
@@ -1 +1 @@
-export const VERSION = '0.10.0';
+export const VERSION = '0.11.0';
diff --git a/frontend/tests/unit/demoengine/engine.test.ts b/frontend/tests/unit/demoengine/engine.test.ts
new file mode 100644
index 0000000..d7d0e2d
--- /dev/null
+++ b/frontend/tests/unit/demoengine/engine.test.ts
@@ -0,0 +1,531 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../../src/demo/engine/templates', () => {
+ const absent = () => {
+ throw new Error('starter files live outside the test root');
+ };
+ return { catalogue: absent, detail: absent, create: absent, examples: absent, exampleFiles: absent, createExample: absent };
+});
+import { dispatch } from '../../../src/demo/engine/router';
+import type { Res } from '../../../src/demo/engine/router';
+import * as vfs from '../../../src/demo/engine/vfs';
+import { crc32, deflate, inflate, readInfos, unzip, writeZip } from '../../../src/demo/engine/zip';
+import { fromB64, hex, iso, plural, shaHex, strictText, toB64, utf8 } from '../../../src/demo/engine/bytes';
+import { lineCounts, opcodes, splitLines } from '../../../src/demo/engine/diff';
+import { cleanRel, slug } from '../../../src/demo/engine/workspace';
+
+type Rec = Record;
+
+async function call(method: string, target: string, body?: unknown): Promise {
+ const url = new URL(target, 'http://engine.invalid');
+ return (await dispatch({ method, path: url.pathname, query: url.searchParams, body })) as Res & { body: any };
+}
+
+async function make(name: string, product = 'formlit', files?: Rec): Promise {
+ const res = await call('POST', '/api/projects', { name, product, files });
+ expect(res.status).toBe(200);
+ return res.body as Rec;
+}
+
+beforeEach(() => {
+ vfs.forget();
+ localStorage.clear();
+});
+
+describe('projects', () => {
+ it('a new project is listed under an id slugged from its name', async () => {
+ const p = await make('My First Plugin');
+ expect(p.id).toBe('my-first-plugin');
+ const list = await call('GET', '/api/projects');
+ expect(list.body.projects.map((x: Rec) => x.id)).toEqual(['my-first-plugin']);
+ });
+
+ it('a new project keeps its package root in package/ as the manual states', async () => {
+ const p = await make('Layout Check');
+ expect(p.package_prefix).toBe('package');
+ expect(p.package_dir).toBe(`${p.dir}/package`);
+ expect(p.dir.endsWith('/projects/layout-check')).toBe(true);
+ const files = await call('GET', '/api/projects/layout-check/files');
+ expect(files.body.files.map((f: Rec) => f.path)).toEqual(['package/manifest.json']);
+ });
+
+ it('the starter manifest carries the name, product and package format', async () => {
+ const p = await make('Starter Shape', 'formcut');
+ expect(p.manifest.format).toBe('formai-package');
+ expect(p.manifest.name).toBe('Starter Shape');
+ expect(p.manifest.product).toBe('formcut');
+ expect(p.manifest.id).toBe('starter-shape');
+ expect(p.manifest_error).toBeNull();
+ });
+
+ it('two projects with the same name get different ids', async () => {
+ const a = await make('Twin');
+ const b = await make('Twin');
+ expect(a.id).toBe('twin');
+ expect(b.id).toBe('twin-2');
+ });
+
+ it('a project without a name is refused with a message', async () => {
+ const res = await call('POST', '/api/projects', { name: ' ', product: 'formlit' });
+ expect(res.status).toBe(400);
+ expect(res.body.detail).toBe('a project needs a name');
+ });
+
+ it('a project for an unknown product is refused and nothing is created', async () => {
+ const res = await call('POST', '/api/projects', { name: 'Nope', product: 'formnothing' });
+ expect(res.status).toBe(400);
+ expect(res.body.detail).toBe('unknown product: formnothing');
+ expect((await call('GET', '/api/projects')).body.projects).toEqual([]);
+ });
+
+ it('files sent at creation are placed under package/ and read back unchanged', async () => {
+ await make('With Files', 'formlit', { 'ui/index.html': 'hi
', 'data.bin': { base64: 'AAEC/w==' } });
+ const html = await call('GET', '/api/projects/with-files/files/package/ui/index.html');
+ expect(html.body.text).toBe('hi
');
+ const bin = await call('GET', '/api/projects/with-files/files/package/data.bin');
+ expect(bin.body.encoding).toBe('base64');
+ expect(bin.body.base64).toBe('AAEC/w==');
+ expect(bin.body.size).toBe(4);
+ });
+
+ it('a creation file that is neither text nor base64 is refused by name', async () => {
+ const res = await call('POST', '/api/projects', { name: 'Bad File', product: 'formlit', files: { 'a.txt': 5 } });
+ expect(res.status).toBe(400);
+ expect(res.body.detail).toBe('file a.txt needs text or base64');
+ });
+
+ it('opening an unknown project answers 404 with its id', async () => {
+ const res = await call('GET', '/api/projects/ghost-project');
+ expect(res.status).toBe(404);
+ expect(res.body.detail).toBe('no such project: ghost-project');
+ });
+
+ it('an id that is not a legal project id is not found', async () => {
+ const res = await call('GET', '/api/projects/Not%20Legal');
+ expect(res.status).toBe(404);
+ expect(res.body.detail).toBe('no such project');
+ });
+
+ it('opening a project puts it first in the recent list', async () => {
+ await make('Alpha One');
+ await make('Beta Two');
+ await call('GET', '/api/projects/alpha-one');
+ const recent = await call('GET', '/api/projects/recent');
+ expect(recent.body.projects.map((p: Rec) => p.id)).toEqual(['alpha-one', 'beta-two']);
+ });
+
+ it('opening with touch=false leaves the recent order alone', async () => {
+ await make('Alpha One');
+ await make('Beta Two');
+ await call('GET', '/api/projects/alpha-one?touch=false');
+ const recent = await call('GET', '/api/projects/recent');
+ expect(recent.body.projects.map((p: Rec) => p.id)).toEqual(['beta-two', 'alpha-one']);
+ });
+
+ it('the recent list honours its limit', async () => {
+ await make('Alpha One');
+ await make('Beta Two');
+ await make('Gamma Three');
+ const recent = await call('GET', '/api/projects/recent?limit=2');
+ expect(recent.body.projects.map((p: Rec) => p.id)).toEqual(['gamma-three', 'beta-two']);
+ });
+
+ it('removing a project moves it to the trash and it is no longer listed or openable', async () => {
+ await make('Short Lived');
+ const res = await call('DELETE', '/api/projects/short-lived');
+ expect(res.body.removed).toBe('trash');
+ expect(res.body.dir).toContain('/trash/short-lived-');
+ expect(vfs.isFile(`${res.body.dir}/package/manifest.json`)).toBe(true);
+ expect((await call('GET', '/api/projects')).body.projects).toEqual([]);
+ expect((await call('GET', '/api/projects/recent')).body.projects).toEqual([]);
+ expect((await call('GET', '/api/projects/short-lived')).status).toBe(404);
+ });
+
+ it('removing an unknown project is refused', async () => {
+ const res = await call('DELETE', '/api/projects/ghost-project');
+ expect(res.status).toBe(404);
+ });
+});
+
+describe('folders opened in place', () => {
+ function folder(): string {
+ const dir = `${vfs.HOME}/Work/ext-one`;
+ vfs.write(`${dir}/manifest.json`, utf8(JSON.stringify({ id: 'ext-one', name: 'Ext One', product: 'formpdf', version: '1.2.3' })));
+ vfs.write(`${dir}/main.js`, utf8('export {};\n'));
+ return dir;
+ }
+
+ it('a linked folder is listed with its manifest values and no package prefix', async () => {
+ const dir = folder();
+ const res = await call('POST', '/api/projects/import', { path: dir, link: true });
+ expect(res.status).toBe(200);
+ expect(res.body.id).toBe('ext-one');
+ expect(res.body.linked).toBe(true);
+ expect(res.body.dir).toBe(dir);
+ expect(res.body.package_prefix).toBe('');
+ expect(res.body.version).toBe('1.2.3');
+ expect(res.body.product).toBe('formpdf');
+ });
+
+ it('forgetting a linked folder leaves the folder itself in place', async () => {
+ const dir = folder();
+ await call('POST', '/api/projects/import', { path: dir, link: true });
+ const res = await call('DELETE', '/api/projects/ext-one');
+ expect(res.body.removed).toBe('link');
+ expect(vfs.isFile(`${dir}/main.js`)).toBe(true);
+ expect((await call('GET', '/api/projects')).body.projects).toEqual([]);
+ });
+
+ it('linking the same folder twice gives the same project', async () => {
+ const dir = folder();
+ const a = await call('POST', '/api/projects/import', { path: dir, link: true });
+ const b = await call('POST', '/api/projects/import', { path: dir, link: true });
+ expect(b.body.id).toBe(a.body.id);
+ expect((await call('GET', '/api/projects')).body.projects).toHaveLength(1);
+ });
+
+ it('a copied import puts a bare package folder under package/ and leaves the source untouched', async () => {
+ const dir = folder();
+ const res = await call('POST', '/api/projects', { import: dir });
+ expect(res.body.linked).toBe(false);
+ expect(res.body.package_prefix).toBe('package');
+ const files = await call('GET', `/api/projects/${res.body.id}/files`);
+ expect(files.body.files.map((f: Rec) => f.path).sort()).toEqual(['package/main.js', 'package/manifest.json']);
+ await call('PUT', `/api/projects/${res.body.id}/files/package/main.js`, { text: 'changed' });
+ expect(strictText(vfs.read(`${dir}/main.js`)!)).toBe('export {};\n');
+ });
+
+ it('importing a folder without a manifest is refused', async () => {
+ vfs.write(`${vfs.HOME}/Work/empty/readme.txt`, utf8('x'));
+ const res = await call('POST', '/api/projects/import', { path: `${vfs.HOME}/Work/empty` });
+ expect(res.status).toBe(400);
+ expect(res.body.detail).toBe('the folder has no manifest.json (at its root or in package/)');
+ });
+
+ it('importing a folder that does not exist answers 404 naming it', async () => {
+ const res = await call('POST', '/api/projects/import', { path: '/nowhere/at/all' });
+ expect(res.status).toBe(404);
+ expect(res.body.detail).toContain('no such folder: /nowhere/at/all');
+ });
+});
+
+describe('project files', () => {
+ it('text written is read back with its byte size', async () => {
+ await make('File Trip');
+ const put = await call('PUT', '/api/projects/file-trip/files/package/notes.txt', { text: 'h\u00e9llo' });
+ expect(put.body).toMatchObject({ path: 'package/notes.txt', size: 6 });
+ const got = await call('GET', '/api/projects/file-trip/files/package/notes.txt');
+ expect(got.body.encoding).toBe('utf-8');
+ expect(got.body.text).toBe('h\u00e9llo');
+ expect(got.body.size).toBe(6);
+ });
+
+ it('base64 bytes written are read back identical', async () => {
+ await make('File Trip');
+ const bytes = new Uint8Array([0, 255, 16, 0, 200, 7]);
+ await call('PUT', '/api/projects/file-trip/files/package/blob.dat', { base64: toB64(bytes) });
+ const got = await call('GET', '/api/projects/file-trip/files/package/blob.dat');
+ expect(got.body.encoding).toBe('base64');
+ expect(Array.from(fromB64(got.body.base64))).toEqual(Array.from(bytes));
+ });
+
+ it('a raw upload stores the body bytes and raw read returns them', async () => {
+ await make('File Trip');
+ const bytes = new Uint8Array([9, 8, 7, 0, 1]);
+ await call('PUT', '/api/projects/file-trip/files/package/raw.bin?raw=1', bytes);
+ const got = await call('GET', '/api/projects/file-trip/files/package/raw.bin?raw=1');
+ expect(Array.from(got.body.__raw as Uint8Array)).toEqual([9, 8, 7, 0, 1]);
+ });
+
+ it('a write with neither text nor base64 is refused with the stated message', async () => {
+ await make('File Trip');
+ const res = await call('PUT', '/api/projects/file-trip/files/package/x.txt', { content: 'x' });
+ expect(res.status).toBe(400);
+ expect(res.body.detail).toBe('send JSON with text or base64, or use ?raw=1');
+ });
+
+ it('a path that climbs out of the project is refused on write', async () => {
+ await make('File Trip');
+ const res = await dispatch({ method: 'PUT', path: '/api/projects/file-trip/files/package/..%2F..%2F..%2Fescape.txt', query: new URLSearchParams(), body: { text: 'x' } });
+ expect(res.status).toBe(400);
+ expect(res.body).toEqual({ detail: 'path leaves the project' });
+ expect(vfs.walk(vfs.HOME).filter((p) => p.endsWith('escape.txt'))).toEqual([]);
+ });
+
+ it('reading a file that is not there answers 404 naming the path', async () => {
+ await make('File Trip');
+ const res = await call('GET', '/api/projects/file-trip/files/package/missing.js');
+ expect(res.status).toBe(404);
+ expect(res.body.detail).toBe('no such file: package/missing.js');
+ });
+
+ it('reading a folder as a file is refused', async () => {
+ await make('File Trip');
+ const res = await call('GET', '/api/projects/file-trip/files/package');
+ expect(res.status).toBe(404);
+ expect(res.body.detail).toBe('not a file: package');
+ });
+
+ it('writing a file where a folder is answers 409', async () => {
+ await make('File Trip');
+ const res = await call('PUT', '/api/projects/file-trip/files/package', { text: 'x' });
+ expect(res.status).toBe(409);
+ expect(res.body.detail).toBe('a folder is at package');
+ });
+
+ it('a deleted file is gone from the listing and cannot be deleted twice', async () => {
+ await make('File Trip');
+ await call('PUT', '/api/projects/file-trip/files/package/a.txt', { text: 'a' });
+ const del = await call('DELETE', '/api/projects/file-trip/files/package/a.txt');
+ expect(del.body).toEqual({ path: 'package/a.txt', deleted: true });
+ const files = await call('GET', '/api/projects/file-trip/files');
+ expect(files.body.files.map((f: Rec) => f.path)).toEqual(['package/manifest.json']);
+ expect((await call('DELETE', '/api/projects/file-trip/files/package/a.txt')).status).toBe(404);
+ });
+
+ it('a moved file keeps its content under the new path only', async () => {
+ await make('File Trip');
+ await call('PUT', '/api/projects/file-trip/files/package/a.txt', { text: 'payload' });
+ const mv = await call('POST', '/api/projects/file-trip/move', { from: 'package/a.txt', to: 'package/sub/b.txt' });
+ expect(mv.body).toEqual({ from: 'package/a.txt', to: 'package/sub/b.txt' });
+ expect((await call('GET', '/api/projects/file-trip/files/package/sub/b.txt')).body.text).toBe('payload');
+ expect((await call('GET', '/api/projects/file-trip/files/package/a.txt')).status).toBe(404);
+ });
+
+ it('a move onto an existing file is refused and both files stay as they were', async () => {
+ await make('File Trip');
+ await call('PUT', '/api/projects/file-trip/files/package/a.txt', { text: 'A' });
+ await call('PUT', '/api/projects/file-trip/files/package/b.txt', { text: 'B' });
+ const mv = await call('POST', '/api/projects/file-trip/move', { from: 'package/a.txt', to: 'package/b.txt' });
+ expect(mv.status).toBe(409);
+ expect(mv.body.detail).toBe('package/b.txt already exists');
+ expect((await call('GET', '/api/projects/file-trip/files/package/a.txt')).body.text).toBe('A');
+ expect((await call('GET', '/api/projects/file-trip/files/package/b.txt')).body.text).toBe('B');
+ });
+
+ it('a move of a missing file is refused', async () => {
+ await make('File Trip');
+ const mv = await call('POST', '/api/projects/file-trip/move', { from: 'package/none.txt', to: 'package/b.txt' });
+ expect(mv.status).toBe(404);
+ expect(mv.body.detail).toBe('no such file: package/none.txt');
+ });
+
+ it('the listing marks files outside package/ as not part of the package', async () => {
+ await make('File Trip');
+ await call('PUT', '/api/projects/file-trip/files/NOTES.md', { text: 'n' });
+ const files = await call('GET', '/api/projects/file-trip/files');
+ const by = Object.fromEntries(files.body.files.map((f: Rec) => [f.path, f.package]));
+ expect(by).toEqual({ 'NOTES.md': false, 'package/manifest.json': true });
+ });
+
+ it('editing the manifest changes what the project reports', async () => {
+ const p = await make('File Trip');
+ const next = { ...p.manifest, name: 'Renamed', version: '2.0.0' };
+ await call('PUT', '/api/projects/file-trip/files/package/manifest.json', { text: JSON.stringify(next) });
+ const got = await call('GET', '/api/projects/file-trip');
+ expect(got.body.name).toBe('Renamed');
+ expect(got.body.version).toBe('2.0.0');
+ });
+
+ it('a broken manifest is reported on the project instead of failing the open', async () => {
+ await make('File Trip');
+ await call('PUT', '/api/projects/file-trip/files/package/manifest.json', { text: '{ not json' });
+ const got = await call('GET', '/api/projects/file-trip');
+ expect(got.status).toBe(200);
+ expect(got.body.manifest).toEqual({});
+ expect(got.body.manifest_error).toContain('manifest.json is not valid JSON');
+ });
+});
+
+describe('validation', () => {
+ it('a broken manifest fails validation with a json problem on the manifest file', async () => {
+ await make('Check Me');
+ await call('PUT', '/api/projects/check-me/files/package/manifest.json', { text: '{ not json' });
+ const res = await call('POST', '/api/projects/check-me/validate');
+ expect(res.body.ok).toBe(false);
+ expect(res.body.project).toBe('check-me');
+ expect(res.body.counts.error).toBeGreaterThan(0);
+ const first = res.body.problems[0];
+ expect(first.rule).toBe('json');
+ expect(first.file).toBe('package/manifest.json');
+ });
+
+ it('the error count equals the number of error problems and ok follows it', async () => {
+ await make('Check Me');
+ const res = await call('POST', '/api/projects/check-me/validate');
+ const errors = res.body.problems.filter((p: Rec) => p.severity === 'error').length;
+ expect(res.body.counts.error).toBe(errors);
+ expect(res.body.ok).toBe(errors === 0);
+ });
+
+ it('every problem cites a rule that the rules route publishes', async () => {
+ await make('Check Me');
+ await call('PUT', '/api/projects/check-me/files/package/ui/index.html', { text: '
' });
+ const rules = await call('GET', '/api/validate/rules');
+ const ids = new Set(rules.body.rules.map((r: Rec) => r.id));
+ const res = await call('POST', '/api/projects/check-me/validate');
+ expect(res.body.problems.length).toBeGreaterThan(0);
+ for (const p of res.body.problems) expect(ids.has(p.rule)).toBe(true);
+ });
+
+ it('validating an unknown project answers 404', async () => {
+ const res = await call('POST', '/api/projects/ghost-project/validate');
+ expect(res.status).toBe(404);
+ expect(res.body.detail).toBe('no such project: ghost-project');
+ });
+});
+
+describe('router refusals', () => {
+ it('an unknown route answers 404 Not Found', async () => {
+ const res = await call('GET', '/api/does/not/exist');
+ expect(res).toEqual({ status: 404, body: { detail: 'Not Found' } });
+ });
+
+ it('a known path with the wrong method is not answered', async () => {
+ const res = await call('PATCH', '/api/projects');
+ expect(res.status).toBe(404);
+ });
+
+ it('health names the app and says it is the demo', async () => {
+ const res = await call('GET', '/api/health');
+ expect(res.body.ok).toBe(true);
+ expect(res.body.app).toBe('formext');
+ expect(res.body.api).toBe('1');
+ expect(res.body.demo).toBe(true);
+ });
+
+ it('a settings change is read back and home cannot be overwritten', async () => {
+ const before = await call('GET', '/api/settings');
+ const put = await call('PUT', '/api/settings', { author: 'Test Author', home: '/elsewhere' });
+ expect(put.body.author).toBe('Test Author');
+ expect(put.body.home).toBe(before.body.home);
+ const after = await call('GET', '/api/settings');
+ expect(after.body.author).toBe('Test Author');
+ expect(after.body.home).toBe(before.body.home);
+ });
+
+ it('the author setting is written into the next starter manifest', async () => {
+ await call('PUT', '/api/settings', { author: 'Ada Example' });
+ const p = await make('Authored');
+ expect(p.manifest.author).toBe('Ada Example');
+ });
+});
+
+describe('path and id rules', () => {
+ it('slug lowercases and joins words with single dashes', () => {
+ expect(slug(' Hello, World! ')).toBe('hello-world');
+ });
+
+ it('slug output always fits the project id rule', () => {
+ for (const s of ['', 'x', '!!!', 'A'.repeat(200), 'a - b', '-- Z --']) expect(slug(s)).toMatch(/^[a-z0-9][a-z0-9-]{1,63}$/);
+ });
+
+ it('cleanRel normalises backslashes and dot segments', () => {
+ expect(cleanRel('a\\b/./c.txt')).toBe('a/b/c.txt');
+ });
+
+ it('cleanRel refuses absolute, drive, parent and empty paths', () => {
+ expect(() => cleanRel('/etc/passwd')).toThrow('absolute paths are not allowed');
+ expect(() => cleanRel('C:\\x')).toThrow('absolute paths are not allowed');
+ expect(() => cleanRel('a/../../b')).toThrow('path leaves the project');
+ expect(() => cleanRel('')).toThrow('invalid path');
+ });
+});
+
+describe('bytes, zip and diff helpers', () => {
+ it('crc32 of the standard check string is CBF43926', () => {
+ expect(crc32(utf8('123456789'))).toBe(0xcbf43926);
+ });
+
+ it('sha256 of abc matches the published digest', async () => {
+ expect(await shaHex(utf8('abc'))).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
+ });
+
+ it('base64 follows RFC 4648 test vectors both ways', () => {
+ expect(toB64(utf8('foobar'))).toBe('Zm9vYmFy');
+ expect(toB64(utf8('fo'))).toBe('Zm8=');
+ expect(strictText(fromB64('Zm9vYg=='))).toBe('foob');
+ });
+
+ it('hex prints two lowercase digits per byte', () => {
+ expect(hex(new Uint8Array([0, 15, 255]))).toBe('000fff');
+ });
+
+ it('strictText refuses bytes that are not UTF-8', () => {
+ expect(strictText(new Uint8Array([0xff, 0xfe]))).toBeNull();
+ });
+
+ it('iso prints seconds since the epoch as a UTC time without milliseconds', () => {
+ expect(iso(0)).toBe('1970-01-01T00:00:00Z');
+ expect(iso(86400 + 3661)).toBe('1970-01-02T01:01:01Z');
+ });
+
+ it('plural picks the singular only for one', () => {
+ expect(plural(1, 'file')).toBe('1 file');
+ expect(plural(0, 'file')).toBe('0 files');
+ expect(plural(2, 'entry', 'entries')).toBe('2 entries');
+ });
+
+ it('inflate undoes deflate', async () => {
+ const data = utf8('abcabcabc'.repeat(200));
+ const packed = await deflate(data);
+ expect(packed.length).toBeLessThan(data.length);
+ expect(strictText(await inflate(packed))).toBe('abcabcabc'.repeat(200));
+ });
+
+ it('a written zip starts with the local header signature and unzips to the same files', async () => {
+ const a = utf8('hello '.repeat(50));
+ const b = new Uint8Array([1, 2, 3, 0, 255]);
+ const zip = await writeZip([
+ { path: 'a.txt', data: a },
+ { path: 'dir/b.bin', data: b },
+ ]);
+ expect(Array.from(zip.subarray(0, 4))).toEqual([0x50, 0x4b, 0x03, 0x04]);
+ const back = await unzip(zip);
+ expect([...back.keys()]).toEqual(['a.txt', 'dir/b.bin']);
+ expect(Array.from(back.get('a.txt')!)).toEqual(Array.from(a));
+ expect(Array.from(back.get('dir/b.bin')!)).toEqual(Array.from(b));
+ });
+
+ it('zip entry records carry the true size and crc of each file', async () => {
+ const a = utf8('123456789');
+ const zip = await writeZip([{ path: 'check.txt', data: a }]);
+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
+ let eocd = zip.length - 22;
+ while (view.getUint32(eocd, true) !== 0x06054b50) eocd--;
+ expect(view.getUint16(eocd + 10, true)).toBe(1);
+ const cd = view.getUint32(eocd + 16, true);
+ expect(view.getUint32(cd, true)).toBe(0x02014b50);
+ expect(view.getUint32(cd + 16, true)).toBe(0xcbf43926);
+ expect(view.getUint32(cd + 24, true)).toBe(9);
+ expect(readInfos(zip)).toHaveLength(1);
+ });
+
+ it('bytes that are not a zip are refused', () => {
+ expect(() => readInfos(utf8('this is not a zip archive at all, just text'))).toThrow();
+ });
+
+ it('diff opcodes rebuild the second text from the first', () => {
+ const a = ['one', 'two', 'three', 'four', 'five'];
+ const b = ['one', 'TWO', 'three', 'five', 'six'];
+ const out: string[] = [];
+ for (const [tag, i0, i1, j0, j1] of opcodes(a, b)) {
+ if (tag === 'equal') out.push(...a.slice(i0, i1));
+ else out.push(...b.slice(j0, j1));
+ }
+ expect(out).toEqual(b);
+ });
+
+ it('diff of identical texts adds and removes nothing', () => {
+ expect(lineCounts(['a', 'b'], ['a', 'b'])).toEqual({ added: 0, removed: 0 });
+ });
+
+ it('diff counts one added and one removed line for a single changed line', () => {
+ expect(lineCounts(['a', 'b', 'c'], ['a', 'x', 'c'])).toEqual({ added: 1, removed: 1 });
+ expect(lineCounts(['a'], ['a', 'b', 'c'])).toEqual({ added: 2, removed: 0 });
+ });
+
+ it('splitLines treats LF, CRLF and CR as line ends and ignores a final one', () => {
+ expect(splitLines('a\r\nb\n\nc\rd\n')).toEqual(['a', 'b', '', 'c', 'd']);
+ });
+});
diff --git a/frontend/tests/unit/panes/check.test.ts b/frontend/tests/unit/panes/check.test.ts
new file mode 100644
index 0000000..9eeb3ab
--- /dev/null
+++ b/frontend/tests/unit/panes/check.test.ts
@@ -0,0 +1,256 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { pane } from '../../../src/panes/check';
+import type { ShellContext, ProjectRef } from '../../../src/shell';
+
+vi.mock('../../../src/shell/shell', () => ({
+ lastArgs: () => undefined,
+ activePane: () => 'check',
+ chooseProject: async () => undefined,
+ partRoot: () => document.body,
+ setStatus: () => undefined,
+ setNavCount: () => undefined,
+ layoutOf: () => 'part',
+}));
+
+const PROJECT: ProjectRef = { id: 'shelf sorter', name: 'Shelf Sorter', product: 'none', dir: '/tmp/x', manifest: {} };
+
+function problem(rule: string, severity: string, file: string, line: number, message: string, fix = '') {
+ return { rule, severity, file, line, column: 0, message, fix, path: '' };
+}
+
+function result(problems: ReturnType[], checked = 100) {
+ const counts = { error: 0, warning: 0, info: 0 } as Record;
+ for (const p of problems) counts[p.severity] += 1;
+ return { ok: counts.error === 0, counts, problems, files: 3, bytes: 10, manifest: 'manifest.json', checked_at: checked, ms: 4, project: PROJECT.id };
+}
+
+interface Harness {
+ el: HTMLElement;
+ post: ReturnType;
+ get: ReturnType;
+ openPane: ReturnType;
+ fire: (name: string, data: unknown) => void;
+ setProject: (p: ProjectRef | null) => void;
+}
+
+function mount(project: ProjectRef | null, postImpl: (p: string) => Promise, getImpl: () => Promise = async () => ({ rules: [] })): Harness {
+ const el = document.createElement('div');
+ document.body.appendChild(el);
+ const listeners = new Map void>();
+ let current = project;
+ let changed: (p: ProjectRef | null) => void = () => undefined;
+ const post = vi.fn(postImpl);
+ const get = vi.fn(getImpl);
+ const openPane = vi.fn();
+ const ctx = {
+ api: { get, post, put: vi.fn(), del: vi.fn() },
+ events: { on: (name: string, cb: (d: unknown) => void) => { listeners.set(name, cb); return () => listeners.delete(name); } },
+ project: { current: () => current, onChange: (cb: (p: ProjectRef | null) => void) => { changed = cb; return () => undefined; }, open: vi.fn() },
+ notify: vi.fn(),
+ openPane,
+ commands: { register: vi.fn() },
+ dialog: { confirm: vi.fn(), form: vi.fn() },
+ } as unknown as ShellContext;
+ pane.mount(el, ctx);
+ return { el, post, get, openPane, fire: (n, d) => listeners.get(n)?.(d), setProject: (p) => { current = p; changed(p); } };
+}
+
+async function settle(): Promise {
+ for (let i = 0; i < 6; i++) await Promise.resolve();
+ await new Promise((r) => setTimeout(r, 0));
+}
+
+function q(h: Harness, sel: string): T {
+ return h.el.querySelector(sel)!;
+}
+
+function shown(h: Harness, sel: string): boolean {
+ return !q(h, sel).classList.contains('hidden');
+}
+
+const TWO = [
+ problem('manifest.id', 'error', 'manifest.json', 3, 'The id has a space in it.', 'Use lower case letters and dashes.'),
+ problem('lint.eval', 'warning', 'ui/app.js', 12, 'eval is not allowed.'),
+ problem('lint.todo', 'info', 'ui/app.js', 20, 'A note was left in the code.'),
+];
+
+describe('check pane', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ document.body.innerHTML = '';
+ });
+
+ it('says no project is open, disables Check and sends nothing', async () => {
+ const h = mount(null, async () => result([]));
+ await settle();
+ expect(q(h, '.check-sub').textContent).toBe('No project open');
+ expect(q(h, '.check-status-text').textContent).toBe('Open a project to check it.');
+ expect(shown(h, '.check-none')).toBe(true);
+ expect(q(h, '.check-run').disabled).toBe(true);
+ expect(h.post).not.toHaveBeenCalled();
+ });
+
+ it('asks the engine to validate the open project with its id encoded in the address', async () => {
+ const h = mount(PROJECT, async () => result([]));
+ await settle();
+ expect(h.post).toHaveBeenCalledTimes(1);
+ expect(h.post.mock.calls[0][0]).toBe('/api/projects/shelf%20sorter/validate');
+ });
+
+ it('shows one row per problem grouped under its file with the message and the fix', async () => {
+ const h = mount(PROJECT, async () => result(TWO));
+ await settle();
+ const files = [...h.el.querySelectorAll('.check-group')].map((g) => [g.querySelector('.check-file')!.textContent, g.querySelector('.check-group-count')!.textContent, g.querySelectorAll('.check-row').length]);
+ expect(files).toEqual([['manifest.json', '1', 1], ['ui/app.js', '2', 2]]);
+ const first = q(h, '.check-row');
+ expect(first.querySelector('.check-msg')!.textContent).toBe('The id has a space in it.');
+ expect(first.querySelector('.check-fix')!.textContent).toBe('Use lower case letters and dashes.');
+ expect(first.querySelector('.check-line')!.textContent).toBe('3');
+ });
+
+ it('counts problems of each kind on the filter chips', async () => {
+ const h = mount(PROJECT, async () => result(TWO));
+ await settle();
+ const counts = Object.fromEntries([...h.el.querySelectorAll('.check-filter')].map((b) => [b.dataset.filter, b.querySelector('.check-count')!.textContent]));
+ expect(counts).toEqual({ all: '3', error: '1', warning: '1', info: '1' });
+ });
+
+ it('sums errors, warnings and info in the status sentence', async () => {
+ const h = mount(PROJECT, async () => result(TWO));
+ await settle();
+ expect(q(h, '.check-status-text').textContent).toContain('1 error, 1 warning, 1 info.');
+ expect(q(h, '.check-status').classList.contains('error')).toBe(true);
+ });
+
+ it('says no problems were found for a clean project', async () => {
+ const h = mount(PROJECT, async () => result([]));
+ await settle();
+ expect(q(h, '.check-status-text').textContent).toBe('No problems found.');
+ expect(shown(h, '.check-clean')).toBe(true);
+ expect(h.el.querySelectorAll('.check-row')).toHaveLength(0);
+ });
+
+ it('shows only warnings when the Warnings filter is pressed and remembers the pressed chip', async () => {
+ const h = mount(PROJECT, async () => result(TWO));
+ await settle();
+ q(h, '.check-filter[data-filter="warning"]').click();
+ expect([...h.el.querySelectorAll('.check-msg')].map((m) => m.textContent)).toEqual(['eval is not allowed.']);
+ expect(q(h, '.check-filter[data-filter="warning"]').getAttribute('aria-pressed')).toBe('true');
+ expect(q(h, '.check-filter[data-filter="all"]').getAttribute('aria-pressed')).toBe('false');
+ });
+
+ it('says nothing to show when the filter leaves no problems', async () => {
+ const h = mount(PROJECT, async () => result([TWO[0]]));
+ await settle();
+ q(h, '.check-filter[data-filter="info"]').click();
+ expect(shown(h, '.check-filtered')).toBe(true);
+ expect(h.el.querySelectorAll('.check-row')).toHaveLength(0);
+ q(h, '.check-filter[data-filter="all"]').click();
+ expect(shown(h, '.check-filtered')).toBe(false);
+ expect(h.el.querySelectorAll('.check-row')).toHaveLength(1);
+ });
+
+ it('opens the studio at the file and line of a clicked problem', async () => {
+ const h = mount(PROJECT, async () => result(TWO));
+ await settle();
+ h.el.querySelectorAll('.check-row')[1].click();
+ expect(h.openPane).toHaveBeenCalledWith('studio', { path: 'ui/app.js', line: 12, column: 1, from: 'check', rule: 'lint.eval' });
+ });
+
+ it('keeps the same row node for a problem that is still there after checking again', async () => {
+ let answer = result(TWO, 100);
+ const h = mount(PROJECT, async () => answer);
+ await settle();
+ const kept = h.el.querySelectorAll('.check-row')[1];
+ const group = h.el.querySelectorAll('.check-group')[1];
+ answer = result([TWO[1]], 200);
+ q(h, '.check-run').click();
+ await settle();
+ expect(h.post).toHaveBeenCalledTimes(2);
+ const rows = h.el.querySelectorAll('.check-row');
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toBe(kept);
+ expect(kept.isConnected).toBe(true);
+ expect(h.el.querySelector('.check-group')).toBe(group);
+ expect(group.querySelector('.check-group-count')!.textContent).toBe('1');
+ });
+
+ it('keeps a file group collapsed when the same problems arrive again', async () => {
+ const h = mount(PROJECT, async () => result(TWO));
+ await settle();
+ const head = q(h, '.check-group-head');
+ head.click();
+ expect(head.getAttribute('aria-expanded')).toBe('false');
+ q(h, '.check-run').click();
+ await settle();
+ expect(q(h, '.check-group-head')).toBe(head);
+ expect(head.getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('shows the engine refusal as a sentence when the check cannot run', async () => {
+ const h = mount(PROJECT, async () => { throw new Error('The manifest could not be read.'); });
+ await settle();
+ expect(q(h, '.check-status-text').textContent).toBe('Check could not run: The manifest could not be read.');
+ expect(q(h, '.check-status').classList.contains('error')).toBe(true);
+ expect(q(h, '.check-run').disabled).toBe(false);
+ });
+
+ it('fills the rules table from the engine the first time Rules is opened and asks only once', async () => {
+ const rules = [{ id: 'manifest.id', severity: 'error', title: 'Id shape', text: 'The id uses lower case letters.' }, { id: 'lint.eval', severity: 'warning', title: 'No eval', text: 'eval is refused by hosts.' }];
+ const h = mount(PROJECT, async () => result([]), async () => ({ rules }));
+ await settle();
+ expect(h.get).not.toHaveBeenCalled();
+ q(h, '.check-rules-toggle').click();
+ await settle();
+ expect(h.get).toHaveBeenCalledWith('/api/validate/rules');
+ expect(shown(h, '.check-rules')).toBe(true);
+ const cells = [...h.el.querySelectorAll('.check-rules-table tbody tr')].map((r) => [r.querySelector('.check-rule-title')!.textContent, r.querySelectorAll('td')[2].textContent]);
+ expect(cells).toEqual([['Id shape', 'The id uses lower case letters.'], ['No eval', 'eval is refused by hosts.']]);
+ q(h, '.check-rules-toggle').click();
+ q(h, '.check-rules-toggle').click();
+ await settle();
+ expect(h.get).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows a rule text with markup in it as text', async () => {
+ const h = mount(PROJECT, async () => result([problem('x', 'error', 'a.js', 1, '
is bad')]));
+ await settle();
+ expect(q(h, '.check-msg').textContent).toBe('
is bad');
+ expect(h.el.querySelector('.check-msg img')).toBeNull();
+ });
+
+ it('clears the problems and stops showing them when the project is closed', async () => {
+ const h = mount(PROJECT, async () => result(TWO));
+ await settle();
+ h.setProject(null);
+ expect(h.el.querySelectorAll('.check-row')).toHaveLength(0);
+ expect(q(h, '.check-sub').textContent).toBe('No project open');
+ expect(q(h, '.check-filter[data-filter="all"] .check-count').textContent).toBe('0');
+ });
+
+ it('runs a check when the pane is opened with the run argument', async () => {
+ const h = mount(PROJECT, async () => result([]));
+ await settle();
+ h.fire('pane.open', { id: 'check', args: { run: true } });
+ await settle();
+ expect(h.post).toHaveBeenCalledTimes(2);
+ });
+
+ it('goes to the New pane from the empty state', async () => {
+ const h = mount(null, async () => result([]));
+ q(h, '.check-new').click();
+ expect(h.openPane).toHaveBeenCalledWith('new');
+ });
+
+ it('remembers that automatic checking was switched off', async () => {
+ const h = mount(PROJECT, async () => result([]));
+ await settle();
+ const box = q(h, '.check-auto input');
+ expect(box.checked).toBe(true);
+ box.checked = false;
+ box.dispatchEvent(new Event('change', { bubbles: true }));
+ const again = mount(PROJECT, async () => result([]));
+ await settle();
+ expect(q(again, '.check-auto input').checked).toBe(false);
+ });
+});
diff --git a/frontend/tests/unit/panes/markdown.test.ts b/frontend/tests/unit/panes/markdown.test.ts
new file mode 100644
index 0000000..d56ce72
--- /dev/null
+++ b/frontend/tests/unit/panes/markdown.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect } from 'vitest';
+import { render, slug, escapeHtml } from '../../../src/panes/docs/markdown';
+
+function dom(src: string): HTMLElement {
+ const el = document.createElement('div');
+ el.innerHTML = render(src).html;
+ return el;
+}
+
+describe('docs markdown', () => {
+ it('turns a level one heading into an h1 and reports it as the title', () => {
+ const r = render('# Getting Started\n\nSome text.');
+ expect(r.title).toBe('Getting Started');
+ const h1 = dom('# Getting Started').querySelector('h1')!;
+ h1.querySelector('a[aria-hidden="true"]')?.remove();
+ expect(h1.textContent!.trim()).toBe('Getting Started');
+ });
+
+ it('lists every heading with its level in document order', () => {
+ const r = render('# One\n\n## Two\n\ntext\n\n### Three\n');
+ expect(r.headings.map((h) => [h.level, h.text])).toEqual([[1, 'One'], [2, 'Two'], [3, 'Three']]);
+ });
+
+ it('gives two headings with the same text different ids', () => {
+ const r = render('## Setup\n\n## Setup\n');
+ expect(r.headings).toHaveLength(2);
+ expect(r.headings[0].id).not.toBe(r.headings[1].id);
+ });
+
+ it('makes a heading id that is its text in lower case with dashes', () => {
+ expect(slug('Hello World')).toBe('hello-world');
+ expect(render('## Hello World').headings[0].id).toBe('hello-world');
+ });
+
+ it('shows raw html from the source as text and builds no script element', () => {
+ const el = dom('Hi there');
+ expect(el.querySelector('script')).toBeNull();
+ expect(el.textContent).toContain('');
+ });
+
+ it('escapes the five html special characters', () => {
+ expect(escapeHtml(`'&'`)).toBe('<a href="x">'&'</a>');
+ });
+
+ it('renders emphasis, strong text and inline code', () => {
+ const el = dom('This is *soft*, **loud** and `code`.');
+ expect(el.querySelector('em')!.textContent).toBe('soft');
+ expect(el.querySelector('strong')!.textContent).toBe('loud');
+ expect(el.querySelector('code')!.textContent).toBe('code');
+ });
+
+ it('keeps the text of a fenced code block exactly, markup included', () => {
+ const el = dom('```js\nconst a = "";\n if (a) {}\n```\n');
+ expect(el.querySelector('pre')!.textContent!.replace(/\n$/, '')).toBe('const a = "";\n if (a) {}');
+ expect(el.querySelector('pre b')).toBeNull();
+ });
+
+ it('builds a bullet list with one item per line', () => {
+ const el = dom('- one\n- two\n- three\n');
+ expect([...el.querySelectorAll('ul > li')].map((li) => li.textContent!.trim())).toEqual(['one', 'two', 'three']);
+ });
+
+ it('builds a numbered list as an ordered list', () => {
+ const el = dom('1. first\n2. second\n');
+ expect([...el.querySelectorAll('ol > li')].map((li) => li.textContent!.trim())).toEqual(['first', 'second']);
+ });
+
+ it('builds a table with header cells and body rows', () => {
+ const el = dom('| Key | Value |\n| --- | --- |\n| a | 1 |\n| b | 2 |\n');
+ expect([...el.querySelectorAll('th')].map((c) => c.textContent!.trim())).toEqual(['Key', 'Value']);
+ expect([...el.querySelectorAll('tbody tr')].map((r) => [...r.querySelectorAll('td')].map((c) => c.textContent!.trim()))).toEqual([['a', '1'], ['b', '2']]);
+ });
+
+ it('wraps quoted lines in a blockquote', () => {
+ expect(dom('> take care\n').querySelector('blockquote')!.textContent!.trim()).toBe('take care');
+ });
+
+ it('passes each link through the resolver and uses the address it returns', () => {
+ const seen: string[] = [];
+ const r = render('See [the guide](guide.md).', (href) => { seen.push(href); return { href: `#/docs/${href}`, attrs: '' }; });
+ const el = document.createElement('div');
+ el.innerHTML = r.html;
+ expect(seen).toEqual(['guide.md']);
+ expect(el.querySelector('a')!.getAttribute('href')).toBe('#/docs/guide.md');
+ expect(el.querySelector('a')!.textContent).toBe('the guide');
+ });
+
+ it('builds no link with a javascript address', () => {
+ const el = dom('[x](javascript:alert(1))');
+ const a = el.querySelector('a');
+ expect(a === null || !/^\s*javascript:/i.test(a.getAttribute('href') ?? '')).toBe(true);
+ });
+
+ it('separates paragraphs at a blank line', () => {
+ expect([...dom('first\n\nsecond\n').querySelectorAll('p')].map((p) => p.textContent!.trim())).toEqual(['first', 'second']);
+ });
+
+ it('returns the plain text of the page for search without markup', () => {
+ const r = render('# Title\n\nSome **bold** words.');
+ expect(r.text).toContain('Some bold words.');
+ expect(r.text).not.toContain('<');
+ });
+});
diff --git a/frontend/tests/unit/panes/new.test.ts b/frontend/tests/unit/panes/new.test.ts
new file mode 100644
index 0000000..a186637
--- /dev/null
+++ b/frontend/tests/unit/panes/new.test.ts
@@ -0,0 +1,300 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { pane } from '../../../src/panes/new';
+import { HOSTS } from '../../../src/shell';
+import type { ShellContext } from '../../../src/shell';
+
+vi.mock('../../../src/shell/shell', () => ({
+ lastArgs: () => undefined,
+ activePane: () => 'new',
+ chooseProject: async () => undefined,
+ partRoot: () => document.body,
+ setStatus: () => undefined,
+ setNavCount: () => undefined,
+ layoutOf: () => 'start',
+}));
+
+const A = HOSTS[0].id;
+const B = HOSTS[1].id;
+
+function starter(product: string, id: string, name: string) {
+ return {
+ product,
+ starter: id,
+ title: id,
+ name,
+ summary: 's',
+ uses: ['doc.read'],
+ description: `${name} description`,
+ permissions: id === 'command' ? [] : ['document', 'network'],
+ panels: id === 'command' ? [] : [{ id: 'main', title: 'Main Panel', location: 'dock' }],
+ commands: id === 'panel' ? [] : [{ id: 'go', title: 'Go Now' }],
+ };
+}
+
+function catalogue() {
+ return {
+ starters: [],
+ products: [A, B].map((p) => ({
+ id: p,
+ name: p,
+ docs: null,
+ starters: ['panel', 'command', 'panel-commands'].map((s) => starter(p, s, `${p} ${s} kit`)),
+ })),
+ };
+}
+
+interface Harness {
+ el: HTMLElement;
+ get: ReturnType;
+ post: ReturnType;
+ open: ReturnType;
+ notify: ReturnType;
+ openPane: ReturnType;
+ fire: (name: string, data: unknown) => void;
+}
+
+function mount(getImpl: () => Promise, postImpl: (p: string, body: unknown) => Promise = async () => ({ id: 'x', name: 'X' })): Harness {
+ const el = document.createElement('div');
+ document.body.appendChild(el);
+ const listeners = new Map void>();
+ const get = vi.fn(getImpl);
+ const post = vi.fn(postImpl);
+ const open = vi.fn(async () => undefined);
+ const notify = vi.fn();
+ const openPane = vi.fn();
+ const ctx = {
+ api: { get, post, put: vi.fn(), del: vi.fn() },
+ events: { on: (name: string, cb: (d: unknown) => void) => { listeners.set(name, cb); return () => listeners.delete(name); } },
+ project: { current: () => null, onChange: () => () => undefined, open },
+ notify,
+ openPane,
+ commands: { register: vi.fn() },
+ dialog: { confirm: vi.fn(), form: vi.fn() },
+ } as unknown as ShellContext;
+ pane.mount(el, ctx);
+ return { el, get, post, open, notify, openPane, fire: (n, d) => listeners.get(n)?.(d) };
+}
+
+async function settle(): Promise {
+ for (let i = 0; i < 6; i++) await Promise.resolve();
+ await new Promise((r) => setTimeout(r, 0));
+}
+
+function q(h: Harness, sel: string): T {
+ return h.el.querySelector(sel)!;
+}
+
+function submit(h: Harness): void {
+ q(h, '.new-form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+}
+
+function type(h: Harness, value: string): void {
+ const input = q(h, '#new-name');
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+describe('new extension pane', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ document.body.innerHTML = '';
+ });
+
+ it('asks the engine for the starter catalogue once when it mounts', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ expect(h.get).toHaveBeenCalledTimes(1);
+ expect(h.get).toHaveBeenCalledWith('/api/templates');
+ });
+
+ it('offers one app choice for every host app', async () => {
+ const h = mount(async () => catalogue());
+ const ids = [...h.el.querySelectorAll('.new-app')].map((b) => b.dataset.product);
+ expect(ids).toEqual(HOSTS.map((p) => p.id));
+ });
+
+ it('keeps Create disabled until the catalogue has arrived', async () => {
+ let release: (v: unknown) => void = () => undefined;
+ const h = mount(() => new Promise((r) => { release = r; }));
+ type(h, 'My Tool');
+ expect(q(h, '.new-create').disabled).toBe(true);
+ release(catalogue());
+ await settle();
+ expect(q(h, '.new-create').disabled).toBe(false);
+ });
+
+ it('fills the name field and detail card from the chosen starter in the engine answer', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ expect(q(h, '#new-name').value).toBe(`${A} panel kit`);
+ expect(q(h, '.new-detail-title').textContent).toBe(`${A} panel kit for ${HOSTS[0].name}`);
+ expect(q(h, '.new-detail-sub').textContent).toBe(`${A} panel kit description`);
+ });
+
+ it('lists each permission of the starter with a plain sentence', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ const items = [...h.el.querySelectorAll('.new-perms li')].map((li) => li.textContent);
+ expect(items).toEqual(['documentread and change the open document', 'networkreach the internet']);
+ });
+
+ it('says nothing needs consent for a starter without permissions', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ q(h, '[data-starter="command"]').click();
+ expect(q(h, '.new-perms').textContent).toBe('Nothing that needs consent');
+ expect(q(h, '.new-adds').textContent).toContain('Command Go Now, runs headless');
+ });
+
+ it('shows panel and command counts on each starter card', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ const chips = [...h.el.querySelectorAll('[data-starter="panel-commands"] .chip')].map((c) => c.textContent);
+ expect(chips).toEqual(['1 panel', '1 command', 'document', 'network']);
+ });
+
+ it('marks only the clicked app as checked and follows it with the starter name', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ q(h, `.new-app[data-product="${B}"]`).click();
+ const checked = [...h.el.querySelectorAll('.new-app[aria-checked="true"]')].map((b) => b.dataset.product);
+ expect(checked).toEqual([B]);
+ expect(q(h, '#new-name').value).toBe(`${B} panel kit`);
+ });
+
+ it('keeps a name the user typed when another starter is chosen', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ type(h, 'Shelf Sorter');
+ q(h, '[data-starter="command"]').click();
+ expect(q(h, '#new-name').value).toBe('Shelf Sorter');
+ });
+
+ it('shows the id made from the typed name in lower case with dashes', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ type(h, ' Shelf Sorter 2! ');
+ expect(q(h, '.new-id').textContent).toBe('Id shelf-sorter-2 (a number is added if a project has it already)');
+ });
+
+ it('sends no request and disables Create when the name is empty', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ type(h, ' ');
+ expect(q(h, '.new-create').disabled).toBe(true);
+ submit(h);
+ await settle();
+ expect(h.post).not.toHaveBeenCalled();
+ expect(q(h, '.new-id').textContent).toBe('The id is made from the name.');
+ });
+
+ it('sends the chosen app, starter, trimmed name and description when Create is pressed', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ q(h, `.new-app[data-product="${B}"]`).click();
+ q(h, '[data-starter="command"]').click();
+ type(h, ' Shelf Sorter ');
+ q(h, '#new-desc').value = ' Sorts shelves. ';
+ submit(h);
+ await settle();
+ expect(h.post).toHaveBeenCalledTimes(1);
+ expect(h.post).toHaveBeenCalledWith('/api/templates/create', { product: B, starter: 'command', name: 'Shelf Sorter', description: 'Sorts shelves.' });
+ });
+
+ it('leaves the description out of the request when it is empty', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ submit(h);
+ await settle();
+ const body = h.post.mock.calls[0][1] as Record;
+ expect(body.description).toBeUndefined();
+ expect(body.name).toBe(`${A} panel kit`);
+ });
+
+ it('opens the made project and goes to the studio after the engine answers', async () => {
+ const h = mount(async () => catalogue(), async () => ({ id: 'shelf-sorter', name: 'Shelf Sorter' }));
+ await settle();
+ submit(h);
+ await settle();
+ expect(h.open).toHaveBeenCalledWith('shelf-sorter');
+ expect(h.openPane).toHaveBeenCalledWith('studio', { path: 'package/ui/app.js', from: 'new' });
+ expect(h.notify.mock.calls[0][0]).toContain('Shelf Sorter is ready');
+ expect(h.notify.mock.calls[0][1]).toBe('success');
+ });
+
+ it('shows the engine refusal as a sentence and does not open anything', async () => {
+ const h = mount(async () => catalogue(), async () => { throw new Error('The name is already taken by another project.'); });
+ await settle();
+ submit(h);
+ await settle();
+ expect(q(h, '.new-msg').textContent).toBe('The name is already taken by another project.');
+ expect(h.notify).toHaveBeenCalledWith('The name is already taken by another project.', 'error');
+ expect(h.open).not.toHaveBeenCalled();
+ expect(h.openPane).not.toHaveBeenCalled();
+ expect(q(h, '.new-create').disabled).toBe(false);
+ });
+
+ it('does not send a second request while the first is still being written', async () => {
+ let release: (v: unknown) => void = () => undefined;
+ const h = mount(async () => catalogue(), () => new Promise((r) => { release = r; }));
+ await settle();
+ submit(h);
+ submit(h);
+ await settle();
+ expect(h.post).toHaveBeenCalledTimes(1);
+ expect(q(h, '.new-msg').textContent).toBe('Writing the project');
+ expect(q(h, '.new-create').disabled).toBe(true);
+ release({ id: 'a', name: 'A' });
+ await settle();
+ expect(q(h, '.new-create').disabled).toBe(false);
+ });
+
+ it('says the starters could not be read when the catalogue request fails', async () => {
+ const h = mount(async () => { throw new Error('The engine is not reachable.'); });
+ await settle();
+ expect(q(h, '.new-msg').textContent).toBe('The starters could not be read: The engine is not reachable.');
+ expect(q(h, '.new-create').disabled).toBe(true);
+ });
+
+ it('remembers the chosen app and starter for the next time the pane is mounted', async () => {
+ const first = mount(async () => catalogue());
+ await settle();
+ q(first, `.new-app[data-product="${B}"]`).click();
+ q(first, '[data-starter="panel-commands"]').click();
+ const second = mount(async () => catalogue());
+ await settle();
+ expect(q(second, '.new-app[aria-checked="true"]').dataset.product).toBe(B);
+ expect(q(second, '.new-starter[aria-checked="true"]').dataset.starter).toBe('panel-commands');
+ });
+
+ it('takes app, starter and name from the arguments the pane is opened with', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ h.fire('pane.open', { id: 'new', args: { product: B, starter: 'command', name: 'From Docs' } });
+ expect(q(h, '#new-name').value).toBe('From Docs');
+ expect(q(h, '.new-app[aria-checked="true"]').dataset.product).toBe(B);
+ expect(q(h, '.new-starter[aria-checked="true"]').dataset.starter).toBe('command');
+ });
+
+ it('ignores an open event meant for another pane', async () => {
+ const h = mount(async () => catalogue());
+ await settle();
+ h.fire('pane.open', { id: 'docs', args: { product: B, name: 'Other' } });
+ expect(q(h, '.new-app[aria-checked="true"]').dataset.product).toBe(A);
+ expect(q(h, '#new-name').value).toBe(`${A} panel kit`);
+ });
+
+ it('keeps the same card and field nodes when choices change', async () => {
+ const h = mount(async () => catalogue());
+ const card = q(h, '[data-starter="panel"]');
+ const input = q(h, '#new-name');
+ const detail = q(h, '.new-detail');
+ await settle();
+ q(h, `.new-app[data-product="${B}"]`).click();
+ q(h, '[data-starter="command"]').click();
+ expect(q(h, '[data-starter="panel"]')).toBe(card);
+ expect(q(h, '#new-name')).toBe(input);
+ expect(q(h, '.new-detail')).toBe(detail);
+ expect(card.isConnected).toBe(true);
+ });
+});
diff --git a/frontend/tests/unit/panes/studio-helpers.test.ts b/frontend/tests/unit/panes/studio-helpers.test.ts
new file mode 100644
index 0000000..dbf434c
--- /dev/null
+++ b/frontend/tests/unit/panes/studio-helpers.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi } from 'vitest';
+import { setKey, formatManifest } from '../../../src/panes/studio/manifest';
+import { minimalChange, Text } from '../../../src/panes/studio/editor';
+import { short, pretty } from '../../../src/panes/preview/log';
+
+vi.mock('../../../src/shell/shell', () => ({
+ lastArgs: () => undefined,
+ activePane: () => 'studio',
+ chooseProject: async () => undefined,
+ partRoot: () => document.body,
+ setStatus: () => undefined,
+ setNavCount: () => undefined,
+ layoutOf: () => 'studio',
+}));
+
+const MANIFEST = {
+ format: 'formext',
+ format_version: 1,
+ id: 'shelf-sorter',
+ name: 'Shelf "Sorter"',
+ permissions: ['document', 'network'],
+ contributes: { panels: [{ id: 'main', title: 'Main', location: 'dock' }], commands: [] },
+ description: 'A long sentence that makes the whole manifest too wide to sit on a single line of one hundred characters.',
+ payload: { nested: { deep: [1, 2.5, true, null, 'x'] }, empty: {} },
+};
+
+function apply(prev: string, next: string): string {
+ const c = minimalChange(Text.of(prev.split('\n')), next);
+ if (!c) return prev;
+ return prev.slice(0, c.from) + c.insert + prev.slice(c.to);
+}
+
+describe('studio manifest text', () => {
+ it('writes manifest text that reads back as the same JSON value', () => {
+ expect(JSON.parse(formatManifest(MANIFEST))).toEqual(MANIFEST);
+ });
+
+ it('keeps the keys in the order they were given', () => {
+ expect(Object.keys(JSON.parse(formatManifest(MANIFEST)) as object)).toEqual(Object.keys(MANIFEST));
+ });
+
+ it('reads back the same value with a tab indent and a narrow width', () => {
+ expect(JSON.parse(formatManifest(MANIFEST, '\t', 20))).toEqual(MANIFEST);
+ });
+
+ it('changes the value of a key that is already there without moving it', () => {
+ const out = setKey({ id: 'a', name: 'A', version: '1.0.0' }, 'name', 'B');
+ expect(out).toEqual({ id: 'a', name: 'B', version: '1.0.0' });
+ expect(Object.keys(out)).toEqual(['id', 'name', 'version']);
+ });
+
+ it('removes a key when its value is cleared and leaves the others alone', () => {
+ expect(setKey({ id: 'a', name: 'A', version: '1.0.0' }, 'name', undefined)).toEqual({ id: 'a', version: '1.0.0' });
+ });
+
+ it('adds a key without losing or changing any other key', () => {
+ const out = setKey({ id: 'a', version: '1.0.0', zeta: 1 }, 'name', 'A');
+ expect(out).toEqual({ id: 'a', name: 'A', version: '1.0.0', zeta: 1 });
+ });
+
+ it('puts an unknown key at the end', () => {
+ expect(Object.keys(setKey({ id: 'a', name: 'A' }, 'x-custom', 1))).toEqual(['id', 'name', 'x-custom']);
+ });
+});
+
+describe('studio editor change', () => {
+ it('reports no change when the new text is the same', () => {
+ expect(minimalChange(Text.of(['same', 'text']), 'same\ntext')).toBeNull();
+ });
+
+ it('gives a change that turns the old text into the new text', () => {
+ const cases: [string, string][] = [
+ ['const a = 1;\nconst b = 2;', 'const a = 1;\nconst c = 3;\nconst b = 2;'],
+ ['abc', ''],
+ ['', 'abc'],
+ ['aaaa', 'aa'],
+ ['hello world', 'hello brave world'],
+ ['x\ny\nz', 'x\nz'],
+ ];
+ for (const [prev, next] of cases) expect(apply(prev, next)).toBe(next);
+ });
+
+ it('touches only the changed middle and leaves the shared start and end alone', () => {
+ const c = minimalChange(Text.of(['hello world']), 'hello brave world')!;
+ expect(c.from).toBeGreaterThanOrEqual(5);
+ expect(c.to - c.from).toBe(0);
+ expect(c.insert).toHaveLength(6);
+ });
+});
+
+describe('preview message text', () => {
+ it('shows a short value as its JSON', () => {
+ expect(short({ a: 1, b: 'x' })).toBe('{"a":1,"b":"x"}');
+ });
+
+ it('cuts a long line at the limit and marks the cut', () => {
+ const out = short({ list: Array.from({ length: 200 }, (_v, i) => i) }, 50);
+ expect(out).toHaveLength(53);
+ expect(out.endsWith('...')).toBe(true);
+ });
+
+ it('says how many characters a long string had instead of printing it', () => {
+ expect(short({ data: 'a'.repeat(500) })).toContain('(500 chars)');
+ });
+
+ it('prints a value in full so it reads back as the same JSON', () => {
+ const v = { method: 'doc.read', params: { ids: [1, 2], deep: { ok: true } } };
+ expect(JSON.parse(pretty(v))).toEqual(v);
+ });
+
+ it('prints something for a value that has no JSON form', () => {
+ const loop: Record = {};
+ loop.self = loop;
+ expect(typeof short(loop)).toBe('string');
+ expect(short(undefined)).toBe('null');
+ });
+});
diff --git a/frontend/tests/unit/shell/host-bridge.test.ts b/frontend/tests/unit/shell/host-bridge.test.ts
new file mode 100644
index 0000000..72fef2b
--- /dev/null
+++ b/frontend/tests/unit/shell/host-bridge.test.ts
@@ -0,0 +1,306 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { ExtensionHost, PERMISSION_WORDS } from '../../../../contract/host/host-bridge';
+import type { HostHandlers, Permission } from '../../../../contract/host/host-bridge';
+import { makeExt, fakeWindow, attach, ask, fromFrame, flush } from './wire';
+
+function handlers(over: Partial = {}): HostHandlers {
+ return {
+ product: 'formwav',
+ app: 'form.wav',
+ appVersion: '9.9.9',
+ locale: () => 'en-GB',
+ theme: () => ({ mode: 'dark', tokens: { '--bg': '#000000' } }),
+ notify: vi.fn(),
+ consent: vi.fn(async () => true),
+ ...over,
+ };
+}
+
+async function granted(host: ExtensionHost, perms: Permission[]) {
+ const ext = makeExt({ permissions: perms });
+ await host.ensureConsent(ext);
+ const container = document.createElement('div');
+ const handle = host.mount(ext, container);
+ const fake = fakeWindow();
+ attach(handle, fake);
+ return { ext, handle, fake, container };
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ document.body.innerHTML = '';
+});
+
+describe('host bridge frame', () => {
+ it('builds the sandboxed frame the contract describes', () => {
+ const host = new ExtensionHost(handlers());
+ const box = document.createElement('div');
+ const h = host.mount(makeExt(), box);
+ expect(h.frame.getAttribute('sandbox')).toBe('allow-scripts');
+ expect(h.frame.getAttribute('allow')).toBe('');
+ expect(h.frame.getAttribute('referrerpolicy')).toBe('no-referrer');
+ expect(h.frame.getAttribute('title')).toBe('Beat Markers');
+ expect(box.querySelector('iframe')).toBe(h.frame);
+ h.dispose();
+ expect(box.querySelector('iframe')).toBeNull();
+ });
+
+ it('answers host.hello with api 1, the extension identity and the theme', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, []);
+ const reply = await ask(fake, 1, 'host.hello');
+ expect(reply.formext).toBe(1);
+ expect(reply.jsonrpc).toBe('2.0');
+ expect(reply.result).toEqual({
+ product: 'formwav',
+ app: 'form.wav',
+ appVersion: '9.9.9',
+ api: '1',
+ extension: { id: 'org.example.beats', version: '1.0.0', source: 'sideload' },
+ permissions: [],
+ theme: { mode: 'dark', tokens: { '--bg': '#000000' } },
+ locale: 'en-GB',
+ });
+ handle.dispose();
+ });
+
+ it('ignores messages that do not come from the extension frame', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, []);
+ fromFrame(window, { formext: 1, jsonrpc: '2.0', id: 5, method: 'host.hello', params: {} });
+ fromFrame({ postMessage() {} }, { formext: 1, jsonrpc: '2.0', id: 6, method: 'host.hello', params: {} });
+ await flush();
+ expect(fake.sent).toEqual([]);
+ handle.dispose();
+ });
+
+ it('ignores messages without the formext marker or the json-rpc version', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, []);
+ fromFrame(fake.win, { jsonrpc: '2.0', id: 1, method: 'host.hello', params: {} });
+ fromFrame(fake.win, { formext: 1, jsonrpc: '1.0', id: 2, method: 'host.hello', params: {} });
+ await flush();
+ expect(fake.sent).toEqual([]);
+ handle.dispose();
+ });
+
+ it('refuses a method outside API 1 with -32601', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, []);
+ const reply = await ask(fake, 3, 'shell.exec', { cmd: 'ls' });
+ expect(reply.error.code).toBe(-32601);
+ handle.dispose();
+ });
+
+ it('refuses document.read with -32001 when the extension did not ask for document', async () => {
+ const readDocument = vi.fn(() => ({ title: 'x' }));
+ const host = new ExtensionHost(handlers({ readDocument }));
+ const { fake, handle } = await granted(host, ['files-read']);
+ const reply = await ask(fake, 1, 'document.read');
+ expect(reply.error.code).toBe(-32001);
+ expect(readDocument).not.toHaveBeenCalled();
+ handle.dispose();
+ });
+
+ it('refuses a permissioned call with -32001 when consent was never given and never prompts mid-call', async () => {
+ const consent = vi.fn(async () => true);
+ const host = new ExtensionHost(handlers({ consent, readDocument: () => ({}) }));
+ const ext = makeExt({ permissions: ['document'] });
+ const handle = host.mount(ext, document.createElement('div'));
+ const fake = fakeWindow();
+ attach(handle, fake);
+ const hello = await ask(fake, 1, 'host.hello');
+ expect(hello.result.permissions).toEqual([]);
+ const reply = await ask(fake, 2, 'document.read');
+ expect(reply.error.code).toBe(-32001);
+ expect(consent).not.toHaveBeenCalled();
+ handle.dispose();
+ });
+
+ it('hands document.read to the app once document is granted and reports the permission in hello', async () => {
+ const host = new ExtensionHost(handlers({ readDocument: (_e, p) => ({ what: p.what ?? 'all', bpm: 120 }) }));
+ const { fake, handle } = await granted(host, ['document']);
+ expect((await ask(fake, 1, 'host.hello')).result.permissions).toEqual(['document']);
+ expect((await ask(fake, 2, 'document.read', { what: 'markers' })).result).toEqual({ what: 'markers', bpm: 120 });
+ handle.dispose();
+ });
+
+ it('answers -32003 for a granted method the app does not offer', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, ['network']);
+ const reply = await ask(fake, 1, 'net.fetch', { url: 'https://example.org/' });
+ expect(reply.error.code).toBe(-32003);
+ handle.dispose();
+ });
+
+ it('refuses net.fetch to an address that is not https with -32602', async () => {
+ const fetcher = vi.fn(async () => ({ status: 200, headers: {}, body: '' }));
+ const host = new ExtensionHost(handlers({ fetch: fetcher }));
+ const { fake, handle } = await granted(host, ['network']);
+ const reply = await ask(fake, 1, 'net.fetch', { url: 'http://example.org/' });
+ expect(reply.error.code).toBe(-32602);
+ expect(fetcher).not.toHaveBeenCalled();
+ const ok = await ask(fake, 2, 'net.fetch', { url: 'https://example.org/' });
+ expect(ok.result.status).toBe(200);
+ handle.dispose();
+ });
+
+ it('refuses document.apply ops without a command name with -32602', async () => {
+ const applyDocument = vi.fn(async () => ({ applied: 0, results: [] }));
+ const host = new ExtensionHost(handlers({ applyDocument }));
+ const { fake, handle } = await granted(host, ['document']);
+ const reply = await ask(fake, 1, 'document.apply', { label: 'x', ops: [{ args: {} }] });
+ expect(reply.error.code).toBe(-32602);
+ expect(applyDocument).not.toHaveBeenCalled();
+ handle.dispose();
+ });
+
+ it('refuses ui.notify without text with -32602 and passes a valid level through', async () => {
+ const notify = vi.fn();
+ const host = new ExtensionHost(handlers({ notify }));
+ const { fake, handle } = await granted(host, []);
+ expect((await ask(fake, 1, 'ui.notify', { message: 42 })).error.code).toBe(-32602);
+ expect((await ask(fake, 2, 'ui.notify', { message: 'Saved', level: 'success' })).result).toBeNull();
+ expect(notify).toHaveBeenCalledWith(expect.objectContaining({ id: 'org.example.beats' }), 'Saved', 'success');
+ handle.dispose();
+ });
+
+ it('refuses files.save without data and files.open without files-read', async () => {
+ const host = new ExtensionHost(handlers({ saveFile: async (_e, name) => ({ saved: true, name }), openFiles: async () => [] }));
+ const { fake, handle } = await granted(host, ['files-write']);
+ expect((await ask(fake, 1, 'files.save', { name: 'a.txt' })).error.code).toBe(-32602);
+ expect((await ask(fake, 2, 'files.save', { name: 'a.txt', type: 'text/plain', data: 'aGk=' })).result).toEqual({ saved: true, name: 'a.txt' });
+ expect((await ask(fake, 3, 'files.open', { accept: ['.wav'] })).error.code).toBe(-32001);
+ handle.dispose();
+ });
+
+ it('stores values per extension and returns null for a key never set', async () => {
+ const host = new ExtensionHost(handlers());
+ const a = await granted(host, []);
+ const other = makeExt({ id: 'org.example.other' });
+ const hb = host.mount(other, document.createElement('div'));
+ const b = fakeWindow();
+ attach(hb, b);
+ expect((await ask(a.fake, 1, 'storage.get', { key: 'bpm' })).result).toBeNull();
+ await ask(a.fake, 2, 'storage.set', { key: 'bpm', value: { n: 128, tags: ['x'] } });
+ expect((await ask(a.fake, 3, 'storage.get', { key: 'bpm' })).result).toEqual({ n: 128, tags: ['x'] });
+ expect((await ask(b, 4, 'storage.get', { key: 'bpm' })).result).toBeNull();
+ a.handle.dispose();
+ hb.dispose();
+ });
+
+ it('refuses storage past 256 KB per extension with -32004', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, []);
+ const small = await ask(fake, 1, 'storage.set', { key: 'a', value: 'x'.repeat(200 * 1024) });
+ expect(small.error).toBeUndefined();
+ const big = await ask(fake, 2, 'storage.set', { key: 'b', value: 'y'.repeat(100 * 1024) });
+ expect(big.error.code).toBe(-32004);
+ expect((await ask(fake, 3, 'storage.get', { key: 'b' })).result).toBeNull();
+ handle.dispose();
+ });
+
+ it('caps a resize request at 4000 and ignores a non-positive height', async () => {
+ const host = new ExtensionHost(handlers());
+ const onResize = vi.fn();
+ const handle = host.mount(makeExt(), document.createElement('div'), { onResize });
+ const fake = fakeWindow();
+ attach(handle, fake);
+ await ask(fake, 1, 'ui.resize', { height: 9000 });
+ await ask(fake, 2, 'ui.resize', { height: -5 });
+ await ask(fake, 3, 'ui.resize', { height: 320 });
+ expect(onResize.mock.calls).toEqual([[4000], [320]]);
+ handle.dispose();
+ });
+
+ it('sends ext.deactivate on dispose and cancels waiting requests with -32002', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, []);
+ await ask(fake, 1, 'host.hello');
+ const waiting = handle.activate({ reason: 'panel', panel: 'main' });
+ await flush();
+ expect(fake.sent.some((m) => m.method === 'ext.activate' && m.params.panel === 'main')).toBe(true);
+ handle.dispose();
+ await expect(waiting).rejects.toMatchObject({ code: -32002 });
+ expect(fake.sent.at(-1)).toMatchObject({ method: 'ext.deactivate', params: {} });
+ });
+
+ it('holds host requests until the extension has said hello', async () => {
+ const host = new ExtensionHost(handlers());
+ const { fake, handle } = await granted(host, []);
+ void handle.send('ext.event', { name: 'x', data: 1 }).catch(() => undefined);
+ await flush();
+ expect(fake.sent).toEqual([]);
+ await ask(fake, 1, 'host.hello');
+ await flush();
+ expect(fake.sent.some((m) => m.method === 'ext.event')).toBe(true);
+ handle.dispose();
+ });
+
+ it('names every permission in plain words as the contract lists them', () => {
+ expect(PERMISSION_WORDS.document.toLowerCase()).toBe('read and change the open document');
+ expect(PERMISSION_WORDS['files-read'].toLowerCase()).toBe('open files you choose');
+ expect(PERMISSION_WORDS['files-write'].toLowerCase()).toBe('save files where you choose');
+ expect(PERMISSION_WORDS.network.toLowerCase()).toBe('reach the internet');
+ expect(PERMISSION_WORDS.models.toLowerCase()).toBe('use local models');
+ });
+});
+
+describe('host bridge consent', () => {
+ it('asks before creating a frame and creates none when the person says Not Now', async () => {
+ const consent = vi.fn(async () => false);
+ const host = new ExtensionHost(handlers({ consent }));
+ const box = document.createElement('div');
+ const out = await host.open(makeExt({ permissions: ['document'] }), box);
+ expect(out).toBeNull();
+ expect(box.querySelector('iframe')).toBeNull();
+ await host.open(makeExt({ permissions: ['document'] }), box);
+ expect(consent).toHaveBeenCalledTimes(2);
+ });
+
+ it('remembers Allow for the same id, version and permissions', async () => {
+ const consent = vi.fn(async () => true);
+ const host = new ExtensionHost(handlers({ consent }));
+ const box = document.createElement('div');
+ const a = await host.open(makeExt({ permissions: ['document', 'network'] }), box);
+ const b = await host.open(makeExt({ permissions: ['network', 'document'] }), box);
+ expect(consent).toHaveBeenCalledTimes(1);
+ expect(box.querySelectorAll('iframe').length).toBe(2);
+ a?.dispose();
+ b?.dispose();
+ });
+
+ it('asks again for a new version or a larger permission set', async () => {
+ const consent = vi.fn(async () => true);
+ const host = new ExtensionHost(handlers({ consent }));
+ await host.ensureConsent(makeExt({ permissions: ['document'] }));
+ await host.ensureConsent(makeExt({ permissions: ['document'], version: '1.1.0' }));
+ await host.ensureConsent(makeExt({ permissions: ['document', 'network'] }));
+ expect(consent).toHaveBeenCalledTimes(3);
+ });
+
+ it('never asks for an extension that needs no permissions', async () => {
+ const consent = vi.fn(async () => false);
+ const host = new ExtensionHost(handlers({ consent }));
+ expect(await host.ensureConsent(makeExt())).toBe(true);
+ expect(consent).not.toHaveBeenCalled();
+ });
+
+ it('asks again after a grant is revoked', async () => {
+ const consent = vi.fn(async () => true);
+ const host = new ExtensionHost(handlers({ consent }));
+ const ext = makeExt({ permissions: ['files-read'] });
+ await host.ensureConsent(ext);
+ expect(host.isGranted(ext)).toBe(true);
+ host.revoke(ext);
+ expect(host.isGranted(ext)).toBe(false);
+ });
+
+ it('refuses a headless command the person did not allow with -32001 and an unknown command with -32601', async () => {
+ const host = new ExtensionHost(handlers({ consent: async () => false }));
+ const ext = makeExt({ permissions: ['document'] });
+ await expect(host.runCommand(ext, 'mark', {}, document.body)).rejects.toMatchObject({ code: -32001 });
+ await expect(host.runCommand(ext, 'nope', {}, document.body)).rejects.toMatchObject({ code: -32601 });
+ expect(document.body.querySelector('iframe')).toBeNull();
+ });
+});
diff --git a/frontend/tests/unit/shell/sdk-host.test.ts b/frontend/tests/unit/shell/sdk-host.test.ts
new file mode 100644
index 0000000..0562fb7
--- /dev/null
+++ b/frontend/tests/unit/shell/sdk-host.test.ts
@@ -0,0 +1,228 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { ExtensionHost } from '../../../../contract/host/host-bridge';
+import type { HostHandlers, Frame } from '../../../../contract/host/host-bridge';
+import { formext, FormExtError, ERR, toBase64, fromBase64, applyTheme } from '../../../../sdk/src/formext';
+import { makeExt, link, flush } from './wire';
+import type { Msg } from './wire';
+
+let handle: Frame | null = null;
+
+function handlers(over: Partial = {}): HostHandlers {
+ return {
+ product: 'formmd',
+ app: 'form.md',
+ appVersion: '1.2.3',
+ locale: () => 'fr-FR',
+ theme: () => ({ mode: 'light', tokens: { '--bg': '#eeeeee', '--accent': '#123456', color: 'red' } }),
+ notify: vi.fn(),
+ consent: async () => true,
+ ...over,
+ };
+}
+
+async function connect(h: Partial = {}, perms: ('document' | 'network' | 'files-read')[] = []) {
+ const host = new ExtensionHost(handlers(h));
+ const ext = makeExt({ permissions: perms });
+ await host.ensureConsent(ext);
+ handle = host.mount(ext, document.createElement('div'));
+ const toHost = link(handle);
+ return { host, ext, toHost };
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ document.documentElement.removeAttribute('data-theme');
+ document.documentElement.removeAttribute('style');
+});
+
+afterEach(() => {
+ handle?.dispose();
+ handle = null;
+ vi.useRealTimers();
+});
+
+describe('SDK and host agree', () => {
+ it('sends every request with the formext marker and json-rpc 2.0', async () => {
+ const { toHost } = await connect();
+ await formext.call('host.hello');
+ expect(toHost[0]).toMatchObject({ formext: 1, jsonrpc: '2.0', method: 'host.hello', params: {} });
+ expect(typeof toHost[0].id).toBe('number');
+ });
+
+ it('gets the hello the host builds and applies its theme tokens to the page', async () => {
+ await connect();
+ const hello = await formext.hello();
+ expect(hello.api).toBe('1');
+ expect(hello.app).toBe('form.md');
+ expect(hello.locale).toBe('fr-FR');
+ expect(hello.extension).toEqual({ id: 'org.example.beats', version: '1.0.0', source: 'sideload' });
+ expect(document.documentElement.dataset.theme).toBe('light');
+ expect(document.documentElement.style.getPropertyValue('--accent')).toBe('#123456');
+ expect(document.documentElement.style.getPropertyValue('color')).toBe('');
+ });
+
+ it('turns a host refusal into a FormExtError carrying the contract code', async () => {
+ await connect({ readDocument: () => ({}) }, []);
+ const err = (await formext.readDocument().catch((e) => e)) as FormExtError;
+ expect(err).toBeInstanceOf(FormExtError);
+ expect(err.code).toBe(ERR.PERMISSION);
+ expect(err.code).toBe(-32001);
+ });
+
+ it('round-trips storage through the host', async () => {
+ await connect();
+ await formext.storageSet('grid', { rows: 4, cols: [1, 2] });
+ expect(await formext.storageGet('grid')).toEqual({ rows: 4, cols: [1, 2] });
+ await formext.storageSet('grid', null);
+ expect(await formext.storageGet('grid')).toBeNull();
+ });
+
+ it('sends document.apply ops the host passes to the app unchanged', async () => {
+ const applyDocument = vi.fn(async (_e: unknown, _l: string, ops: { command: string }[]) => ({ applied: ops.length, results: ops.map((o) => o.command) }));
+ await connect({ applyDocument }, ['document']);
+ const out = await formext.apply('Add beats', [{ command: 'marker.add', args: { t: 1 } }, { command: 'marker.add', args: { t: 2 } }]);
+ expect(out).toEqual({ applied: 2, results: ['marker.add', 'marker.add'] });
+ expect(applyDocument.mock.calls[0][1]).toBe('Add beats');
+ expect(applyDocument.mock.calls[0][2]).toEqual([{ command: 'marker.add', args: { t: 1 } }, { command: 'marker.add', args: { t: 2 } }]);
+ });
+
+ it('notifies through ui.notify with the level it was given', async () => {
+ const notify = vi.fn();
+ await connect({ notify });
+ await formext.notify('Done', 'warning');
+ expect(notify).toHaveBeenCalledWith(expect.anything(), 'Done', 'warning');
+ });
+
+ it('rounds a fractional resize height up before it reaches the host', async () => {
+ const { toHost } = await connect();
+ await formext.resize(100.2);
+ expect(toHost.at(-1)).toMatchObject({ method: 'ui.resize', params: { height: 101 } });
+ });
+
+ it('delivers ext.activate to the extension handler and returns its answer to the host', async () => {
+ await connect();
+ const seen: unknown[] = [];
+ formext.onActivate((a) => {
+ seen.push(a);
+ return { opened: a.panel };
+ });
+ await formext.call('host.hello');
+ const result = await handle!.activate({ reason: 'panel', panel: 'main' });
+ expect(seen).toEqual([{ reason: 'panel', panel: 'main' }]);
+ expect(result).toEqual({ opened: 'main' });
+ });
+
+ it('reports a failing activate handler to the host with its code', async () => {
+ await connect();
+ formext.onActivate(() => {
+ throw new FormExtError(ERR.CANCELLED, 'person closed it');
+ });
+ await formext.call('host.hello');
+ await expect(handle!.activate({ reason: 'command', command: 'mark' })).rejects.toMatchObject({ code: -32002, message: 'person closed it' });
+ });
+
+ it('answers a host request it has no handler for with -32601', async () => {
+ await connect();
+ await formext.call('host.hello');
+ await expect(handle!.send('ext.unknownThing', {})).rejects.toMatchObject({ code: -32601 });
+ });
+
+ it('passes app events from broadcast to onEvent', async () => {
+ const { host } = await connect();
+ const events: unknown[] = [];
+ formext.onEvent((e) => void events.push(e));
+ await formext.call('host.hello');
+ host.broadcast('document.changed', { blocks: 3 });
+ await flush();
+ expect(events).toEqual([{ name: 'document.changed', data: { blocks: 3 } }]);
+ });
+
+ it('repaints the page when the host changes theme', async () => {
+ const { host } = await connect();
+ await formext.call('host.hello');
+ host.setTheme({ mode: 'dark', tokens: { '--bg': '#010101' } });
+ await flush();
+ expect(document.documentElement.dataset.theme).toBe('dark');
+ expect(document.documentElement.style.getPropertyValue('--bg')).toBe('#010101');
+ });
+
+ it('ends a headless command with the result the extension gives to done', async () => {
+ const host = new ExtensionHost(handlers());
+ const ext = makeExt();
+ const box = document.createElement('div');
+ const mount = host.mount.bind(host);
+ vi.spyOn(host, 'mount').mockImplementation((e, c, o) => {
+ const h = mount(e, c, o);
+ link(h);
+ void formext.call('host.hello');
+ return h;
+ });
+ formext.onActivate(async (a) => {
+ await formext.done({ marked: a.command, args: a.args });
+ return null;
+ });
+ const result = await host.runCommand(ext, 'mark', { bpm: 90 }, box);
+ expect(result).toEqual({ marked: 'mark', args: { bpm: 90 } });
+ expect(box.querySelector('iframe')).toBeNull();
+ });
+});
+
+describe('SDK on its own', () => {
+ it('gives up on a plain request after 30 s with -32003', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(window.parent, 'postMessage').mockImplementation((() => undefined) as typeof window.postMessage);
+ const p = formext.storageGet('x').catch((e) => e as FormExtError);
+ await vi.advanceTimersByTimeAsync(29_999);
+ let settled = false;
+ void p.then(() => (settled = true));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(settled).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ const err = (await p) as FormExtError;
+ expect(err.code).toBe(-32003);
+ });
+
+ it('waits 300 s for files and app.run before giving up', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(window.parent, 'postMessage').mockImplementation((() => undefined) as typeof window.postMessage);
+ const out: Record = {};
+ const track = (name: string, p: Promise) => p.catch((e) => (out[name] = e.code));
+ track('open', formext.openFiles(['.wav']));
+ track('save', formext.saveFile('a.txt', 'text/plain', ''));
+ track('run', formext.run('x'));
+ await vi.advanceTimersByTimeAsync(31_000);
+ expect(out).toEqual({});
+ await vi.advanceTimersByTimeAsync(270_000);
+ expect(out).toEqual({ open: -32003, save: -32003, run: -32003 });
+ });
+
+ it('accepts answers only from the parent window', async () => {
+ const sent: Msg[] = [];
+ vi.spyOn(window.parent, 'postMessage').mockImplementation(((m: Msg) => void sent.push(m)) as typeof window.postMessage);
+ let value: unknown = 'pending';
+ void formext.storageGet('k').then((v) => (value = v));
+ const id = sent[0].id;
+ window.dispatchEvent(new MessageEvent('message', { data: { formext: 1, jsonrpc: '2.0', id, result: 'forged' }, source: {} as Window }));
+ await flush();
+ expect(value).toBe('pending');
+ window.dispatchEvent(new MessageEvent('message', { data: { formext: 1, jsonrpc: '2.0', id, result: 'real' }, source: window.parent }));
+ await flush();
+ expect(value).toBe('real');
+ });
+
+ it('round-trips bytes through base64 and agrees with the platform encoder', () => {
+ const bytes = new Uint8Array(70_000).map((_, i) => (i * 31) % 256);
+ const b64 = toBase64(bytes);
+ expect(b64).toBe(Buffer.from(bytes).toString('base64'));
+ expect(Array.from(fromBase64(b64))).toEqual(Array.from(bytes));
+ expect(toBase64(new TextEncoder().encode('hi'))).toBe('aGk=');
+ });
+
+ it('ignores a missing theme and skips token names without the leading dashes', () => {
+ applyTheme(undefined);
+ expect(document.documentElement.dataset.theme).toBeUndefined();
+ applyTheme({ mode: 'dark', tokens: { '--panel': '#222222', panel: '#333333' } });
+ expect(document.documentElement.style.getPropertyValue('--panel')).toBe('#222222');
+ expect(document.documentElement.style.getPropertyValue('panel')).toBe('');
+ });
+});
diff --git a/frontend/tests/unit/shell/shell-boot.test.ts b/frontend/tests/unit/shell/shell-boot.test.ts
new file mode 100644
index 0000000..12a5dda
--- /dev/null
+++ b/frontend/tests/unit/shell/shell-boot.test.ts
@@ -0,0 +1,207 @@
+import { describe, it, expect, vi, beforeAll } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const here = (p: string) => fileURLToPath(new URL(p, import.meta.url));
+const page = readFileSync(here('../../../index.html'), 'utf8');
+const contractMd = readFileSync(here('../../../../contract/CONTRACT.md'), 'utf8');
+const manualMd = readFileSync(here('../../../../docs/MANUAL.md'), 'utf8');
+
+const REGISTRY = {
+ url: 'https://registry.example.org/index.json', url_source: 'default', name: 'Example', verified: true, key: 'k1', keys: 1, note: '', offline: null,
+ fetched_at: 1700000000, sha256: 'a'.repeat(64), registry_commit: 'abcdef1234567', publishers: [],
+ extensions: [
+ { id: 'org.example.tidal', name: 'Tidal Grid', product: 'formmd', version: '1.0.0', kind: 'extension', author: 'Ada', licence: 'MIT', description: 'Grid for tides', permissions: [{ id: 'document', words: 'Read and change the open document' }], verified: true, listed_verified: true, source: 'registry', registry_commit: 'abcdef1', url: 'https://registry.example.org/a.formpkg', sha256: 'b'.repeat(64), bytes: 2048, signed_by: null, imported: [] },
+ { id: 'org.example.beats', name: 'Beat Markers', product: 'formwav', version: '2.1.0', kind: 'extension', author: 'Grace', licence: 'MIT', description: 'Markers on beats', permissions: [], verified: true, listed_verified: true, source: 'registry', registry_commit: 'abcdef1', url: 'https://registry.example.org/b.formpkg', sha256: 'c'.repeat(64), bytes: 4096, signed_by: null, imported: [] },
+ ],
+};
+
+const RECENT = { projects: [{ id: 'p1', name: 'Golden Hour', product: 'formvis', version: '0.3.0', dir: '/tmp/golden-hour', linked: false, manifest: {} }] };
+
+function json(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
+}
+
+async function route(input: RequestInfo | URL): Promise {
+ const url = new URL(String(input instanceof Request ? input.url : input), 'http://localhost');
+ const p = url.pathname;
+ if (p === '/api/health') return json({ version: '7.7.7' });
+ if (p === '/api/projects/recent') return json(RECENT);
+ if (p === '/api/projects') return json([]);
+ if (p === '/api/library/registry') return json(REGISTRY);
+ return json({ detail: 'Not found' }, 404);
+}
+
+class QuietSocket {
+ static OPEN = 1;
+ readyState = 0;
+ onopen: unknown = null;
+ onclose: unknown = null;
+ onmessage: unknown = null;
+ onerror: unknown = null;
+ constructor(public url: string) {}
+ send() {}
+ close() {}
+ addEventListener() {}
+ removeEventListener() {}
+}
+
+function headings(md: string, level: number): string[] {
+ const mark = '#'.repeat(level) + ' ';
+ const out: string[] = [];
+ let fence = false;
+ for (const line of md.split('\n')) {
+ if (line.startsWith('```')) fence = !fence;
+ else if (!fence && line.startsWith(mark)) out.push(line.slice(mark.length).replace(/`/g, '').trim());
+ }
+ return out;
+}
+
+const tick = (ms = 0) => new Promise((r) => setTimeout(r, ms));
+
+async function until(check: () => boolean, tries = 40) {
+ for (let i = 0; i < tries && !check(); i++) await tick(10);
+}
+
+let shell: typeof import('../../../src/shell/shell');
+let VERSION = '';
+
+beforeAll(async () => {
+ vi.stubGlobal('fetch', vi.fn(route));
+ vi.stubGlobal('WebSocket', QuietSocket);
+ localStorage.clear();
+ history.replaceState(null, '', '/');
+ document.body.innerHTML = page.slice(page.indexOf('') + 6, page.indexOf('')).replace(/\n