diff --git a/compiler/Cargo.lock b/compiler/Cargo.lock
index 3b408292..f66bf9cc 100644
--- a/compiler/Cargo.lock
+++ b/compiler/Cargo.lock
@@ -996,6 +996,7 @@ dependencies = [
"napi-derive",
"oxc_allocator",
"oxc_ast",
+ "oxc_codegen",
"oxc_sourcemap",
"oxc_span",
"oxc_syntax",
diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml
index 8ac3e98a..93e4881d 100644
--- a/compiler/Cargo.toml
+++ b/compiler/Cargo.toml
@@ -29,6 +29,7 @@ serde_json = { version = "1", features = ["preserve_order"] }
solidjs-compiler = { git = "https://github.com/solidjs/solid", rev = "2105ffb8ca2fced55f5fac0763177fc93f97c2c2", default-features = false }
oxc_allocator = "0.144"
oxc_ast = "0.144"
+oxc_codegen = "0.144"
oxc_span = "0.144"
oxc_sourcemap = "8.1"
oxc_syntax = "0.144"
diff --git a/compiler/src/app.rs b/compiler/src/app.rs
index f014d014..f8dc8f89 100644
--- a/compiler/src/app.rs
+++ b/compiler/src/app.rs
@@ -2,7 +2,7 @@
//! compiler for `target`, each importing its dependencies by `.rx` path, with the program's stylesheet. What `rxc app`
//! prints and the Node-API build (`src/node.rs`) returns to `@reactivescript/compiler/vite`.
use crate::check::check_modules;
-use crate::emit::{compile_linked, lower_view, Target};
+use crate::emit::{compile_linked, lower_view, view_jsx, Target};
use crate::modules::load_modules;
use serde_json::{json, Map, Value};
use std::path::Path;
@@ -26,16 +26,22 @@ pub fn target(name: &str) -> Target {
/// `{entry, css, modules: {path: {code, map, css}}}` (the program's stylesheet, and each module's own), or `{diagnostics: [...]}` / `{error}`. `entry` is an absolute path.
/// `spa`: a client-only build, checked under 08 CN-3d.
pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
+ app_with(entry, target, module_name, spa, false, &read_disk)
+}
+
+/// `app` over `read` in place of the disk: the WebAssembly build's host, or an editor's open files. `jsx`: each module
+/// also carries the JSX Solid's compiler was handed (`view_jsx`).
+pub fn app_with(entry: &str, target: Target, module_name: &str, spa: bool, jsx: bool, read: &dyn Fn(&str) -> Option) -> Value {
// module keys are POSIX paths (`modules::join_path`); Windows takes `D:/a/b.rx` as it takes `D:\a\b.rx`
let entry = &entry.replace('\\', "/");
(|| {
- if read_disk(entry).is_none() {
+ if read(entry).is_none() {
return Err(json!({ "error": format!("{entry}: no such file") }));
}
- let set = load_modules(entry, &read_disk).map_err(|e| {
+ let set = load_modules(entry, read).map_err(|e| {
// a parse error is a diagnostic like the checker's, with its code (PARSE, or the habit it names)
let file = e.2.clone().unwrap_or_else(|| entry.to_string());
- let mut d = crate::serve::parse_error_in(&file, &e, read_disk(&file).as_deref());
+ let mut d = crate::serve::parse_error_in(&file, &e, read(&file).as_deref());
d["msg"] = json!(crate::serve::parse_message(&e));
json!({ "diagnostics": [d] })
})?;
@@ -47,9 +53,13 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
let mut modules = Map::new();
for (name, module) in &out.files {
let path = &out.paths[name];
- let text = read_disk(path).unwrap_or_default();
+ let text = read(path).unwrap_or_default();
let l = lower_view(module, path, target, module_name, Some((path, &text))).map_err(|e| json!({ "error": e }))?;
- modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name] }));
+ let mut m = json!({ "code": l.code, "map": l.map, "css": out.module_css[name] });
+ if jsx {
+ m["jsx"] = json!(view_jsx(module));
+ }
+ modules.insert(path.clone(), m);
}
Ok(json!({ "entry": set.entry, "css": out.css, "modules": modules }))
})()
diff --git a/compiler/src/emit.rs b/compiler/src/emit.rs
index 985f5710..93274050 100644
--- a/compiler/src/emit.rs
+++ b/compiler/src/emit.rs
@@ -1892,6 +1892,13 @@ pub struct Lowered {
pub map: Option,
}
+/// A module as the JSX Solid's compiler is handed, printed: what `lower_view` compiles, before templates.
+pub fn view_jsx(module: &[S]) -> String {
+ let alloc = oxc_allocator::Allocator::default();
+ let program = crate::oxc::Build::new(&alloc).program(module);
+ oxc_codegen::Codegen::new().build(&program).code
+}
+
/// Each module's JSX → JavaScript for `target` (`ref/compile/jsx.ts`): dom and ssr with hydration; universal over the
/// renderer `module_name`. With `rx` (the module's `.rx` path and text), the output carries a source map onto it. CP-1c:
/// Solid's positions are the program's layout; each maps to the `.rx` line it was lowered from (`oxc::Build::lines`), at
diff --git a/compiler/src/parse.rs b/compiler/src/parse.rs
index 52052e43..081d8d66 100644
--- a/compiler/src/parse.rs
+++ b/compiler/src/parse.rs
@@ -1217,11 +1217,16 @@ pub fn parse_block(c: &mut Cursor) -> R> {
c.ws(true);
let mut out = vec![];
while !c.starts_with("}") {
+ let at = c.i;
out.push(parse_stmt(c)?);
out.append(&mut c.pending);
c.ws(true);
c.eat(";");
c.ws(true);
+ // an editor's parse reads a missing statement as an empty one, so at the end of input nothing moves
+ if c.i == at {
+ break;
+ }
}
c.expect("}")?;
Ok(out)
@@ -2257,6 +2262,13 @@ mod recovering {
assert!(parse_program(src).is_err());
}
+ #[test]
+ fn an_unclosed_block_at_the_end_of_input_stops() {
+ let src = "export default component App() {\n { c";
+ let (_, errs) = parse_program_recovering(src);
+ assert!(!errs.is_empty());
+ }
+
#[test]
fn function_types_in_props_and_type_aliases() {
let src = "type Pick = (id: number) => void\ncomponent Row(props: { id: number; onPick: (id: number) => void; onDrop: Pick }) {\n source n: number := peek(props.id)\n { props.onPick(n) }}>{n} \n}\nfn twice(x: number): number => x * 2\nexport default component App() {\n { log(id) }} onDrop={id => { log(id) }} />\n}\n";
diff --git a/compiler/src/serve.rs b/compiler/src/serve.rs
index 78035689..5c5519bf 100644
--- a/compiler/src/serve.rs
+++ b/compiler/src/serve.rs
@@ -3,11 +3,12 @@
use serde_json::{json, Value};
use std::collections::HashMap;
-/// One request: `analyze` (`{file, overlays, prelude}`) or `prelude`.
+/// One request: `analyze` (`{file, overlays, prelude, project}`), `app` (`{entry, overlays, target, moduleName, spa, jsx}`) or `prelude`.
pub fn request(method: &str, params: &Value, disk: &dyn Fn(&str) -> Option) -> Value {
match method {
"analyze" => analyze(params, disk),
"prelude" => json!(crate::project::PRELUDE),
+ "app" => app(params, disk),
_ => json!({ "error": "unknown method" }),
}
}
@@ -60,12 +61,17 @@ pub fn utf16_index(s: &str) -> Vec {
idx
}
+/// A request's `overlays`: the editor's open files, read before the disk.
+fn overlays(params: &Value) -> HashMap {
+ params["overlays"].as_object().map(|o| o.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default()
+}
+
/// `rxc serve`, one request: `{file, overlays: {path: text}, prelude}` — the file loaded (and its imports) as an editor
/// has them, recovering (CP-8e); its projection with mappings in UTF-16 offsets, and its diagnostics: the parse's, else
/// the checker's.
pub fn analyze(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value {
let file = params["file"].as_str().unwrap_or_default().to_string();
- let overlays: HashMap = params["overlays"].as_object().map(|o| o.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default();
+ let overlays = overlays(params);
let read = |p: &str| overlays.get(p).cloned().or_else(|| disk(p));
let set = match crate::modules::load_modules_recovering(&file, &read) {
Ok(s) => s,
@@ -77,7 +83,9 @@ pub fn analyze(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value {
let src = set.sources.get(&file).cloned().unwrap_or_default();
let prelude = params["prelude"].as_str();
let mut out = json!({ "code": null, "mappings": [] });
- if let Some(p) = crate::project::project_modules_with(&set, prelude).into_iter().find(|p| p.rx == file) {
+ // `project: false`: diagnostics only, for a caller that does not show the TSX projection
+ let project = params["project"].as_bool().unwrap_or(true);
+ if let Some(p) = project.then(|| crate::project::project_modules_with(&set, prelude).into_iter().find(|p| p.rx == file)).flatten() {
let (gi, si) = (utf16_index(&p.code), utf16_index(&src));
let maps: Vec<[u32; 3]> = p.mappings.iter().map(|m| [gi[m.gen as usize], si[m.src as usize], si[(m.src + m.len) as usize] - si[m.src as usize]]).collect();
let u = |i: &[u32], a: u32, n: u32| [i[a as usize], i[(a + n) as usize] - i[a as usize]];
@@ -93,3 +101,12 @@ pub fn analyze(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value {
out
}
+
+/// `rxc app` over the editor's files: what `app.rs` returns for `entry`, reading `overlays` before the disk.
+pub fn app(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value {
+ let overlays = overlays(params);
+ let read = |p: &str| overlays.get(p).cloned().or_else(|| disk(p));
+ let target = crate::app::target(params["target"].as_str().unwrap_or("dom"));
+ let module_name = params["moduleName"].as_str().unwrap_or("@solidjs/web");
+ crate::app::app_with(params["entry"].as_str().unwrap_or_default(), target, module_name, params["spa"].as_bool().unwrap_or(false), params["jsx"].as_bool().unwrap_or(false), &read)
+}
diff --git a/site/.assetsignore b/site/.assetsignore
index 328f4a40..bcfd63c3 100644
--- a/site/.assetsignore
+++ b/site/.assetsignore
@@ -1,3 +1,4 @@
wrangler.toml
.assetsignore
.wrangler
+playground/
diff --git a/site/playground/.gitignore b/site/playground/.gitignore
new file mode 100644
index 00000000..fae9c091
--- /dev/null
+++ b/site/playground/.gitignore
@@ -0,0 +1,4 @@
+node_modules
+dist
+test-results
+public/rxc.wasm
diff --git a/site/playground/README.md b/site/playground/README.md
new file mode 100644
index 00000000..9cccf499
--- /dev/null
+++ b/site/playground/README.md
@@ -0,0 +1,68 @@
+# ReactiveScript Playground
+
+
+
+Type `.rx` on the left and see it as Solid 2.0 on the right: the program written with Solid's own primitives
+(`createSignal`, `createMemo`, `createOptimistic`, `action`, ``, ``) and the checker's diagnostics
+(each linked to `guide/diagnostics.md#`). The program is kept in the URL hash, so a link reopens it, the Solid → .rx side included.
+
+The Solid view is the JSX the crate hands to Solid's compiler, with each `__rt` helper that is a Solid primitive
+underneath written as that primitive and the mangled names (`v$id`, `w$id`) made plain (`src/solidify.ts`), then
+formatted with Prettier. It is a reading aid, not the code that runs.
+
+## How it compiles in the browser
+
+`public/rxc.wasm` is the crate (`compiler/` in this repository) built for `wasm32-unknown-unknown`, the same build the
+language server loads (`compiler/src/wasm.rs`: `rx_alloc`, `rx_call`, `rx_free`, and a host `env.rx_read`). The page
+answers `rx_read` from the editor's files in memory, so there is no server and no filesystem. Each keystroke sends
+`analyze` (diagnostics) for every `.rx` file and `app` with `jsx: true` for `main.rx`.
+
+The `app` request is new: `app::app_with` takes a reader in place of the disk, `serve.rs` routes `app` to it, and with
+`jsx: true` each module also carries the JSX printed before Solid's compiler runs (`emit::view_jsx`, over
+`oxc_codegen`). `pnpm wasm` rebuilds `../../compiler` and copies the result into `public/` (it is not checked in).
+
+The playground is not part of the deployed site: `site/.assetsignore` leaves `playground/` out of the static upload.
+Publishing it would need a build step (`pnpm wasm && pnpm build`) and its `dist/` served under `/playground/`.
+
+## Solid → .rx (prototype)
+
+The header's **Solid → .rx** button turns the page around: Solid 2.0 on the left, the same program as `.rx` on the
+right (`src/torx.ts`). It parses the Solid with the Babel parser Prettier already carries, reads the forms the Solid
+view produces (signals, memos, stores, keyed and draft projections, actions with guesses, `Show`, `For`, `Errored`,
+`Loading`, prop patterns), and lists everything else under "Not converted" with its line instead of guessing.
+Plain TypeScript beside a component (data, `async` functions, anything with statements) moves to `helpers.ts`, which
+the `.rx` imports; a call to one of its `async` functions from reactive scope is written as an `await`. The
+compiler then checks the `.rx`, so a Solid program with, say, an await and no `Errored` boundary gets
+`UNHANDLED_FAILURE`.
+
+The same button turns the page back. Each way round, the left side gets what the right side showed: the Solid view
+going in, and the `.rx` (with its `helpers.ts`) coming back, unless the reading left something out, in which case
+the editor keeps the program it had.
+
+`pnpm test:torx` is the round trip: each example's `.rx` → Solid view → `.rx` → Solid view must give the same view,
+plus hand-written Solid that must convert and compile, or be refused with reasons.
+
+## Types on hover, and completion
+
+Both editors answer two questions from TypeScript's language service, which runs in a Web Worker
+(`src/types.worker.ts`) that loads on the first hover or completion (7.9 MB, 1.7 MB gzipped, with TypeScript, its
+DOM and ES libraries, and Solid's types).
+
+For `.rx`, the worker reads what the editor extension reads: the crate's TSX projection of each module and its
+mappings onto the `.rx` (`analyze`, spec/13 TY-1c). `src/hover.ts` takes the offset under the pointer or at the caret
+through those mappings, so `id` reads `source id: number`, an attribute shows its documentation, and `user.` offers
+the store's fields. A `.d.rx`'s functions are declared from their written parameters. Names every JavaScript module
+has are left out, because `.rx` has none.
+
+In the Solid → .rx pane the worker reads the Solid source as it is. Every `solid-js` export is offered where a name
+can stand, and picking one that is not imported adds it to the import.
+
+## Run
+
+```sh
+. ~/.local/share/solid-toolchain/env.sh
+corepack pnpm@11.9.0 install
+corepack pnpm@11.9.0 wasm # needs Rust with the wasm32-unknown-unknown target
+corepack pnpm@11.9.0 dev # vite --host on port 3020
+corepack pnpm@11.9.0 test # Playwright against the running dev server
+```
diff --git a/site/playground/docs/screenshot.png b/site/playground/docs/screenshot.png
new file mode 100644
index 00000000..850d144c
Binary files /dev/null and b/site/playground/docs/screenshot.png differ
diff --git a/site/playground/index.html b/site/playground/index.html
new file mode 100644
index 00000000..c78ad389
--- /dev/null
+++ b/site/playground/index.html
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+ ReactiveScript Playground
+
+
+
+
+
+
+
diff --git a/site/playground/package.json b/site/playground/package.json
new file mode 100644
index 00000000..b98f0ef8
--- /dev/null
+++ b/site/playground/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "reactivescript-playground",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "vite --host --port 3020",
+ "build": "vite build",
+ "preview": "vite preview --host --port 3020",
+ "wasm": "sh scripts/build-wasm.sh",
+ "test": "node tests/playground.check.mjs",
+ "test:torx": "node tests/torx.check.mts",
+ "test:roundtrip": "node tests/roundtrip.check.mts"
+ },
+ "dependencies": {
+ "@solidjs/web": "2.0.3",
+ "highlight.js": "^11.11.1",
+ "prettier": "^3.10.1",
+ "solid-js": "2.0.3"
+ },
+ "devDependencies": {
+ "@solidjs/signals": "2.0.3",
+ "@solidjs/vite-plugin": "3.0.1",
+ "csstype": "3.2.3",
+ "playwright-core": "^1.56.0",
+ "typescript": "^5.9.3",
+ "vite": "^8.3.8"
+ }
+}
diff --git a/site/playground/pnpm-lock.yaml b/site/playground/pnpm-lock.yaml
new file mode 100644
index 00000000..3017ee2e
--- /dev/null
+++ b/site/playground/pnpm-lock.yaml
@@ -0,0 +1,816 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ dependencies:
+ '@solidjs/web':
+ specifier: 2.0.3
+ version: 2.0.3(solid-js@2.0.3)
+ highlight.js:
+ specifier: ^11.11.1
+ version: 11.12.0
+ prettier:
+ specifier: ^3.10.1
+ version: 3.10.1
+ solid-js:
+ specifier: 2.0.3
+ version: 2.0.3
+ devDependencies:
+ '@solidjs/signals':
+ specifier: 2.0.3
+ version: 2.0.3
+ '@solidjs/vite-plugin':
+ specifier: 3.0.1
+ version: 3.0.1(@solidjs/web@2.0.3(solid-js@2.0.3))(solid-js@2.0.3)(vite@8.3.8)
+ csstype:
+ specifier: 3.2.3
+ version: 3.2.3
+ playwright-core:
+ specifier: ^1.56.0
+ version: 1.65.0
+ typescript:
+ specifier: ^5.9.3
+ version: 5.9.3
+ vite:
+ specifier: ^8.3.8
+ version: 8.3.8
+
+packages:
+
+ '@ampproject/remapping@2.3.0':
+ resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}
+ engines: {node: '>=6.0.0'}
+
+ '@emnapi/core@1.11.3':
+ resolution: {integrity: sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==}
+
+ '@emnapi/core@2.0.0-beta.2':
+ resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==}
+
+ '@emnapi/runtime@1.11.3':
+ resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
+
+ '@emnapi/runtime@2.0.0-beta.2':
+ resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==}
+
+ '@emnapi/wasi-threads@1.2.3':
+ resolution: {integrity: sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==}
+
+ '@emnapi/wasi-threads@2.2.0':
+ resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==}
+
+ '@jridgewell/gen-mapping@0.3.13':
+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
+
+ '@jridgewell/resolve-uri@3.1.2':
+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
+ engines: {node: '>=6.0.0'}
+
+ '@jridgewell/sourcemap-codec@1.6.0':
+ resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
+
+ '@jridgewell/trace-mapping@0.3.31':
+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+
+ '@napi-rs/wasm-runtime@1.2.6':
+ resolution: {integrity: sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
+ peerDependencies:
+ '@emnapi/core': ^1.7.1 || 2.0.0-beta.2
+ '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2
+
+ '@napi-rs/wasm-runtime@1.2.7':
+ resolution: {integrity: sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
+ peerDependencies:
+ '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3
+ '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3
+
+ '@oxc-project/types@0.156.0':
+ resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
+
+ '@rolldown/binding-android-arm-eabi@1.2.19':
+ resolution: {integrity: sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [android]
+
+ '@rolldown/binding-android-arm64@1.2.19':
+ resolution: {integrity: sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [android]
+
+ '@rolldown/binding-darwin-arm64@1.2.19':
+ resolution: {integrity: sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rolldown/binding-darwin-x64@1.2.19':
+ resolution: {integrity: sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rolldown/binding-freebsd-x64@1.2.19':
+ resolution: {integrity: sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rolldown/binding-linux-arm-gnueabihf@1.2.19':
+ resolution: {integrity: sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [linux]
+
+ '@rolldown/binding-linux-arm64-gnu@1.2.19':
+ resolution: {integrity: sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-arm64-musl@1.2.19':
+ resolution: {integrity: sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/binding-linux-ppc64-gnu@1.2.19':
+ resolution: {integrity: sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-s390x-gnu@1.2.19':
+ resolution: {integrity: sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-x64-gnu@1.2.19':
+ resolution: {integrity: sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-x64-musl@1.2.19':
+ resolution: {integrity: sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/binding-openharmony-arm64@1.2.19':
+ resolution: {integrity: sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rolldown/binding-wasm32-wasi@1.2.19':
+ resolution: {integrity: sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
+ cpu: [wasm32]
+
+ '@rolldown/binding-win32-arm64-msvc@1.2.19':
+ resolution: {integrity: sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rolldown/binding-win32-x64-msvc@1.2.19':
+ resolution: {integrity: sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [win32]
+
+ '@rolldown/pluginutils@1.1.0':
+ resolution: {integrity: sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==}
+
+ '@solidjs/compiler-darwin-arm64@2.0.2':
+ resolution: {integrity: sha512-ctgEtzj0R5JDUiyo1wNcSgAyjO2XqNXvyPx6UolK1WK6qStR5KIHz3uIIG68aKrFhnOLTUiwS3hjd4yZWolBpA==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@solidjs/compiler-darwin-x64@2.0.2':
+ resolution: {integrity: sha512-iTcLdvzEFF3jfDwnmdpax4q1eVd6Jth0u59BzA++p345feNXFSJvzS/bGE5UrGMe9NsLFFV1IEHkZyEpbSOovw==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@solidjs/compiler-linux-arm64-gnu@2.0.2':
+ resolution: {integrity: sha512-DBdg24ud/Eu/+Ns9jgwy0AmyyExhoXn5R14VBkGX9w5lxiI3k/eG21im+hsUkqdwt/Ej0CazauifTdGaEceUzw==}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@solidjs/compiler-linux-x64-gnu@2.0.2':
+ resolution: {integrity: sha512-tRbkqVgJH7rOghIFe9j3MRvosx8ueNsGIDAd+XIUQbexhbM7KMCOJnWLmL7J/9PMPmbk34zJYz0fwwFSBp8ULQ==}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@solidjs/compiler-wasm32-wasi@2.0.2':
+ resolution: {integrity: sha512-wh69K4+T5Krrts/sipnYQtks0II2ZZyuPSadT7v1O3prcA96E3IiKA4Kr5+K54nsRSYv1GsW3NWTyt/Zje0l0Q==}
+ engines: {node: '>=14.0.0'}
+
+ '@solidjs/compiler-win32-x64-msvc@2.0.2':
+ resolution: {integrity: sha512-5q6RRWRI9y685wzBcteezVifcVz/di9hCEKqruZrBo60qbne13Orl6FOwP8LK4Exls+Ws98UNvznFuz0NhLQTg==}
+ cpu: [x64]
+ os: [win32]
+
+ '@solidjs/compiler@2.0.2':
+ resolution: {integrity: sha512-z7ZlbBQaCeNt4wt12xLS86pdgwet2QwAjyB/+enhDkPL2LUF4jWt7Q8NIlLkXVxm6RJWvZRL5hwcVmrH6JZhZA==}
+
+ '@solidjs/signals@2.0.3':
+ resolution: {integrity: sha512-M6+kiJflqSvJRHRcmdsdIXpPLPkQrY817zWKKfxZ3z3ZRE5eEtddtWPrDXY4IM1Wz3zAqG+3Fx/HQIkAtpRwnA==}
+ engines: {node: '>=22.12.0'}
+
+ '@solidjs/vite-plugin@3.0.1':
+ resolution: {integrity: sha512-dyRU4LJXhzEEgtF32AtUdjqaUuMVYTVLQvhYlT6HcYBvf10yIVmKgW9cg42b5YDxkl6BgAJ9o0OjUnAy3qKb9A==}
+ engines: {node: '>=22.12.0'}
+ peerDependencies:
+ '@babel/core': ^7.23.3 || ^8.0.0
+ '@solidjs/babel-plugin': ^2.0.0
+ '@solidjs/start-devtools': ^1.0.0-next.2
+ '@solidjs/web': ^2.0.0
+ '@testing-library/jest-dom': ^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0
+ solid-js: ^2.0.0
+ vite: ^8.0.0 || ^9.0.0
+ peerDependenciesMeta:
+ '@babel/core':
+ optional: true
+ '@solidjs/babel-plugin':
+ optional: true
+ '@solidjs/start-devtools':
+ optional: true
+ '@testing-library/jest-dom':
+ optional: true
+
+ '@solidjs/web@2.0.3':
+ resolution: {integrity: sha512-XYl9JGOtQ8yJSZRnd6uC+5gYXsYvnIRNxhn89m+F1v6D4d4ZFdTJY2Lq/8XJ3YcjckkCrK/mNfd3kIiqqgnG7w==}
+ engines: {node: '>=22.12.0'}
+ peerDependencies:
+ solid-js: ^2.0.3
+
+ '@tybys/wasm-util@0.10.4':
+ resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==}
+
+ csstype@3.2.3:
+ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+
+ detect-libc@2.1.2:
+ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
+ engines: {node: '>=8'}
+
+ fdir@6.5.0:
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ fsevents@2.3.3:
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
+ highlight.js@11.12.0:
+ resolution: {integrity: sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==}
+ engines: {node: '>=12.0.0'}
+
+ is-what@4.1.16:
+ resolution: {integrity: sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==}
+ engines: {node: '>=12.13'}
+
+ lightningcss-android-arm64@1.33.0:
+ resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
+
+ lightningcss-darwin-arm64@1.33.0:
+ resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ lightningcss-darwin-x64@1.33.0:
+ resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ lightningcss-freebsd-x64@1.33.0:
+ resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
+
+ lightningcss-linux-arm-gnueabihf@1.33.0:
+ resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
+
+ lightningcss-linux-arm64-gnu@1.33.0:
+ resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ lightningcss-linux-arm64-musl@1.33.0:
+ resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ lightningcss-linux-x64-gnu@1.33.0:
+ resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ lightningcss-linux-x64-musl@1.33.0:
+ resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ lightningcss-win32-arm64-msvc@1.33.0:
+ resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ lightningcss-win32-x64-msvc@1.33.0:
+ resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
+
+ lightningcss@1.33.0:
+ resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
+ engines: {node: '>= 12.0.0'}
+
+ magic-string@0.30.21:
+ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+
+ merge-anything@5.1.7:
+ resolution: {integrity: sha512-eRtbOb1N5iyH0tkQDAoQ4Ipsp/5qSR79Dzrz8hEPxRX10RWWR/iQXdoKmBSRCThY1Fh5EhISDtpSc93fpxUniQ==}
+ engines: {node: '>=12.13'}
+
+ nanoid@3.3.20:
+ resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
+ picocolors@1.1.1:
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
+ picomatch@4.0.7:
+ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
+ engines: {node: '>=12'}
+
+ playwright-core@1.65.0:
+ resolution: {integrity: sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==}
+ engines: {node: '>=20'}
+ hasBin: true
+
+ postcss@8.5.32:
+ resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
+ engines: {node: ^10 || ^12 || >=14}
+
+ prettier@3.10.1:
+ resolution: {integrity: sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg==}
+ engines: {node: '>=14'}
+ hasBin: true
+
+ rolldown@1.2.19:
+ resolution: {integrity: sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+
+ seroval-plugins@1.8.0:
+ resolution: {integrity: sha512-96vBb12rDvPPwdKUgWw1op3fGq8AVBFOr0IllbnM72yR5J9WWXF18cQ4g1XfDO7HCyh2dt70P3XdtyRayP8FWg==}
+ engines: {node: '>=20'}
+ peerDependencies:
+ seroval: ^1.8.0
+
+ seroval@1.8.2:
+ resolution: {integrity: sha512-zmMxi/9MdLK1MKazLmIP6Rk39RuK0Xydd+QHeOYntS37olJeTjB3+nwVj4ce/ZWiZJeRhcO5htfxt0mUzQBscQ==}
+ engines: {node: '>=20'}
+
+ solid-js@2.0.3:
+ resolution: {integrity: sha512-XOHstv+GAJjfcSGZU9xfX5q6Mbqmv72IcdWh2JuMx3KvBbfpQPdy/Yl00A1ouk7A0etjqhNe799CPdr6i7koWg==}
+ engines: {node: '>=22.12.0'}
+
+ source-map-js@1.2.2:
+ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
+ engines: {node: '>=0.10.0'}
+
+ tinyglobby@0.2.17:
+ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
+ engines: {node: '>=12.0.0'}
+
+ tslib@2.9.1:
+ resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==}
+
+ typescript@5.9.3:
+ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ vite@8.3.8:
+ resolution: {integrity: sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^20.19.0 || >=22.12.0
+ '@vitejs/devtools': ^0.7.1 || ^0.8.0
+ esbuild: ^0.27.0 || ^0.28.0
+ jiti: '>=1.21.0'
+ less: ^4.0.0
+ sass: ^1.70.0
+ sass-embedded: ^1.70.0
+ stylus: '>=0.54.8'
+ sugarss: ^5.0.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ '@vitejs/devtools':
+ optional: true
+ esbuild:
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ vitefu@1.1.3:
+ resolution: {integrity: sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==}
+ peerDependencies:
+ vite: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
+ peerDependenciesMeta:
+ vite:
+ optional: true
+
+snapshots:
+
+ '@ampproject/remapping@2.3.0':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@emnapi/core@1.11.3':
+ dependencies:
+ '@emnapi/wasi-threads': 1.2.3
+ tslib: 2.9.1
+ optional: true
+
+ '@emnapi/core@2.0.0-beta.2':
+ dependencies:
+ '@emnapi/wasi-threads': 2.2.0
+ tslib: 2.9.1
+ optional: true
+
+ '@emnapi/runtime@1.11.3':
+ dependencies:
+ tslib: 2.9.1
+ optional: true
+
+ '@emnapi/runtime@2.0.0-beta.2':
+ dependencies:
+ tslib: 2.9.1
+ optional: true
+
+ '@emnapi/wasi-threads@1.2.3':
+ dependencies:
+ tslib: 2.9.1
+ optional: true
+
+ '@emnapi/wasi-threads@2.2.0':
+ dependencies:
+ tslib: 2.9.1
+ optional: true
+
+ '@jridgewell/gen-mapping@0.3.13':
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.6.0
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@jridgewell/resolve-uri@3.1.2': {}
+
+ '@jridgewell/sourcemap-codec@1.6.0': {}
+
+ '@jridgewell/trace-mapping@0.3.31':
+ dependencies:
+ '@jridgewell/resolve-uri': 3.1.2
+ '@jridgewell/sourcemap-codec': 1.6.0
+
+ '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)':
+ dependencies:
+ '@emnapi/core': 2.0.0-beta.2
+ '@emnapi/runtime': 2.0.0-beta.2
+ '@tybys/wasm-util': 0.10.4
+ optional: true
+
+ '@napi-rs/wasm-runtime@1.2.7(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)':
+ dependencies:
+ '@emnapi/core': 1.11.3
+ '@emnapi/runtime': 1.11.3
+ '@tybys/wasm-util': 0.10.4
+ optional: true
+
+ '@oxc-project/types@0.156.0': {}
+
+ '@rolldown/binding-android-arm-eabi@1.2.19':
+ optional: true
+
+ '@rolldown/binding-android-arm64@1.2.19':
+ optional: true
+
+ '@rolldown/binding-darwin-arm64@1.2.19':
+ optional: true
+
+ '@rolldown/binding-darwin-x64@1.2.19':
+ optional: true
+
+ '@rolldown/binding-freebsd-x64@1.2.19':
+ optional: true
+
+ '@rolldown/binding-linux-arm-gnueabihf@1.2.19':
+ optional: true
+
+ '@rolldown/binding-linux-arm64-gnu@1.2.19':
+ optional: true
+
+ '@rolldown/binding-linux-arm64-musl@1.2.19':
+ optional: true
+
+ '@rolldown/binding-linux-ppc64-gnu@1.2.19':
+ optional: true
+
+ '@rolldown/binding-linux-s390x-gnu@1.2.19':
+ optional: true
+
+ '@rolldown/binding-linux-x64-gnu@1.2.19':
+ optional: true
+
+ '@rolldown/binding-linux-x64-musl@1.2.19':
+ optional: true
+
+ '@rolldown/binding-openharmony-arm64@1.2.19':
+ optional: true
+
+ '@rolldown/binding-wasm32-wasi@1.2.19':
+ dependencies:
+ '@emnapi/core': 2.0.0-beta.2
+ '@emnapi/runtime': 2.0.0-beta.2
+ '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)
+ optional: true
+
+ '@rolldown/binding-win32-arm64-msvc@1.2.19':
+ optional: true
+
+ '@rolldown/binding-win32-x64-msvc@1.2.19':
+ optional: true
+
+ '@rolldown/pluginutils@1.1.0': {}
+
+ '@solidjs/compiler-darwin-arm64@2.0.2':
+ optional: true
+
+ '@solidjs/compiler-darwin-x64@2.0.2':
+ optional: true
+
+ '@solidjs/compiler-linux-arm64-gnu@2.0.2':
+ optional: true
+
+ '@solidjs/compiler-linux-x64-gnu@2.0.2':
+ optional: true
+
+ '@solidjs/compiler-wasm32-wasi@2.0.2':
+ dependencies:
+ '@emnapi/core': 1.11.3
+ '@emnapi/runtime': 1.11.3
+ '@napi-rs/wasm-runtime': 1.2.7(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)
+ optional: true
+
+ '@solidjs/compiler-win32-x64-msvc@2.0.2':
+ optional: true
+
+ '@solidjs/compiler@2.0.2':
+ optionalDependencies:
+ '@solidjs/compiler-darwin-arm64': 2.0.2
+ '@solidjs/compiler-darwin-x64': 2.0.2
+ '@solidjs/compiler-linux-arm64-gnu': 2.0.2
+ '@solidjs/compiler-linux-x64-gnu': 2.0.2
+ '@solidjs/compiler-wasm32-wasi': 2.0.2
+ '@solidjs/compiler-win32-x64-msvc': 2.0.2
+
+ '@solidjs/signals@2.0.3': {}
+
+ '@solidjs/vite-plugin@3.0.1(@solidjs/web@2.0.3(solid-js@2.0.3))(solid-js@2.0.3)(vite@8.3.8)':
+ dependencies:
+ '@ampproject/remapping': 2.3.0
+ '@solidjs/compiler': 2.0.2
+ '@solidjs/web': 2.0.3(solid-js@2.0.3)
+ magic-string: 0.30.21
+ merge-anything: 5.1.7
+ solid-js: 2.0.3
+ vite: 8.3.8
+ vitefu: 1.1.3(vite@8.3.8)
+
+ '@solidjs/web@2.0.3(solid-js@2.0.3)':
+ dependencies:
+ csstype: 3.2.3
+ seroval: 1.8.2
+ seroval-plugins: 1.8.0(seroval@1.8.2)
+ solid-js: 2.0.3
+
+ '@tybys/wasm-util@0.10.4':
+ dependencies:
+ tslib: 2.9.1
+ optional: true
+
+ csstype@3.2.3: {}
+
+ detect-libc@2.1.2: {}
+
+ fdir@6.5.0(picomatch@4.0.7):
+ optionalDependencies:
+ picomatch: 4.0.7
+
+ fsevents@2.3.3:
+ optional: true
+
+ highlight.js@11.12.0: {}
+
+ is-what@4.1.16: {}
+
+ lightningcss-android-arm64@1.33.0:
+ optional: true
+
+ lightningcss-darwin-arm64@1.33.0:
+ optional: true
+
+ lightningcss-darwin-x64@1.33.0:
+ optional: true
+
+ lightningcss-freebsd-x64@1.33.0:
+ optional: true
+
+ lightningcss-linux-arm-gnueabihf@1.33.0:
+ optional: true
+
+ lightningcss-linux-arm64-gnu@1.33.0:
+ optional: true
+
+ lightningcss-linux-arm64-musl@1.33.0:
+ optional: true
+
+ lightningcss-linux-x64-gnu@1.33.0:
+ optional: true
+
+ lightningcss-linux-x64-musl@1.33.0:
+ optional: true
+
+ lightningcss-win32-arm64-msvc@1.33.0:
+ optional: true
+
+ lightningcss-win32-x64-msvc@1.33.0:
+ optional: true
+
+ lightningcss@1.33.0:
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ lightningcss-android-arm64: 1.33.0
+ lightningcss-darwin-arm64: 1.33.0
+ lightningcss-darwin-x64: 1.33.0
+ lightningcss-freebsd-x64: 1.33.0
+ lightningcss-linux-arm-gnueabihf: 1.33.0
+ lightningcss-linux-arm64-gnu: 1.33.0
+ lightningcss-linux-arm64-musl: 1.33.0
+ lightningcss-linux-x64-gnu: 1.33.0
+ lightningcss-linux-x64-musl: 1.33.0
+ lightningcss-win32-arm64-msvc: 1.33.0
+ lightningcss-win32-x64-msvc: 1.33.0
+
+ magic-string@0.30.21:
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.6.0
+
+ merge-anything@5.1.7:
+ dependencies:
+ is-what: 4.1.16
+
+ nanoid@3.3.20: {}
+
+ picocolors@1.1.1: {}
+
+ picomatch@4.0.7: {}
+
+ playwright-core@1.65.0: {}
+
+ postcss@8.5.32:
+ dependencies:
+ nanoid: 3.3.20
+ picocolors: 1.1.1
+ source-map-js: 1.2.2
+
+ prettier@3.10.1: {}
+
+ rolldown@1.2.19:
+ dependencies:
+ '@oxc-project/types': 0.156.0
+ '@rolldown/pluginutils': 1.1.0
+ optionalDependencies:
+ '@rolldown/binding-android-arm-eabi': 1.2.19
+ '@rolldown/binding-android-arm64': 1.2.19
+ '@rolldown/binding-darwin-arm64': 1.2.19
+ '@rolldown/binding-darwin-x64': 1.2.19
+ '@rolldown/binding-freebsd-x64': 1.2.19
+ '@rolldown/binding-linux-arm-gnueabihf': 1.2.19
+ '@rolldown/binding-linux-arm64-gnu': 1.2.19
+ '@rolldown/binding-linux-arm64-musl': 1.2.19
+ '@rolldown/binding-linux-ppc64-gnu': 1.2.19
+ '@rolldown/binding-linux-s390x-gnu': 1.2.19
+ '@rolldown/binding-linux-x64-gnu': 1.2.19
+ '@rolldown/binding-linux-x64-musl': 1.2.19
+ '@rolldown/binding-openharmony-arm64': 1.2.19
+ '@rolldown/binding-wasm32-wasi': 1.2.19
+ '@rolldown/binding-win32-arm64-msvc': 1.2.19
+ '@rolldown/binding-win32-x64-msvc': 1.2.19
+
+ seroval-plugins@1.8.0(seroval@1.8.2):
+ dependencies:
+ seroval: 1.8.2
+
+ seroval@1.8.2: {}
+
+ solid-js@2.0.3:
+ dependencies:
+ '@solidjs/signals': 2.0.3
+ seroval: 1.8.2
+ seroval-plugins: 1.8.0(seroval@1.8.2)
+
+ source-map-js@1.2.2: {}
+
+ tinyglobby@0.2.17:
+ dependencies:
+ fdir: 6.5.0(picomatch@4.0.7)
+ picomatch: 4.0.7
+
+ tslib@2.9.1:
+ optional: true
+
+ typescript@5.9.3: {}
+
+ vite@8.3.8:
+ dependencies:
+ lightningcss: 1.33.0
+ picomatch: 4.0.7
+ postcss: 8.5.32
+ rolldown: 1.2.19
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ fsevents: 2.3.3
+
+ vitefu@1.1.3(vite@8.3.8):
+ optionalDependencies:
+ vite: 8.3.8
diff --git a/site/playground/pnpm-workspace.yaml b/site/playground/pnpm-workspace.yaml
new file mode 100644
index 00000000..2437fcb9
--- /dev/null
+++ b/site/playground/pnpm-workspace.yaml
@@ -0,0 +1,15 @@
+# pnpm settings for this project (honored even for a single-package project —
+# this file marks the workspace root). The Solid packages release in lockstep
+# and templates track them closely; exclude the whole family from any
+# minimumReleaseAge policy so fresh Solid releases install immediately.
+#
+# NOTE: this exclusion is a temporary measure for the Solid 2.0 prerelease
+# cycle (frequent lockstep releases where new floors would otherwise fail
+# under an age policy). It should be removed once Solid 2.0 is stable —
+# at that point a caret range nearly always contains an age-satisfying
+# release and the policy can protect these packages like any other.
+minimumReleaseAgeExclude:
+ - solid-js
+ - '@solidjs/*'
+ # ReactiveScript 0.x releases follow the Solid RCs the same way.
+ - '@reactivescript/*'
diff --git a/site/playground/public/logo.svg b/site/playground/public/logo.svg
new file mode 100644
index 00000000..9c1c3f69
--- /dev/null
+++ b/site/playground/public/logo.svg
@@ -0,0 +1,8 @@
+
+ ReactiveScript
+
+
+
+
+
+
diff --git a/site/playground/scripts/build-wasm.sh b/site/playground/scripts/build-wasm.sh
new file mode 100644
index 00000000..6ad82ce8
--- /dev/null
+++ b/site/playground/scripts/build-wasm.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Builds the crate's WebAssembly library (serve.rs requests, with the `app` method) into public/rxc.wasm.
+set -e
+HERE="$(cd "$(dirname "$0")/.." && pwd)"
+CRATE="${RX_CRATE:-$HERE/../../compiler}"
+export CARGO_HOME="${CARGO_HOME:-$HOME/.local/share/cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.local/share/rustup}"
+export PATH="$CARGO_HOME/bin:$PATH"
+cargo build --lib --release --config 'profile.release.strip=true' --target wasm32-unknown-unknown --manifest-path "$CRATE/Cargo.toml"
+cp "$CRATE/target/wasm32-unknown-unknown/release/reactivescript.wasm" "$HERE/public/rxc.wasm"
+ls -la "$HERE/public/rxc.wasm"
diff --git a/site/playground/src/compile.ts b/site/playground/src/compile.ts
new file mode 100644
index 00000000..a9caf6f6
--- /dev/null
+++ b/site/playground/src/compile.ts
@@ -0,0 +1,98 @@
+import { loadRxc, type Files } from "./rxc";
+
+export type Target = "dom" | "ssr" | "universal";
+
+export type Diagnostic = {
+ file: string;
+ line?: number;
+ code: string;
+ rule: string;
+ message: string;
+ range?: { start: { line: number; column: number }; end: { line: number; column: number } };
+};
+
+export type AppOut = {
+ entry?: string;
+ css?: string;
+ modules?: Record;
+ diagnostics?: Diagnostic[];
+ error?: string;
+};
+
+export type Result = {
+ diagnostics: Diagnostic[];
+ app: AppOut;
+ ms: number;
+};
+
+export const ENTRY = "/main.rx";
+
+// kept across hot updates, so an edited module does not drop the loaded compiler
+let call: ReturnType | undefined = import.meta.hot?.data.call;
+
+async function fetchModule(): Promise {
+ const res = await fetch(`${import.meta.env.BASE_URL}rxc.wasm`);
+ if (!res.ok || res.headers.get("content-type")?.includes("text/html")) throw new Error("rxc.wasm is missing: run `pnpm wasm` to build it");
+ return res.headers.get("content-type")?.includes("application/wasm") ? WebAssembly.compileStreaming(res) : WebAssembly.compile(await res.arrayBuffer());
+}
+
+export async function init() {
+ let module: WebAssembly.Module | undefined;
+ for (let attempt = 1; !module; attempt++) {
+ try {
+ module = await fetchModule();
+ } catch (e) {
+ // a download cut off midway (NotReadableError, a network error) is worth another try; a missing file is not
+ if (attempt >= 3 || String(e).includes("pnpm wasm")) throw e;
+ }
+ }
+ call = loadRxc(module);
+ if (import.meta.hot) import.meta.hot.data.call = call;
+}
+
+/** The editor's files keyed by absolute path, as the crate reads them. */
+export const toFs = (files: Record): Files =>
+ Object.fromEntries(Object.entries(files).map(([k, v]) => ["/" + k.replace(/^\/+/, ""), v]));
+
+const normalize = (d: any): Diagnostic => ({ ...d, message: d.message ?? d.msg ?? "" });
+
+/** Each module's TSX projection with its mappings onto the .rx (spec/13 TY-1c), and the prelude it imports. */
+export function projection(files: Record): { prelude: string; code: Record; mappings: Record } {
+ const out = { prelude: "", code: {} as Record, mappings: {} as Record };
+ if (!call) return out;
+ const fs = toFs(files);
+ try {
+ out.prelude = call("prelude", {});
+ for (const file of Object.keys(fs).filter((f) => f.endsWith(".rx") && !f.endsWith(".d.rx"))) {
+ const a = call("analyze", { file, prelude: "./prelude" }, fs);
+ if (a.code) (out.code[file] = a.code), (out.mappings[file] = a.mappings ?? []);
+ }
+ } catch {}
+ return out;
+}
+
+export function compile(files: Record, target: Target): Result {
+ if (!call) return { diagnostics: [], app: { error: "the compiler is not loaded: reload the page" }, ms: 0 };
+ const t0 = performance.now();
+ const fs = toFs(files);
+ const diagnostics: Diagnostic[] = [];
+ for (const file of Object.keys(fs).filter((f) => f.endsWith(".rx") && !f.endsWith(".d.rx"))) {
+ try {
+ const a = call("analyze", { file, prelude: "./prelude", project: false }, fs);
+ diagnostics.push(...(a.diagnostics ?? []).map(normalize));
+ } catch (e) {
+ diagnostics.push({ file, code: "PANIC", rule: "—", message: `the compiler trapped: ${(e as Error).message}` });
+ }
+ }
+ let app: AppOut;
+ try {
+ app = fs[ENTRY] === undefined ? { error: "no main.rx: the program starts at main.rx" } : call("app", { entry: ENTRY, target, jsx: true }, fs);
+ } catch (e) {
+ app = { error: `the compiler trapped: ${(e as Error).message}` };
+ }
+ if (app.diagnostics) app.diagnostics = app.diagnostics.map(normalize);
+ // analyze reports per file; app's checker run can name a file analyze did not (a .d.rx, say)
+ for (const d of app.diagnostics ?? [])
+ if (!diagnostics.some((x) => x.file === d.file && x.code === d.code && x.line === d.line)) diagnostics.push(d);
+ return { diagnostics, app, ms: performance.now() - t0 };
+}
diff --git a/site/playground/src/explain.ts b/site/playground/src/explain.ts
new file mode 100644
index 00000000..0ec088e4
--- /dev/null
+++ b/site/playground/src/explain.ts
@@ -0,0 +1,37 @@
+
+/** The `.rx` form each Solid primitive in the view stands for (spec/11 CP-4b, @reactivescript/runtime). */
+export const SOLID_PRIMS: Record = {
+ createSignal: "source x := e (ST-1); for source x = await …, its truth (ST-5)",
+ createStore: "source x := […] or {…}: structured, a store (ST-2a)",
+ createOptimistic: "source x = … that an action guesses (AC-3)",
+ createOptimisticStore: "a keyed or structured source an action guesses by row (AC-3)",
+ createMemo: "an equation x = e (E-1), and each hoisted await (R-1)",
+ createProjection: "x key k = e (ST-4), and x = draft(pre x -> seed) { … } (ST-3)",
+ action: "action f(…) { … } (AC-1): each await is a yield",
+ affects: "affects x (AC-5)",
+ refresh: "refresh x (AC-4)",
+ untrack: "a read in imperative scope: a snapshot (H-10)",
+ omit: "{ a, ...rest }: a rest of a destructured value, a live view of the other fields (RG-4b)",
+ latest: "latest x (R-12)",
+ isPending: "pending? x (R-9)",
+ onFlush: "onFlush(() => { … }) (EF-8)",
+ createDeferred: "deferred x = e: an equation that lags its inputs on purpose (V-16)",
+ createEffect: "effect (a, b) { … }: the inputs it runs for, then what it does with them ($0, $1) (EF-1)",
+ onSettled: "onSettled (EF-7)",
+ until: "until (AC-6)",
+ Errored: "errored fallback(e) { … } { … } (R-f-4)",
+ Loading: "loading fallback { … } { … }",
+ Show: "if c { … } else { … }",
+ For: "for x in xs { … }",
+ Repeat: "for i in 0..n { … }",
+};
+
+export function primsIn(code: string): { name: string; from: string }[] {
+ const m = /^import \{([^}]*)\} from "solid-js";/m.exec(code);
+ if (!m) return [];
+ return m[1]
+ .split(",")
+ .map((s) => s.trim())
+ .filter((n) => SOLID_PRIMS[n])
+ .map((name) => ({ name, from: SOLID_PRIMS[name] }));
+}
diff --git a/site/playground/src/format.ts b/site/playground/src/format.ts
new file mode 100644
index 00000000..871d713f
--- /dev/null
+++ b/site/playground/src/format.ts
@@ -0,0 +1,85 @@
+import { solidify } from "./solidify";
+import { toRx, type RxProblem } from "./torx";
+
+let loaded: Promise<(code: string) => Promise> | undefined;
+
+const WIDTH = 110;
+const width = (s: string) => s.replace(/\t/g, " ").length;
+
+/** Puts the short calls Prettier splits one argument per line back on one line. */
+function rejoin(code: string) {
+ const lines = code.split("\n");
+ const out: string[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const open = lines[i];
+ if (open.endsWith("(")) {
+ const indent = /^\t*/.exec(open)![0];
+ let j = i + 1;
+ while (j < lines.length && j - i <= 6 && !/^\t*\)/.test(lines[j]) && !/[<>{]\s*$/.test(lines[j]) && !lines[j].includes("//")) j++;
+ const close = lines[j];
+ if (close !== undefined && close.startsWith(indent + ")") && j - i <= 6) {
+ const args = lines.slice(i + 1, j).map((l) => l.trim()).join(" ").replace(/,$/, "");
+ const joined = open + args + close.slice(indent.length);
+ if (width(joined) <= WIDTH) {
+ out.push(joined);
+ i = j;
+ continue;
+ }
+ }
+ }
+ out.push(open);
+ }
+ return out.join("\n");
+}
+
+/** Prettier, loaded the first time the JSX view is shown. */
+export function formatter() {
+ return (loaded ??= Promise.all([import("prettier/standalone"), import("prettier/plugins/babel"), import("prettier/plugins/estree")]).then(
+ ([prettier, babel, estree]) =>
+ async (code: string) =>
+ rejoin(await prettier.format(code, { parser: "babel", plugins: [babel, estree as any], printWidth: 100, useTabs: true })),
+ (e) => {
+ loaded = undefined;
+ throw e;
+ },
+ ));
+}
+
+/** The crate's JSX read as Solid primitives (`solidify`), formatted. */
+export async function formatSolid(raw: string): Promise<{ code: string; error?: string }> {
+ const format = await formatter();
+ let runtime = raw;
+ try {
+ runtime = await format(raw);
+ return { code: await format(solidify(runtime)) };
+ } catch (e) {
+ return { code: runtime, error: String((e as Error)?.message ?? e).split("\n")[0] };
+ }
+}
+
+/** Solid 2.0 written back as .rx (`toRx`), over the Babel parser Prettier carries. */
+export async function solidToRx(code: string, views: Record = {}): Promise<{ code: string; problems: RxProblem[]; files: Record }> {
+ const babel = await import("prettier/plugins/babel");
+ const parse = (src: string) => (babel as any).parsers["babel-ts"].parse(src, {});
+ let ast;
+ try {
+ ast = parse(code);
+ } catch (e: any) {
+ return { code: "", problems: [{ line: e?.loc?.start?.line ?? e?.loc?.line ?? 0, message: String(e?.message ?? e).split("\n")[0] }], files: {} };
+ }
+ // the program's other modules, by the path an import names them, so a source read from one reads as itself
+ const parsed = new Map();
+ const modules = (from: string) => {
+ const view = views[from.replace(/^\.\//, "")];
+ if (view === undefined) return;
+ if (!parsed.has(from)) {
+ try {
+ parsed.set(from, parse(view));
+ } catch {
+ parsed.set(from, undefined);
+ }
+ }
+ return parsed.get(from) as any;
+ };
+ return toRx(ast, code, { modules });
+}
diff --git a/site/playground/src/highlight.ts b/site/playground/src/highlight.ts
new file mode 100644
index 00000000..14db05fa
--- /dev/null
+++ b/site/playground/src/highlight.ts
@@ -0,0 +1,45 @@
+import hljs from "highlight.js/lib/core";
+import javascript from "highlight.js/lib/languages/javascript";
+import xml from "highlight.js/lib/languages/xml";
+
+hljs.registerLanguage("javascript", javascript);
+hljs.registerLanguage("xml", xml);
+
+export const highlight = (code: string, language: "javascript") => hljs.highlight(code, { language, ignoreIllegals: true }).value;
+
+const RX_KEYWORDS = new Set(
+ "source|component|action|effect|export|default|import|pure|from|if|else|for|in|await|loading|errored|fallback|guess|affects|refresh|latest|pending?|peek|pre|deferred|key|draft|let|try|catch|throw|error|fn|type|on|portal|onFlush|until|server|client|return|true|false|null|rejects".split("|"),
+);
+
+const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">");
+
+/** A light colouring of .rx for the editor's backdrop: comments, strings, keywords, :=, tags. Each `[start, end)` of
+ * `marks` is underlined, a problem's span. */
+export function highlightRx(src: string, marks: [number, number][] = []) {
+ const TOKEN = /(\/\/[^\n]*)|("(?:[^"\\\n]|\\.)*"|`(?:[^`\\]|\\.)*`)|(:=)|(<\/?[A-Za-z][\w.-]*)|([A-Za-z_$][\w$]*\??)|([^"`/<:A-Za-z_$]+|.)/gs;
+ const marked = (t: string, at: number) => {
+ const cuts = new Set([0, t.length]);
+ for (const [s, e] of marks) for (const c of [s - at, e - at]) if (c > 0 && c < t.length) cuts.add(c);
+ const at2 = [...cuts].sort((a, b) => a - b);
+ let s = "";
+ // a newline stays outside the underline, so each editor line keeps its own spans
+ for (let i = 0; i + 1 < at2.length; i++) {
+ const part = t.slice(at2[i], at2[i + 1]);
+ const on = marks.some(([ms, me]) => ms <= at + at2[i] && at + at2[i] < me);
+ s += on ? part.split("\n").map((p) => (p ? `${esc(p)} ` : "")).join("\n") : esc(part);
+ }
+ return s;
+ };
+ let out = "";
+ for (const m of src.matchAll(TOKEN)) {
+ const [t, comment, str, assign, tag, word] = m;
+ const x = marked(t, m.index ?? 0);
+ if (comment) out += `${x} `;
+ else if (str) out += `${x} `;
+ else if (assign) out += `${x} `;
+ else if (tag) out += `${x} `;
+ else if (word) out += RX_KEYWORDS.has(t) ? `${x} ` : x;
+ else out += x;
+ }
+ return out;
+}
diff --git a/site/playground/src/hover.ts b/site/playground/src/hover.ts
new file mode 100644
index 00000000..b9f3a167
--- /dev/null
+++ b/site/playground/src/hover.ts
@@ -0,0 +1,156 @@
+// The type under the pointer, and what can be written at the caret: an .rx offset, through the projection's mappings,
+// to TypeScript in a worker.
+import { projection } from "./compile";
+import type { Entry, TypeAnswer, TypeRequest } from "./types.worker";
+
+export type { Entry };
+
+export type Hover = { text: string; doc: string; start: number; length: number };
+
+let worker: Worker | undefined;
+let seq = 0;
+const waiting = new Map void>();
+
+function ask(request: Omit): Promise {
+ if (!worker) {
+ worker = new Worker(new URL("./types.worker.ts", import.meta.url), { type: "module" });
+ worker.onmessage = (e: MessageEvent) => {
+ waiting.get(e.data.id)?.(e.data);
+ waiting.delete(e.data.id);
+ };
+ worker.onerror = () => {
+ for (const done of waiting.values()) done({ id: -1, error: "the type checker did not load" });
+ waiting.clear();
+ worker = undefined;
+ };
+ }
+ const id = ++seq;
+ return new Promise((done) => {
+ waiting.set(id, done);
+ worker!.postMessage({ id, ...request } satisfies TypeRequest);
+ });
+}
+
+/** A `.d.rx`'s functions as TypeScript sees them: their parameters, and the return type when one is written. */
+const declarations = (rx: string) =>
+ [...rx.matchAll(/^export\s+(?:pure\s+)?fn\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*(?::\s*([^\n]*?))?\s*(?:rejects\([^)]*\))?\s*$/gm)]
+ .map(([, name, params, type]) => `export declare function ${name}(${params.replace(/\bref\s+/g, "")}): ${type?.trim() || "any"};`)
+ .join("\n") + "\nexport {};\n";
+
+type Projected = { of: Record; files: Record; maps: Record };
+let last: Projected | undefined;
+
+/** What TypeScript reads for these files: each module's projection, the prelude, declarations, and plain modules as they are. */
+function project(files: Record): Projected {
+ if (last?.of === files) return last;
+ const p = projection(files);
+ const out: Record = { "/prelude.ts": p.prelude };
+ for (const [name, text] of Object.entries(files)) {
+ if (name.endsWith(".d.rx")) out[`/${name.slice(0, -5)}.d.ts`] = declarations(text);
+ else if (name.endsWith(".rx")) out[`/${name.slice(0, -3)}.tsx`] = p.code["/" + name] ?? "export {};\n";
+ else out["/" + name] = text;
+ }
+ return (last = { of: files, files: out, maps: p.mappings });
+}
+
+/** `const x: number` is how the projection declares it; the .rx says what it is. */
+function inRx(text: string, name: string, rx: string) {
+ // an import reads as what it names; the `import x` line under it says nothing more
+ text = text.replace(/^\(alias\) /, "").replace(/\nimport [\w$]+$/, "");
+ const m = /^(const|let|var) /.exec(text);
+ if (!m) return text;
+ const id = name.replace(/[$]/g, "\\$&");
+ return (new RegExp(`\\bsource\\s+${id}\\b`).test(rx) ? "source " : "") + text.slice(m[0].length);
+}
+
+export async function typeAt(files: Record, name: string, offset: number): Promise {
+ if (!name.endsWith(".rx") || name.endsWith(".d.rx")) return;
+ const p = project(files);
+ // the name the offset is in: the projection copies its text, so the same place inside it is the same place
+ const hit = (p.maps["/" + name] ?? []).filter(([, s, n]) => s <= offset && offset <= s + n).sort((a, b) => a[2] - b[2])[0];
+ if (!hit) return;
+ const [g, s, n] = hit;
+ const a = await ask({ files: p.files, file: `/${name.slice(0, -3)}.tsx`, offset: g + Math.min(offset - s, n - 1) });
+ // an import nothing declares has no type to show
+ if (!a.text || /^import [\w$]+$/.test(a.text)) return;
+ const rx = files[name];
+ return { text: inRx(a.text, rx.slice(s, s + n), rx), doc: a.doc ?? "", start: s, length: n };
+}
+
+// what every .rx module has without importing it (spec/11 CP-4b, `B`)
+const BUILTINS = "log str len map filter sum every indexOf onFlush onSettled until".split(" ");
+// the forms a name can start: offered beside the names in scope, never after a dot
+const KEYWORDS = "source component action server effect fn await latest peek pre guess refresh affects draft import export let return try catch if else for loading errored fallback".split(" ");
+
+/** Of what TypeScript offers, what continues the word being typed. */
+function fitting(items: Entry[], prefix: string, from: number): { from: number; items: Entry[] } {
+ const lower = prefix.toLowerCase();
+ const fits = items.filter((x, i) => x.name.toLowerCase().startsWith(lower) && items.findIndex((y) => y.name === x.name) === i);
+ // nothing left to write when the one thing that fits is already there
+ if (fits.length === 1 && fits[0].name === prefix) return { from, items: [] };
+ return { from, items: fits.sort((a, b) => Number(b.name.startsWith(prefix)) - Number(a.name.startsWith(prefix)) || (a.rank ?? 0) - (b.rank ?? 0)).slice(0, 40) };
+}
+
+/** `text` with `name` imported from `from`: added to that module's import, or as a new one. `shift`: how far what follows moved. */
+export function withImport(text: string, name: string, from: string): { text: string; at: number; shift: number } {
+ const m = new RegExp(`import\\s*(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*["']${from.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}["']`).exec(text);
+ if (!m) {
+ const line = `import { ${name} } from "${from}";\n`;
+ return { text: line + text, at: 0, shift: line.length };
+ }
+ const list = m[1];
+ if (list.split(",").some((x) => x.trim().split(/\s+as\s+/).pop() === name)) return { text, at: 0, shift: 0 };
+ const kept = list.replace(/\s+$/, "");
+ const comma = kept.endsWith(",");
+ const add = !kept.trim() ? ` ${name}` : list.includes("\n") ? `${comma ? "" : ","}\n ${name}${comma ? "," : ""}` : `${comma ? " " : ", "}${name}`;
+ const at = m.index + m[0].indexOf("{") + 1 + kept.length;
+ return { text: text.slice(0, at) + add + text.slice(at), at, shift: add.length };
+}
+
+/** The names that fit at `offset`: `from` is where the word being typed starts, so that much is replaced. */
+export async function completeAt(files: Record, name: string, offset: number): Promise<{ from: number; items: Entry[] }> {
+ const rx = files[name] ?? "";
+ const prefix = /[\w$]*$/.exec(rx.slice(0, offset))![0];
+ const from = offset - prefix.length;
+ if (!name.endsWith(".rx") || name.endsWith(".d.rx")) return { from, items: [] };
+ const p = project(files);
+ const hit = (p.maps["/" + name] ?? []).filter(([, s, n]) => s <= offset && offset <= s + n).sort((a, b) => a[2] - b[2])[0];
+ let items: Entry[] = [];
+ if (hit) items = (await ask({ files: p.files, file: `/${name.slice(0, -3)}.tsx`, offset: hit[0] + (offset - hit[1]), complete: true })).entries ?? [];
+ if (rx[from - 1] !== "." && prefix) items = [...items, ...BUILTINS.map((k) => ({ name: k, kind: "built-in" })), ...KEYWORDS.map((k) => ({ name: k, kind: "keyword" }))];
+ return fitting(items, prefix, from);
+}
+
+// ---- Solid's own source, in the Solid → .rx pane: TypeScript reads it as it is
+
+const SOLID_FILE = "/App.tsx";
+/** The Solid source with what it can import: the other files' declarations, and plain modules as they are. */
+function beside(source: string, files: Record) {
+ const out: Record = { [SOLID_FILE]: source };
+ for (const [name, text] of Object.entries(files)) {
+ if (name.endsWith(".d.rx")) out[`/${name.slice(0, -5)}.d.ts`] = declarations(text);
+ else if (!name.endsWith(".rx")) out["/" + name] = text;
+ }
+ return out;
+}
+
+export async function typeAtSolid(source: string, files: Record, offset: number): Promise {
+ const start = offset - /[\w$]*$/.exec(source.slice(0, offset))![0].length;
+ const length = /^[\w$]*/.exec(source.slice(start))![0].length;
+ if (!length) return;
+ const a = await ask({ files: beside(source, files), file: SOLID_FILE, offset });
+ if (!a.text) return;
+ return { text: a.text.replace(/^\(alias\) /, ""), doc: a.doc ?? "", start, length };
+}
+
+export async function completeAtSolid(source: string, files: Record, offset: number): Promise<{ from: number; items: Entry[] }> {
+ const prefix = /[\w$]*$/.exec(source.slice(0, offset))![0];
+ const from = offset - prefix.length;
+ // after a dot, or once a word is started: every name in scope is too many to offer for nothing typed
+ if (source[from - 1] !== "." && !prefix) return { from, items: [] };
+ const a = await ask({ files: beside(source, files), file: SOLID_FILE, offset, complete: true, ambient: true });
+ const items = a.entries ?? [];
+ // where a name can stand, every Solid export fits, imported or not: picking one adds the import
+ const more = a.member || !prefix ? [] : (a.solid ?? []).filter((n) => !items.some((x) => x.name === n && x.rank === 0)).sort().map((n) => ({ name: n, kind: "solid-js", rank: 1, importFrom: "solid-js" }));
+ return fitting([...items.filter((x) => !more.some((y) => y.name === x.name)), ...more], prefix, from);
+}
diff --git a/site/playground/src/link.ts b/site/playground/src/link.ts
new file mode 100644
index 00000000..29fff967
--- /dev/null
+++ b/site/playground/src/link.ts
@@ -0,0 +1,67 @@
+// Which .rx line each line of the Solid view came from: a declaration by its name, a block by its place among the
+// module's blocks of that kind. The view is rewritten text, so this is what survives it.
+
+export type Link = { file: string; line: number };
+
+const esc = (s: string) => s.replace(/\$/g, "\\$");
+const lower = (s: string) => s.charAt(0).toLowerCase() + s.slice(1);
+
+/** What a view line declares or opens: a name to find, or the nth block of a kind. */
+function target(line: string): { name: string; provide?: boolean } | { block: string } | undefined {
+ const l = line.replace(/^\s*(?:export\s+(?:default\s+)?)?/, "");
+ let m: RegExpExecArray | null;
+ if ((m = /^const \[(\w+?)(?:\$truth)?, \w+\] = create(?:Signal|Store|OptimisticStore|Optimistic)\(/.exec(l))) return { name: m[1] };
+ if ((m = /^const (\w+)Context = createContext\(/.exec(l))) return { name: lower(m[1]) };
+ if ((m = /^const (?:i\$)?(\w+?)(?:\$await\d*|\$answer)? = (?:createMemo|createDeferred|createProjection|omit|useContext|action)\(/.exec(l))) return { name: m[1] };
+ if ((m = /^(?:async )?function (\w+)\(/.exec(l))) return { name: m[1] };
+ if ((m = /^class (\w+) extends Error\b/.exec(l))) return { name: m[1] };
+ if ((m = /^<(\w+)Context value=/.exec(l))) return { name: lower(m[1]), provide: true };
+ if (/^createEffect\(/.test(l)) return { block: "effect" };
+ if ((m = /^<(Errored|Loading|Show|For)\b/.exec(l))) return { block: { Errored: "errored", Loading: "loading", Show: "if", For: "for" }[m[1]]! };
+}
+
+// a block nested in another is written without its own `{`; an `if (` with a parenthesis is a statement, not markup
+const BLOCK: Record = {
+ errored: /\{errored\b|^[ \t]*errored\b/gm,
+ loading: /\{loading\b|^[ \t]*loading\b/gm,
+ if: /\{if\b|^[ \t]*if[ \t]+(?!\()/gm,
+ for: /\{for\b|^[ \t]*for[ \t]+[\w$]+[ \t]+in\b/gm,
+ effect: /^[ \t]*effect\b/gm,
+};
+
+/** The 1-based line of `at` in `src`. */
+const lineOf = (src: string, at: number) => src.slice(0, at).split("\n").length;
+
+/** One entry per line of `view`: where in which .rx module it was written, when that can be told. */
+export function linkLines(view: string, files: Record, entry = "main.rx"): (Link | undefined)[] {
+ let file = entry;
+ const seen = new Map();
+ return view.split("\n").map((line) => {
+ const header = /^\/\/ \/(\S+\.rx)$/.exec(line);
+ if (header) {
+ file = header[1];
+ seen.clear();
+ return { file, line: 1 };
+ }
+ const src = files[file];
+ const t = src === undefined ? undefined : target(line);
+ if (!t || src === undefined) return;
+ if ("block" in t) {
+ const n = seen.get(t.block) ?? 0;
+ seen.set(t.block, n + 1);
+ const hit = [...src.matchAll(BLOCK[t.block])][n];
+ return hit ? { file, line: lineOf(src, hit.index ?? 0) } : undefined;
+ }
+ const n = esc(t.name);
+ const forms = t.provide
+ ? [new RegExp(`^[ \\t]*provide[ \\t]+${n}\\b`, "m")]
+ : [
+ new RegExp(`^[ \\t]*(?:export[ \\t]+)?(?:default[ \\t]+)?(?:source|deferred|action|component|error|context|server[ \\t]+fn|fn)[ \\t]+${n}\\b`, "m"),
+ new RegExp(`^[ \\t]*(?:export[ \\t]+)?${n}\\b[^=\\n]*?[^:=!<>]=(?!=)`, "m"),
+ ];
+ for (const r of forms) {
+ const hit = r.exec(src);
+ if (hit) return { file, line: lineOf(src, hit.index + (/^\s*/.exec(hit[0])![0].length)) };
+ }
+ });
+}
diff --git a/site/playground/src/main.tsx b/site/playground/src/main.tsx
new file mode 100644
index 00000000..85914305
--- /dev/null
+++ b/site/playground/src/main.tsx
@@ -0,0 +1,705 @@
+import { render } from "@solidjs/web";
+import { createEffect, createMemo, createSignal, For, Show } from "solid-js";
+import { compile, ENTRY, init, type Diagnostic } from "./compile";
+import { highlight, highlightRx } from "./highlight";
+import { linkLines } from "./link";
+import { primsIn } from "./explain";
+import { presets } from "./presets";
+import { decode, encode } from "./share";
+import { formatSolid, solidToRx } from "./format";
+import { HELPERS, type RxProblem } from "./torx";
+import { completeAt, completeAtSolid, typeAt, typeAtSolid, withImport, type Entry, type Hover } from "./hover";
+
+const GUIDE = "https://github.com/solidjs/reactivescript/blob/main/guide/diagnostics.md";
+
+const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """);
+
+function lineCol(text: string, line: number, column: number) {
+ let i = 0;
+ for (let l = 1; l < line; l++) {
+ const n = text.indexOf("\n", i);
+ if (n < 0) return text.length;
+ i = n + 1;
+ }
+ return Math.min(i + column, text.length);
+}
+
+/** A textarea over its highlighted copy. */
+function Editor(props: { value: string; html: string; onChange: (value: string) => void; testid: string; ref?: (el: HTMLTextAreaElement) => void; typeAt?: (offset: number) => Promise; completeAt?: (offset: number, text: string) => Promise<{ from: number; items: Entry[] }> }) {
+ let textarea!: HTMLTextAreaElement;
+ let backdrop!: HTMLPreElement;
+ const [tip, setTip] = createSignal<{ hover: Hover; left: number; top: number } | undefined>();
+ let timer: ReturnType | undefined;
+ let asked = -1;
+ const hide = () => {
+ clearTimeout(timer);
+ asked = -1;
+ setTip(undefined);
+ };
+ const syncScroll = () => {
+ backdrop.scrollTop = textarea.scrollTop;
+ backdrop.scrollLeft = textarea.scrollLeft;
+ hide();
+ };
+ /** Where the text sits: the padding, a line's height and a character's width, measured from the backdrop. */
+ const metrics = () => {
+ const cs = getComputedStyle(backdrop);
+ const probe = document.createElement("span");
+ probe.textContent = "0".repeat(100);
+ probe.style.cssText = "position:absolute;visibility:hidden";
+ backdrop.append(probe);
+ const box = probe.getBoundingClientRect();
+ probe.remove();
+ return { left: parseFloat(cs.paddingLeft), top: parseFloat(cs.paddingTop), line: box.height, char: box.width / 100 };
+ };
+ const onMove = (e: MouseEvent) => {
+ if (!props.typeAt) return;
+ clearTimeout(timer);
+ const box = textarea.getBoundingClientRect();
+ const m = metrics();
+ const row = Math.floor((e.clientY - box.top + textarea.scrollTop - m.top) / m.line);
+ const column = (e.clientX - box.left + textarea.scrollLeft - m.left) / m.char;
+ const lines = props.value.split("\n");
+ // a tab is as wide as the tab-size, so columns are counted, not characters
+ let at = 0;
+ let width = 0;
+ const text = lines[row] ?? "";
+ while (at < text.length && width + (text[at] === "\t" ? 2 - (width % 2) : 1) <= column) width += text[at++] === "\t" ? 2 - (width % 2) : 1;
+ if (row < 0 || row >= lines.length || column < 0 || at >= text.length || !/[\w$.]/.test(text[at])) return hide();
+ const offset = lines.slice(0, row).reduce((n, l) => n + l.length + 1, 0) + at;
+ const shown = tip();
+ if (shown && offset >= shown.hover.start && offset < shown.hover.start + shown.hover.length) return;
+ timer = setTimeout(async () => {
+ asked = offset;
+ const hover = await props.typeAt!(offset).catch(() => undefined);
+ if (asked !== offset) return;
+ if (!hover) return setTip(undefined);
+ const before = props.value.slice(0, hover.start);
+ const line = before.split("\n").length - 1;
+ const col = [...before.slice(before.lastIndexOf("\n") + 1)].reduce((w, c) => w + (c === "\t" ? 2 - (w % 2) : 1), 0);
+ setTip({ hover, left: Math.max(4, m.left + col * m.char - textarea.scrollLeft), top: m.top + (line + 1) * m.line - textarea.scrollTop + 4 });
+ }, 180);
+ };
+ // what can be written at the caret, as a list under it
+ const [menu, setMenu] = createSignal<{ from: number; to: number; items: Entry[]; index: number; left: number; top: number } | undefined>();
+ let suggesting: ReturnType | undefined;
+ let wanted = 0;
+ let list: HTMLUListElement | undefined;
+ createEffect(
+ () => menu()?.index,
+ (index) => {
+ if (index !== undefined) list?.children[index]?.scrollIntoView({ block: "nearest" });
+ },
+ );
+ const close = () => {
+ clearTimeout(suggesting);
+ wanted++;
+ setMenu(undefined);
+ };
+ /** Where an offset of `text` is drawn, in the editor's box. */
+ const place = (text: string, offset: number) => {
+ const m = metrics();
+ const before = text.slice(0, offset);
+ const col = [...before.slice(before.lastIndexOf("\n") + 1)].reduce((w, c) => w + (c === "\t" ? 2 - (w % 2) : 1), 0);
+ return { left: Math.max(4, m.left + col * m.char - textarea.scrollLeft), top: m.top + before.split("\n").length * m.line - textarea.scrollTop + 2 };
+ };
+ const suggest = (force = false) => {
+ if (!props.completeAt) return;
+ clearTimeout(suggesting);
+ suggesting = setTimeout(async () => {
+ const text = textarea.value;
+ const at = textarea.selectionStart;
+ if (at !== textarea.selectionEnd) return close();
+ // after a dot, or inside a word; anywhere when asked for
+ if (!force && !/[\w$.]/.test(text[at - 1] ?? "")) return close();
+ const mine = ++wanted;
+ const found = await props.completeAt!(at, text).catch(() => undefined);
+ if (mine !== wanted) return;
+ if (!found?.items.length || textarea.selectionStart !== at) return setMenu(undefined);
+ hide();
+ setMenu({ from: found.from, to: at, items: found.items, index: 0, ...place(text, found.from) });
+ }, 90);
+ };
+ const accept = (item: Entry) => {
+ const m = menu();
+ if (!m) return;
+ let text = textarea.value.slice(0, m.from) + item.name + textarea.value.slice(m.to);
+ let caret = m.from + item.name.length;
+ if (item.importFrom) {
+ const added = withImport(text, item.name, item.importFrom);
+ text = added.text;
+ if (added.at <= caret) caret += added.shift;
+ }
+ close();
+ props.onChange(text);
+ queueMicrotask(() => {
+ textarea.focus();
+ textarea.setSelectionRange(caret, caret);
+ });
+ };
+ const onKey = (e: KeyboardEvent) => {
+ const m = menu();
+ if (m) {
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ e.preventDefault();
+ return void setMenu({ ...m, index: (m.index + (e.key === "ArrowDown" ? 1 : m.items.length - 1)) % m.items.length });
+ }
+ if (e.key === "Enter" || e.key === "Tab") {
+ e.preventDefault();
+ return accept(m.items[m.index]);
+ }
+ if (e.key === "Escape") return close();
+ if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Home" || e.key === "End") close();
+ }
+ if (e.key === " " && e.ctrlKey) {
+ e.preventDefault();
+ return suggest(true);
+ }
+ if (e.key === "Tab" && !e.shiftKey) {
+ e.preventDefault();
+ const { selectionStart: s, selectionEnd: end, value } = textarea;
+ props.onChange(value.slice(0, s) + " " + value.slice(end));
+ queueMicrotask(() => textarea.setSelectionRange(s + 2, s + 2));
+ }
+ };
+ return (
+
+ );
+}
+
+const SAMPLE_SOLID = `import { createSignal, createMemo } from "solid-js";
+
+export default function Counter() {
+ const [count, setCount] = createSignal(0);
+ const doubled = createMemo(() => count() * 2);
+ return setCount(count() + 1)}>{doubled()} ;
+}
+`;
+
+/** Solid 2.0 on the left, the same program as .rx on the right (torx.ts), checked by the compiler. */
+function FromSolid(props: { source: string; onChange: (value: string) => void; files: Record; ready: boolean; hidden: boolean; views: Record; onRx: (r: { of: string; code: string; files: Record }) => void }) {
+ const [out, setOut] = createSignal<{ of: string; code: string; problems: RxProblem[]; files: Record }>({ of: "", code: "", problems: [], files: {} });
+ createEffect(
+ () => [props.source, props.views] as const,
+ ([source, views]) => {
+ solidToRx(source, views).then((r) => {
+ if (props.source !== source) return;
+ setOut({ of: source, ...r });
+ props.onRx({ of: source, code: r.problems.length ? "" : r.code, files: r.files });
+ });
+ },
+ );
+ const current = () => out().of === props.source;
+ const rx = () => (current() ? out().code : "");
+ const problems = () => (current() ? out().problems : []);
+ const helpers = () => Object.entries(current() ? out().files : {});
+ // the checker's word on the .rx, with the declaration files of the program in the other mode
+ const checked = createMemo(() => (props.ready && rx() && !problems().length ? compile({ ...props.files, ...out().files, "main.rx": rx() }, "dom") : undefined));
+ const diagnostics = () => (checked()?.diagnostics ?? []).filter((d) => d.file === ENTRY);
+ const html = createMemo(() => {
+ const bad = new Set(problems().map((p) => p.line));
+ return props.source
+ .split("\n")
+ .map((l, i) => `${highlight(l, "javascript") || " "} `)
+ .join("\n");
+ });
+ let textarea!: HTMLTextAreaElement;
+ const goTo = (line: number) => {
+ const start = lineCol(props.source, line, 0);
+ textarea.focus();
+ textarea.setSelectionRange(start, lineCol(props.source, line + 1, 0) - 1);
+ };
+ return (
+
+
+
+
+ App.tsx
+
+
+ (textarea = el)}
+ typeAt={(offset) => typeAtSolid(props.source, props.files, offset)}
+ completeAt={(offset, text) => completeAtSolid(text, props.files, offset)}
+ />
+
+
+ Not converted {problems().length}
+
+
{current() ? "Every form here has an .rx reading." : ""}}>
+
+
+ {(p) => (
+
+ goTo(p().line)}>
+ App.tsx:{p().line}
+
+ {p().message}
+
+ )}
+
+
+
+
+
+
+
+
+ ReactiveScript
+ the same program as .rx; a prototype that lists what it cannot read
+
+
+ Some of this has no .rx form yet, so the result is incomplete.
+
+
+
+
+ {([name, code]) => (
+
+
+ {name} plain TypeScript stays TypeScript; the .rx imports it
+
+
+
+ )}
+
+
+
+
+ The checker on this .rx {diagnostics().length}
+
+
The checker accepts it.}>
+
+
+ {(d) => (
+
+ main.rx:{d().line ?? "?"}
+
+ {d().code}
+
+ [{d().rule}]
+ {d().message}
+
+ )}
+
+
+
+
+
+
+
+
+ );
+}
+
+async function copyText(text: string): Promise {
+ if (navigator.clipboard) {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {}
+ }
+ // the Clipboard API exists only on https and localhost; a LAN address over http needs the old copy command
+ const ta = document.createElement("textarea");
+ ta.value = text;
+ ta.style.cssText = "position:fixed;opacity:0";
+ document.body.append(ta);
+ ta.select();
+ try {
+ return document.execCommand("copy");
+ } catch {
+ return false;
+ } finally {
+ ta.remove();
+ }
+}
+
+function Playground(props: { initial: { files: Record; active: string; preset?: string; solid?: string }; compiler: Promise }) {
+ const [files, setFiles] = createSignal>(props.initial.files);
+ const [active, setActive] = createSignal(props.initial.active);
+ const [preset, setPreset] = createSignal(props.initial.preset ?? "");
+ const [copied, setCopied] = createSignal("");
+ const [mode, setMode] = createSignal<"rx" | "solid">(props.initial.solid === undefined ? "rx" : "solid");
+ const [solidSource, setSolidSource] = createSignal(props.initial.solid ?? "");
+
+ // "loading", "ready", or why the compiler did not load
+ const [compiler, setCompiler] = createSignal("loading");
+ props.compiler.then(
+ () => setCompiler("ready"),
+ (e) => setCompiler(String(e?.message ?? e)),
+ );
+ const ready = () => compiler() === "ready";
+ const result = createMemo(() => (ready() ? compile(files(), "dom") : { diagnostics: [], app: {}, ms: 0 }));
+ const lastGood = createMemo | undefined>((prev) => (result().app.modules ? result() : prev));
+ const stale = () => ready() && !result().app.modules;
+ const diagnostics = () => result().diagnostics;
+ const failure = () => result().app.error;
+ const modules = createMemo(() =>
+ Object.entries(lastGood()?.app.modules ?? {})
+ .sort(([a], [b]) => Number(b === ENTRY) - Number(a === ENTRY))
+ .map(([p, m]) => ({ path: p, jsx: m.jsx ?? "" })),
+ );
+ const rawJsx = createMemo(() => modules().map((m) => m.jsx).join("\n\n"));
+ const [solid, setSolid] = createSignal<{ raw: string; code: string; error?: string }>({ raw: "", code: "" });
+ createEffect(
+ () => [rawJsx(), modules()] as const,
+ ([raw, mods]) => {
+ Promise.all(mods.map((m) => formatSolid(m.jsx).then((r) => ({ ...r, path: m.path }))))
+ .then(
+ (rs) =>
+ rawJsx() === raw &&
+ setSolid({ raw, code: rs.map((r) => (r.path === ENTRY ? r.code : `// ${r.path}\n${r.code}`)).join("\n"), error: rs.find((r) => r.error)?.error }),
+ )
+ .catch((e) => rawJsx() === raw && setSolid({ raw, code: raw, error: String(e?.message ?? e) }));
+ },
+ );
+ const shown = () => (solid().raw === rawJsx() ? solid().code : "");
+ // the Solid view of each .rx module, by file name: the converter reads what another module exports from it
+ const moduleViews = createMemo(() => {
+ const out: Record = {};
+ let name = ENTRY.replace(/^\//, "");
+ let lines: string[] = [];
+ for (const l of shown().split("\n")) {
+ const h = /^\/\/ \/(\S+\.rx)$/.exec(l);
+ if (!h) {
+ lines.push(l);
+ continue;
+ }
+ out[name] = lines.join("\n");
+ name = h[1];
+ lines = [];
+ }
+ out[name] = lines.join("\n");
+ return out;
+ });
+ // each view line's .rx line, where it can be told: a click there selects it in the editor
+ const links = createMemo(() => linkLines(shown(), files()));
+ const [picked, setPicked] = createSignal(-1);
+ const codeHtml = createMemo(() =>
+ shown()
+ .split("\n")
+ .map((l, i) => {
+ const at = links()[i];
+ const cls = `cl${at ? " link" : ""}${picked() === i ? " on" : ""}`;
+ return `${highlight(l, "javascript") || " "}
`;
+ })
+ .join(""),
+ );
+ const prims = createMemo(() => primsIn(shown()));
+
+ const text = () => files()[active()] ?? "";
+ const editLines = createMemo(() => {
+ const mine = diagnostics().filter((d) => d.file === "/" + active() && d.line);
+ const bad = new Set(mine.map((d) => d.line!));
+ const t = text();
+ // a problem's own span, or the word at its start when the span is empty
+ const marks = mine.flatMap((d): [number, number][] => {
+ if (!d.range) return [];
+ const s = lineCol(t, d.range.start.line, d.range.start.column);
+ const e = lineCol(t, d.range.end.line, d.range.end.column);
+ return [[s, e > s ? e : s + Math.max(1, /^[\w$]*/.exec(t.slice(s))![0].length)]];
+ });
+ return highlightRx(t, marks)
+ .split("\n")
+ .map((l, i) => `${l || " "} `)
+ .join("\n");
+ });
+
+ let textarea!: HTMLTextAreaElement;
+
+ const update = (value: string) => {
+ setFiles({ ...files(), [active()]: value });
+ setPreset("");
+ };
+ const loadPreset = (id: string) => {
+ const p = presets.find((x) => x.id === id);
+ if (!p) return;
+ setFiles({ ...p.files });
+ setActive("main.rx");
+ setPreset(id);
+ setMode("rx");
+ };
+ // the .rx read from the Solid side, kept for turning the page back; none when the reading left something out
+ let converted: { of: string; code: string; files: Record } | undefined;
+ const toggleMode = () => {
+ // each way round, the editor gets the program the other side showed: the Solid view, or the .rx read from it
+ if (mode() === "rx") setSolidSource(shown().split(/\n\/\/ \/[^\n]*\n/)[0] || SAMPLE_SOLID);
+ else if (converted && converted.of === solidSource() && converted.code.trim()) {
+ const next: Record = { ...files(), ...converted.files, "main.rx": converted.code };
+ if (!(HELPERS in converted.files)) delete next[HELPERS];
+ setFiles(next);
+ setActive("main.rx");
+ setPreset("");
+ }
+ setMode(mode() === "rx" ? "solid" : "rx");
+ };
+ const goTo = (d: Diagnostic) => {
+ const name = d.file.replace(/^\//, "");
+ if (name in files()) setActive(name);
+ queueMicrotask(() => {
+ const t = files()[active()] ?? "";
+ const start = d.range ? lineCol(t, d.range.start.line, d.range.start.column) : lineCol(t, d.line ?? 1, 0);
+ const end = d.range ? lineCol(t, d.range.end.line, d.range.end.column) : start;
+ textarea.focus();
+ textarea.setSelectionRange(start, Math.max(end, start));
+ });
+ };
+ const pickLine = (e: MouseEvent) => {
+ const el = (e.target as HTMLElement).closest(".cl[data-l]");
+ const at = el ? links()[Number(el.dataset.l)] : undefined;
+ if (!el || !at) return;
+ setPicked(Number(el.dataset.l));
+ if (at.file in files()) setActive(at.file);
+ queueMicrotask(() => {
+ const t = files()[active()] ?? "";
+ const start = lineCol(t, at.line, 0);
+ const end = t.indexOf("\n", start);
+ textarea.focus({ preventScroll: true });
+ textarea.setSelectionRange(start, end < 0 ? t.length : end);
+ const lh = parseFloat(getComputedStyle(textarea).lineHeight) || 20;
+ textarea.scrollTop = Math.max(0, (at.line - 1) * lh - textarea.clientHeight / 3);
+ });
+ };
+ const addFile = () => {
+ const name = prompt("New file name (an .rx module, a .d.rx declaration, or a .js module):", "util.rx");
+ if (!name || name in files() || !/^[\w./-]+\.(rx|js|mjs)$/.test(name)) return;
+ setPreset("");
+ setFiles({ ...files(), [name]: name.endsWith(".d.rx") ? "export pure fn load()\n" : name.endsWith(".rx") ? "export n = 1\n" : "export const n = 1;\n" });
+ setActive(name);
+ };
+ const removeFile = (name: string) => {
+ if (name === "main.rx" || !confirm(`Remove ${name}?`)) return;
+ const next = { ...files() };
+ delete next[name];
+ setPreset("");
+ setFiles(next);
+ setActive("main.rx");
+ };
+ const share = async () => {
+ const hash = await encode({ files: files(), active: active(), solid: mode() === "solid" ? solidSource() : undefined });
+ history.replaceState(null, "", "#" + hash);
+ setCopied((await copyText(location.href)) ? "Link copied" : "Copy the address bar");
+ setTimeout(() => setCopied(""), 2000);
+ };
+
+ // the URL keeps the program, so a reload or a shared link opens it again
+ let hashTimer: ReturnType | undefined;
+ createEffect(
+ () => [files(), active(), preset(), mode() === "solid" ? solidSource() : undefined] as const,
+ ([f, a, p, s]) => {
+ clearTimeout(hashTimer);
+ hashTimer = setTimeout(async () => {
+ // the Solid → .rx side is kept too, so a reload opens the page the same way round
+ const hash = p && s === undefined ? `example=${p}` : await encode({ files: f, active: a, solid: s });
+ history.replaceState(null, "", "#" + hash);
+ }, 300);
+ },
+ );
+
+ return (
+
+
+
+
+
+ ReactiveScript Playground
+
+
+
+ Example
+ loadPreset(e.currentTarget.value)}>
+
+ (edited)
+
+ {(p) => {p.title} }
+
+
+
+ {mode() === "rx" ? "Solid → .rx" : ".rx → Solid"}
+
+
+
+ {ready() ? `${result().ms.toFixed(1)} ms` : ""}
+
+
+ {copied() || "Share"}
+
+
+
+
Paste Solid 2.0 on the left to read it as ReactiveScript. The compiler then checks the result.}>
+ p.id === preset())}>{(p) => {p().blurb}
}
+
+
+
(converted = r)} />
+
+
+
+
+ {(name) => (
+
+ setActive(name)}>
+ {name}
+
+
+ removeFile(name)}>
+ ×
+
+
+
+ )}
+
+
+ +
+
+
+ (textarea = el)} typeAt={(offset) => typeAt(files(), active(), offset)} completeAt={(offset, text) => completeAt({ ...files(), [active()]: text }, active(), offset)} />
+
+
+ Diagnostics {diagnostics().length}
+
+
{ready() ? "The checker accepts the program." : ""}}>
+ {(f) => {f()} }
+
+
+ {(d) => (
+
+ goTo(d())}>
+ {d().file.replace(/^\//, "")}:{d().range ? `${d().range!.start.line}:${d().range!.start.column + 1}` : d().line ?? "?"}
+
+
+ {d().code}
+
+ [{d().rule}]
+ {d().message}
+
+ )}
+
+
+
+
+
+
+
+
+ Solid primitives
+ what the compiler's __rt calls are in Solid 2.0, for reading
+
+
+ Not compiled: showing the last output that compiled.
+
+
+
+ Could not write this as Solid primitives ({solid().error}); showing the compiler's JSX instead.
+
+
+
+
+
+
Loading the compiler…}>
+ The compiler did not load.
+ {compiler()}
+ location.reload()}>
+ Retry
+
+
+
+
+
+
+
+
What each primitive stands for in .rx
+
+
+
+ Solid
+ written in .rx as
+
+
+
+
+ {(p) => (
+
+
+ {p().name}
+
+ {p().from}
+
+ )}
+
+
+
+
+
+
+
+
+
+ );
+}
+
+async function start() {
+ const compiler = init();
+ const fromHash = await decode(location.hash);
+ const featured = presets.find((p) => p.id === (fromHash?.preset ?? "await")) ?? presets[0];
+ const initial = fromHash?.files
+ ? { files: fromHash.files, active: fromHash.active in fromHash.files ? fromHash.active : "main.rx", solid: fromHash.solid }
+ : { files: { ...featured.files }, active: "main.rx", preset: featured.id };
+ const root = document.getElementById("app")!;
+ root.textContent = "";
+ render(() => , root);
+}
+
+start().catch((e) => {
+ const root = document.getElementById("app")!;
+ root.innerHTML = `The playground did not start.
`;
+ root.querySelector("pre")!.textContent = String(e?.message ?? e);
+});
diff --git a/site/playground/src/presets.ts b/site/playground/src/presets.ts
new file mode 100644
index 00000000..d3e15087
--- /dev/null
+++ b/site/playground/src/presets.ts
@@ -0,0 +1,295 @@
+export type Preset = { id: string; title: string; blurb: string; files: Record };
+
+const users = {
+ "users.d.rx": `export pure fn fetchUser(id: number) rejects(NotFound)
+export error NotFound
+`,
+ // what users.d.rx declares: the compiler reads the declaration, a browser runs this
+ "users.js": `const NAMES = ["Ada", "Grace", "Anders", "Brendan"];
+
+export class NotFound extends Error {}
+
+export async function fetchUser(id) {
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ if (id > NAMES.length) throw new NotFound("There is no user " + id);
+ return { id, name: NAMES[id - 1] };
+}
+`,
+};
+
+export const presets: Preset[] = [
+ {
+ id: "source",
+ title: "Source and equation",
+ blurb: "A source is a signal you write; an equation is a memo over what it reads.",
+ files: {
+ "main.rx": `export default component App() {
+ source count := 0 // a source: __rt.source, over createSignal
+ double = count * 2 // an equation: __rt.memo, over createMemo
+ parity = count % 2 == 0 ? "even" : "odd"
+
+
+
{ count := count + 1 }}>
+ Clicked {count} times
+
+
double: {double}, {parity}
+
+}
+`,
+ },
+ },
+ {
+ id: "await",
+ title: "await, loading, errored",
+ blurb: "One equation with an await lowers to two memos: the hoisted await keyed on id, and the rest reading suffix.",
+ files: {
+ "main.rx": `import pure { fetchUser } from "./users"
+
+export default component App() {
+ source id := 1
+ source suffix := "!"
+ label = (await fetchUser(id)).name + suffix
+
+
+ {errored fallback(e) { {e.message}
} {
+ {loading fallback { Loading…
} {
+ {label}
+ }}
+ }}
+ { id := latest id + 1 }}>Next user ({latest id})
+ { suffix := suffix + "!" }}>More excitement
+
+
+
+}
+`,
+ ...users,
+ },
+ },
+ {
+ id: "action",
+ title: "action with guess",
+ blurb: "guess shows a value now and takes it back by itself if the action fails.",
+ files: {
+ "main.rx": `import pure { loadName, saveName } from "./names"
+
+export default component App() {
+ source name = await loadName() // a source with a question: it can take a guess
+ source draft := ""
+ source saveError := ""
+
+ action save(next: string) {
+ guess name := next
+ affects name
+ onFlush(() => { saveError := "" })
+ try {
+ let saved = await saveName(next)
+ name := saved
+ } catch (e) {
+ saveError := e.message
+ }
+ }
+
+
+ {errored fallback(e) { {e.message}
} {
+ {loading fallback { Loading…
} {
+ Hello, {name}
+ }}
+ }}
+ { draft := e.currentTarget.value }} />
+ save(draft)}>Save
+ {if saveError != "" { {saveError}
}}
+
+
+
+}
+`,
+ "names.d.rx": `export pure fn loadName()
+export pure fn saveName(name: string)
+`,
+ "names.js": `let saved = "Ada";
+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+export async function loadName() {
+ await wait(300);
+ return saved;
+}
+
+export async function saveName(name) {
+ await wait(700);
+ if (!name.trim()) throw new Error("A name cannot be empty.");
+ return (saved = name.trim());
+}
+`,
+ },
+ },
+ {
+ id: "server",
+ title: "server fn",
+ blurb: "A server fn's body runs on the server. The view writes it as Solid's \"use server\" function, and an equation that calls it awaits a request.",
+ files: {
+ "main.rx": `import pure { findUser } from "./db"
+import { renameUser } from "./db"
+
+// runs on the server; a call from the page is a request
+server fn loadUser(id: number) {
+ let row = await findUser(id)
+ return { id, name: row.name }
+}
+
+server fn rename(id: number, name: string) {
+ await renameUser(id, name)
+}
+
+export default component App() {
+ source id := 1
+ source draft := ""
+ source saveError := ""
+ user = await loadUser(id)
+
+ action save() {
+ try {
+ await rename(id, draft)
+ saveError := ""
+ refresh user
+ } catch (e) {
+ saveError := e.message
+ }
+ }
+
+
+ {errored fallback(e) { {e.message}
} {
+ {loading fallback { Loading…
} {
+ {user.name}
+ }}
+ }}
+ { draft := e.currentTarget.value }} />
+ Rename
+ { id := latest id % 3 + 1 }}>Next user
+ {if saveError != "" { {saveError}
}}
+
+
+
+}
+`,
+ "db.d.rx": `export pure fn findUser(id: number)
+export fn renameUser(id: number, name: string)
+`,
+ // what db.d.rx declares: on a real server this would be the database
+ "db.js": `const names = ["Ada", "Grace", "Anders"];
+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+export async function findUser(id) {
+ await wait(300);
+ return { id, name: names[id - 1] };
+}
+
+export async function renameUser(id, name) {
+ await wait(500);
+ if (!name.trim()) throw new Error("A name cannot be empty.");
+ names[id - 1] = name.trim();
+}
+`,
+ },
+ },
+ {
+ id: "control",
+ title: "for and if",
+ blurb: "for and if are expressions in the view; they lower to Solid's For and Show.",
+ files: {
+ "main.rx": `names = ["Ada", "Grace", "Anders", "Brendan"]
+
+export default component App() {
+ source guests: string[] := []
+ count = guests.length
+
+
+ { guests := gs => [...gs, names[gs.length % names.length]] }}>
+ Sign the guestbook
+
+ { guests := [] }}>Clear
+
+ {if count == 0 {
+ No signatures yet.
+ } else {
+ {for guest in guests {
+ {guest}
+ }}
+ }}
+
+
+}
+`,
+ },
+ },
+ {
+ id: "projection",
+ title: "Projections: key and draft",
+ blurb: "A keyed equation and a draft both become createProjection: rows keep identity by key, a draft writes only what changed.",
+ files: {
+ "main.rx": `export default component App() {
+ source todos := [
+ { id: 1, title: "Write the spec", done: true },
+ { id: 2, title: "Port the crate", done: false },
+ { id: 3, title: "Ship the playground", done: false },
+ ]
+ source picked := 2
+ source last := 0
+
+ open key id = todos.filter(t => !t.done) // a keyed equation: createMemo + createProjection
+ marks = draft(pre marks -> {}) { // a draft: createProjection over its own writes
+ d[str(picked)] := true
+ d[str(last)] := false
+ }
+
+
+ {for todo in open {
+
+ { last := picked; picked := todo.id }}>{todo.title}
+
+ }}
+
+
+
+}
+`,
+ },
+ },
+ {
+ id: "style",
+ title: "Scoped style",
+ blurb: "A component's
+
+
The card is {lit ? "lit" : "dark"}.
+
{ lit := !lit }}>Toggle
+
+}
+`,
+ },
+ },
+];
diff --git a/site/playground/src/rxc.ts b/site/playground/src/rxc.ts
new file mode 100644
index 00000000..d802d318
--- /dev/null
+++ b/site/playground/src/rxc.ts
@@ -0,0 +1,38 @@
+export type Files = Record;
+
+export function loadRxc(module: WebAssembly.Module) {
+ let x: any;
+ let files: Files = {};
+ const enc = new TextEncoder(), dec = new TextDecoder();
+ const put = (b: Uint8Array) => {
+ const p = x.rx_alloc(b.length + 4);
+ new DataView(x.memory.buffer).setUint32(p, b.length, true);
+ new Uint8Array(x.memory.buffer).set(b, p + 4);
+ return p;
+ };
+ const env = {
+ rx_read(ptr: number, len: number) {
+ const f = dec.decode(new Uint8Array(x.memory.buffer, ptr, len));
+ return f in files ? put(enc.encode(files[f])) : 0;
+ },
+ };
+ const fresh = () => (x = new WebAssembly.Instance(module, { env }).exports);
+ fresh();
+ return (method: string, params: any, fs: Files = {}) => {
+ files = fs;
+ try {
+ const req = enc.encode(JSON.stringify({ method, params }));
+ const p = x.rx_alloc(req.length);
+ new Uint8Array(x.memory.buffer).set(req, p);
+ const out = x.rx_call(p, req.length);
+ const n = new DataView(x.memory.buffer).getUint32(out, true);
+ const text = dec.decode(new Uint8Array(x.memory.buffer, out + 4, n));
+ x.rx_free(out, n + 4);
+ return JSON.parse(text);
+ } catch (e) {
+ // a panic traps and leaves the instance unusable
+ fresh();
+ throw e;
+ }
+ };
+}
diff --git a/site/playground/src/share.ts b/site/playground/src/share.ts
new file mode 100644
index 00000000..72f50c29
--- /dev/null
+++ b/site/playground/src/share.ts
@@ -0,0 +1,26 @@
+/** `solid`: the Solid source, when the page is turned around (Solid → .rx). */
+export type State = { files: Record; active: string; preset?: string; solid?: string };
+
+const b64 = (bytes: Uint8Array) => btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join("")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+const unb64 = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
+
+async function pipe(bytes: Uint8Array, stream: CompressionStream | DecompressionStream) {
+ return new Uint8Array(await new Response(new Blob([bytes as BlobPart]).stream().pipeThrough(stream)).arrayBuffer());
+}
+
+export async function encode(state: State) {
+ const json = new TextEncoder().encode(JSON.stringify({ f: state.files, a: state.active, ...(state.solid === undefined ? {} : { s: state.solid }) }));
+ return "code=" + b64(await pipe(json, new CompressionStream("deflate-raw")));
+}
+
+export async function decode(hash: string): Promise {
+ const params = new URLSearchParams(hash.replace(/^#/, ""));
+ const code = params.get("code");
+ if (!code) return params.get("example") ? ({ preset: params.get("example")! } as State) : undefined;
+ try {
+ const s = JSON.parse(new TextDecoder().decode(await pipe(unb64(code), new DecompressionStream("deflate-raw"))));
+ return { files: s.f, active: s.a ?? "main.rx", solid: typeof s.s === "string" ? s.s : undefined };
+ } catch {
+ return undefined;
+ }
+}
diff --git a/site/playground/src/solidify.ts b/site/playground/src/solidify.ts
new file mode 100644
index 00000000..0acab43d
--- /dev/null
+++ b/site/playground/src/solidify.ts
@@ -0,0 +1,612 @@
+// The crate's `__rt` JSX read as Solid 2.0 primitives (spec/11 CP-4b); a reading aid, not what runs.
+
+/** The index just past the bracket that closes the one at `open`, skipping strings, templates and comments. */
+function close(code: string, open: number): number {
+ const pairs: Record = { "(": ")", "[": "]", "{": "}" };
+ const stack: string[] = [];
+ for (let i = open; i < code.length; i++) {
+ const c = code[i];
+ if (c === '"' || c === "'" || c === "`") {
+ for (i++; i < code.length && code[i] !== c; i++) if (code[i] === "\\") i++;
+ continue;
+ }
+ if (c === "/" && code[i + 1] === "/") {
+ i = code.indexOf("\n", i);
+ if (i < 0) return code.length;
+ continue;
+ }
+ if (pairs[c]) stack.push(pairs[c]);
+ else if (c === ")" || c === "]" || c === "}") {
+ stack.pop();
+ if (!stack.length) return i + 1;
+ }
+ }
+ return code.length;
+}
+
+/** Top-level arguments of the call whose `(` is at `open`. */
+function args(code: string, open: number): { list: string[]; end: number } {
+ const end = close(code, open);
+ const inner = code.slice(open + 1, end - 1);
+ const list: string[] = [];
+ let depth = 0;
+ let start = 0;
+ for (let i = 0; i < inner.length; i++) {
+ const c = inner[i];
+ if (c === '"' || c === "'" || c === "`") {
+ for (i++; i < inner.length && inner[i] !== c; i++) if (inner[i] === "\\") i++;
+ } else if ("([{".includes(c)) depth++;
+ else if (")]}".includes(c)) depth--;
+ else if (c === "," && depth === 0) {
+ list.push(inner.slice(start, i).trim());
+ start = i + 1;
+ }
+ }
+ if (inner.slice(start).trim()) list.push(inner.slice(start).trim());
+ return { list, end };
+}
+
+/** Applies `f` to the code between strings, templates and comments, leaving their contents as written. */
+function inCode(code: string, f: (part: string) => string): string {
+ let out = "";
+ let from = 0;
+ for (let i = 0; i < code.length; i++) {
+ const c = code[i];
+ let end = -1;
+ if (c === '"' || c === "'" || c === "`") {
+ let j = i + 1;
+ for (; j < code.length && code[j] !== c; j++) if (code[j] === "\\") j++;
+ end = j + 1;
+ } else if (c === "/" && code[i + 1] === "/") {
+ end = code.indexOf("\n", i);
+ if (end < 0) end = code.length;
+ }
+ if (end < 0) continue;
+ out += f(code.slice(from, i)) + code.slice(i, end);
+ from = i = end;
+ i--;
+ }
+ return out + f(code.slice(from));
+}
+
+/** Rewrites every `name(` call in `code` with `f(args, start, end)`; returning undefined keeps the call. */
+function eachCall(code: string, name: string, f: (a: string[], start: number) => string | undefined): string {
+ let out = "";
+ let from = 0;
+ for (let i = code.indexOf(name + "(", from); i >= 0; i = code.indexOf(name + "(", from)) {
+ // a member call is not this one; a spread's `...` is not a member access
+ if (/[\w$]/.test(code[i - 1] ?? "") || (code[i - 1] === "." && code.slice(i - 3, i) !== "...")) {
+ out += code.slice(from, i + name.length);
+ from = i + name.length;
+ continue;
+ }
+ const open = i + name.length;
+ const { list, end } = args(code, open);
+ const r = f(list, i);
+ out += code.slice(from, i) + (r ?? code.slice(i, end));
+ from = end;
+ }
+ return out + code.slice(from);
+}
+
+/** The index just past the JSX element whose `<` is at `i`, or -1 if it is not one. */
+function elementEnd(code: string, i: number): number {
+ const open = /^<([A-Za-z][\w.$-]*)/.exec(code.slice(i));
+ if (!open) return -1;
+ let depth = 0;
+ for (let j = i; j < code.length; j++) {
+ const c = code[j];
+ if (c === "{") {
+ j = close(code, j) - 1;
+ continue;
+ }
+ if (c !== "<") continue;
+ const tag = /^<(\/?)([A-Za-z][\w.$-]*)?/.exec(code.slice(j))!;
+ if (tag[1] === "/") {
+ if (!tag[2] && code.slice(j, j + 3) === ">") return -1;
+ depth--;
+ j = code.indexOf(">", j);
+ if (depth === 0) return j + 1;
+ continue;
+ }
+ if (!tag[2]) return -1;
+ // the rest of the tag: attributes with their expressions, up to `>` or `/>`
+ let k = j + tag[0].length;
+ for (; k < code.length && code[k] !== ">"; k++) {
+ if (code[k] === "{") k = close(code, k) - 1;
+ else if (code[k] === '"' || code[k] === "'") k = code.indexOf(code[k], k + 1);
+ }
+ if (code[k - 1] === "/") {
+ if (depth === 0) return k + 1;
+ } else depth++;
+ j = k;
+ }
+ return -1;
+}
+/** `open X close` → `X` where X is one JSX element and `keep(at)` allows it. */
+function unwrapOne(code: string, open: string, closer: string, keep: (code: string, at: number) => boolean): string {
+ for (let i = code.indexOf(open); i >= 0; i = code.indexOf(open, i + 1)) {
+ const start = i + open.length + (/^\s*/.exec(code.slice(i + open.length))![0].length);
+ if (code[start] !== "<" || code[start + 1] === ">" || code[start + 1] === "/") continue;
+ const end = elementEnd(code, start);
+ if (end < 0) continue;
+ const rest = /^\s*/.exec(code.slice(end))![0].length;
+ if (code.slice(end + rest, end + rest + closer.length) !== closer || !keep(code, i)) continue;
+ code = code.slice(0, i) + code.slice(start, end) + code.slice(end + rest + closer.length);
+ }
+ return code;
+}
+
+/** `(X)` → `X` when the parentheses wrap all of it. */
+const unparen = (x: string) => {
+ x = x.trim();
+ return x.startsWith("(") && close(x, 0) === x.length ? x.slice(1, -1).trim() : x;
+};
+const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+const unprev = (fn: string) => (/__prev/.test(fn.replace(/^\(__prev\)\s*=>/, "")) ? fn : fn.replace(/^\(__prev\)\s*=>/, "() =>"));
+const unseed = (seed: string) => {
+ const m = /^__rt\.untrack\(\(\) => ([\s\S]*)\)$/.exec(seed);
+ if (!m) return seed;
+ const value = unparen(m[1]);
+ // createSignal(fn) would derive from fn, so a function-valued seed keeps its untrack
+ return /^(\([^)]*\)\s*=>|\w+\s*=>|function|async)/.test(value) ? seed : value;
+};
+
+/** The index of the `;` (or closing `}`) that ends the statement running from `from`. */
+function statementEnd(code: string, from: number): number {
+ for (let i = from; i < code.length; i++) {
+ const c = code[i];
+ if (c === '"' || c === "'" || c === "`") {
+ for (i++; i < code.length && code[i] !== c; i++) if (code[i] === "\\") i++;
+ } else if ("([{".includes(c)) i = close(code, i) - 1;
+ else if (c === ";" || c === "}") return i;
+ }
+ return code.length;
+}
+/** The `{` of the innermost block around `at`. */
+function enclosing(code: string, at: number): number {
+ for (let o = at - 1; o >= 0; o--) if (code[o] === "{" && close(code, o) > at) return o;
+ return -1;
+}
+/** The last `return` directly in the block whose `{` is at `open`. */
+function lastReturn(code: string, open: number): number {
+ const end = close(code, open) - 1;
+ let found = -1;
+ for (let i = open + 1; i < end; i++) {
+ const c = code[i];
+ if (c === '"' || c === "'" || c === "`") {
+ for (i++; i < end && code[i] !== c; i++) if (code[i] === "\\") i++;
+ } else if ("([{".includes(c)) i = close(code, i) - 1;
+ else if (/^return\b/.test(code.slice(i, i + 7)) && !/[\w$.]/.test(code[i - 1])) found = i;
+ }
+ return found;
+}
+
+/** `context c = d`, `use c` and `provide c = e` (07): Solid's createContext, useContext and the context as provider. */
+function contexts(code: string, used: Set): string {
+ const names = new Set();
+ for (const m of code.matchAll(/__rt\.(?:context\("([\w$]+)"|useGet\(([\w$]+),|provide\(([\w$]+),)/g)) names.add((m[1] ?? m[2] ?? m[3]).replace(/^v\$/, ""));
+ if (!names.size) return code;
+ code = eachCall(code, "__rt.context", (a) => (used.add("createContext"), `createContext(${a[1] === "null" ? "" : a[1]})`));
+ code = eachCall(code, "__rt.useGet", (a) => (used.add("useContext"), `useContext(${a[0]})()`));
+ for (let i = code.indexOf("__rt.provide("); i >= 0; i = code.indexOf("__rt.provide(", i + 1)) {
+ const { list, end } = args(code, i + "__rt.provide".length);
+ // the entry's `w` is the source's writer, for the runtime's registry; a reader takes only the value
+ const fields = (list[1] ?? "").startsWith("{") ? args(list[1], 0).list : [];
+ const g = fields.map((f) => /^get:\s*([\s\S]*)$/.exec(f)).find(Boolean);
+ const v = fields.map((f) => /^value:\s*([\s\S]*)$/.exec(f)).find(Boolean);
+ // `{ get: memo }`: the memo's function is the accessor the context carries
+ const memo = g && /^(__rt\.memo|createMemo)\(/.exec(g[1]);
+ const inner = memo && close(g[1], memo[1].length) === g[1].length ? args(g[1], memo[1].length).list : undefined;
+ const value = inner ? (memo![1] === "createMemo" ? inner[0] : unprev(inner[1] ?? "")) : g ? g[1] : v ? `() => ${v[1]}` : undefined;
+ const open = enclosing(code, i);
+ const ret = open < 0 ? -1 : lastReturn(code, open);
+ if (value === undefined || ret < 0) continue;
+ const from = code.lastIndexOf("\n", i) + 1;
+ const to = code[end] === ";" ? end + 1 : end;
+ const xEnd = statementEnd(code, ret + "return".length);
+ const x = unparen(code.slice(ret + "return".length, xEnd));
+ const wrapped = `return (\n<${list[0]} value={${value}}>\n${x.startsWith("<") ? x : `{${x}}`}\n${list[0]}>\n)`;
+ code = ret > i ? code.slice(0, from) + code.slice(to, ret) + wrapped + code.slice(xEnd) : code.slice(0, ret) + wrapped + code.slice(xEnd, from) + code.slice(to);
+ i = from - 1;
+ }
+ // a context is its own provider component, so its name is capitalized
+ for (const n of names) {
+ const e = n.replace(/\$/g, "\\$");
+ code = code.replace(new RegExp(`(__i\\d+\\[)"${e}"\\]`, "g"), `$1"${cap(n)}Context"]`);
+ code = inCode(code, (part) => part.replace(new RegExp(`(? m` (R-f-1) as a class, `throw E(a)` as `throw new E(a)`, and a typed catch or boundary by instanceof. */
+function errorClasses(code: string): string {
+ const names: string[] = [];
+ for (let i = code.indexOf("function g$"); i >= 0; i = code.indexOf("function g$", i + 1)) {
+ const m = /^function g\$([\w$]+)\(__rt\) \{/.exec(code.slice(i));
+ if (!m) continue;
+ const end = close(code, i + m[0].length - 1);
+ const at = code.indexOf("__rt.errorClass(", i);
+ if (at < 0 || at > end) continue;
+ const a = args(code, at + "__rt.errorClass".length).list;
+ const fn = /^\(([^)]*)\)\s*=>\s*([\s\S]*)$/.exec(a[2] ?? "");
+ let fields: string[];
+ try {
+ fields = JSON.parse(a[1] ?? "[]");
+ } catch {
+ continue;
+ }
+ if (!fn) continue;
+ const name = m[1];
+ const ps = fn[1].split(",").map((s) => s.trim()).filter(Boolean);
+ const cls = [`class ${name} extends Error {`, `constructor(${ps.join(", ")}) {`, `super(${unparen(fn[2])});`, `this.name = ${JSON.stringify(name)};`, ...fields.map((f, k) => `this.${f} = ${ps[k] ?? "undefined"};`), "}", "}"].join("\n");
+ const lead = `let c$${name};\n`;
+ const from = code.slice(i - lead.length, i) === lead ? i - lead.length : i;
+ code = code.slice(0, from) + cls + code.slice(end);
+ names.push(name);
+ i = from;
+ }
+ for (const n of names) code = code.replace(new RegExp(`^[ \\t]*const (?:v\\$)?${n} = g\\$${n}\\(__rt\\);\\n`, "m"), "");
+ // an error a JavaScript module declares (a .d.rx `error`) is its class, imported by name
+ for (const m of code.matchAll(/^[ \t]*const (?:v\$)?([\w$]+) = __rt\.jsError\("[\w$]+"\);$/gm)) names.push(m[1]);
+ for (const n of names) code = inCode(code, (part) => part.replace(new RegExp(`(? (close(`(${e})`, 0) === e.length + 2 ? `${ind}if (${c}) throw ${e};\n${ind}return ${x};` : all));
+ code = eachCall(code, "__rt.throw", (a) => `(() => {\nthrow ${a[0]};\n})()`);
+ code = eachCall(code, "__rt.isA", (a) => {
+ const cs = /^\[([\w$,\s]+)\]$/.exec(a[1] ?? "");
+ return cs ? `(${cs[1].split(",").map((c) => c.trim()).filter(Boolean).map((c) => `${a[0]} instanceof ${c}`).join(" || ")})` : undefined;
+ });
+ // `await e -> v` (R-7): Solid's loadingValue. A question only the browser answers (SV-7b) is ssrSource "client"
+ code = eachCall(code, "__rt.firstPaint", (a) => {
+ const f = /^\(\)\s*=>\s*([\s\S]*)$/.exec(a[0] ?? "");
+ return f && !f[1].trim().startsWith("{") ? `{ loadingValue: ${unparen(f[1])} }` : undefined;
+ });
+ code = eachCall(code, "__rt.clientQuestion", (a) => {
+ const o = (a[0] ?? "").trim();
+ if (!o || o === "undefined") return `{ ssrSource: "client" }`;
+ return o.startsWith("{") && o.endsWith("}") ? `{ ${o.slice(1, -1).trim().replace(/,$/, "")}, ssrSource: "client" }` : undefined;
+ });
+ // `x catch (e: C) => alt` (R-f-4, 07): what it matches, as a test on the alternative's parameter
+ const caught = (match: string, alt: string) => {
+ const f = /^\(([\w$]+)\)\s*=>\s*([\s\S]*)$/.exec(alt.trim());
+ const m = /^\(([\w$]+)\)\s*=>\s*([\s\S]*)$/.exec(match.trim());
+ if (!f || !m) return;
+ const p = f[1] === "__e" ? "e" : f[1];
+ const any = /^__rt\.isA\([\w$]+, undefined\)$/.test(m[2].trim());
+ if (!any && /__rt\./.test(m[2])) return;
+ const test = any ? undefined : unparen(m[2].replace(new RegExp(`\\b${m[1].replace(/\$/g, "\\$")}\\b`, "g"), p));
+ return { p, test, body: unparen(f[2].replace(/\b__e\b/g, p)) };
+ };
+ // on an awaited answer: the promise's own catch, which throws the other classes on
+ code = eachCall(code, "__rt.settle", (a) => {
+ const c = caught(a[1] ?? "", a[2] ?? "");
+ if (!c) return undefined;
+ const on = /^[\w$.]+(\([^()]*\))?$/.test(a[0]) ? a[0] : `(${a[0]})`;
+ return c.test ? `${on}.catch((${c.p}) => {\nif (!(${c.test})) throw ${c.p};\nreturn ${c.body};\n})` : `${on}.catch((${c.p}) => ${c.body})`;
+ });
+ // on a read: a try that lets Solid's NotReadyError through, so a pending read stays pending
+ const tried = (f: string, c: NonNullable>) => {
+ const r = /^\(\)\s*=>\s*([\s\S]*)$/.exec(f.trim());
+ const read = r && !r[1].trim().startsWith("{") ? `return ${r[1]};` : `return (${f})();`;
+ return `try {\n${read}\n} catch (${c.p}) {\nif (${c.p} instanceof NotReadyError${c.test ? ` || !(${c.test})` : ""}) throw ${c.p};\nreturn ${c.body};\n}`;
+ };
+ code = eachCall(code, "__rt.catchMemo", (a) => {
+ const c = caught(a[1] ?? "", a[2] ?? "");
+ return c ? `__rt.memo(null, () => {\n${tried(a[0], c)}\n})` : undefined;
+ });
+ for (const h of ["__rt.catchRead", "__rt.tryCatch"])
+ code = eachCall(code, h, (a) => {
+ const c = caught(a[1] ?? "", a[2] ?? "");
+ return c ? `(() => {\n${tried(a[0], c)}\n})()` : undefined;
+ });
+
+ // a typed boundary (R-f-4) is an Errored whose fallback throws other classes on, to the boundary above it
+ for (let i = code.indexOf("<__rt.TypedErrored"); i >= 0; i = code.indexOf("<__rt.TypedErrored", i + 1)) {
+ let k = i + "<__rt.TypedErrored".length;
+ for (; k < code.length && code[k] !== ">"; k++) if (code[k] === "{") k = close(code, k) - 1;
+ const tag = code.slice(i, k);
+ const attr = (n: string) => {
+ const m = new RegExp(`\\s${n}=\\{`).exec(tag);
+ const o = m ? i + m.index + m[0].length - 1 : -1;
+ return o < 0 ? undefined : code.slice(o + 1, close(code, o) - 1).trim();
+ };
+ const cs = /^\[([\w$,\s]+)\]$/.exec(attr("classes") ?? "");
+ const fb = /^\(([\w$]+)\)\s*=>\s*([\s\S]*)$/.exec(attr("fallback") ?? "");
+ if (!cs || !fb) continue;
+ const p = fb[1] === "__err" ? "err" : fb[1];
+ const test = cs[1].split(",").map((c) => `${p}() instanceof ${c.trim()}`).join(" || ");
+ code = code.slice(0, i) + ` {\nif (!(${test})) throw ${p}();\nreturn ${fb[2].replace(/\b__err\b/g, p)};\n}}` + code.slice(k);
+ }
+ return code.replace(/<\/__rt\.TypedErrored>/g, " ");
+}
+
+export function solidify(code: string): string {
+ const used = new Set();
+ const optimistic = new Set();
+ const stores = new Set();
+ // a source's setter is setX, unless the module already has that name (an action `setX`, say): then setXValue
+ const taken = new Set([...code.matchAll(/\b(?:const|let|function|class) (?:[vw]\$)?([\w$]+)/g)].map((m) => m[1]));
+ for (const m of code.matchAll(/^import \{([^}]*)\}/gm)) for (const x of m[1].split(",")) taken.add(x.trim().split(/\s+as\s+/).pop()!.replace(/^[vw]\$/, ""));
+ const setter = (n: string) => (taken.has(`set${cap(n)}`) ? `set${cap(n)}Value` : `set${cap(n)}`);
+
+ // import aliases: `import { f as w$f }` and `const v$f = w$f;` are one name
+ code = code.replace(/(\w+) as w\$\1\b/g, "$1").replace(/^\s*const v\$(\w+) = w\$\1;\n/gm, "");
+ // at the module's top level (a server fn's body) an import is still read by its alias
+ const imported = [...code.matchAll(/^import \{([^}]*)\} from /gm)].flatMap((m) => m[1].split(",").map((x) => x.trim().split(/\s+as\s+/).pop()!)).filter(Boolean);
+ for (const n of imported) code = inCode(code, (part) => part.replace(new RegExp(`\\bw\\$${n}\\b`, "g"), n));
+ // `server fn f(a) { … }` (12 SF-1): Solid's "use server" function. Its body arrives as a generator handed to the
+ // runtime, each await a yield
+ for (let i = code.indexOf("async function sf$"); i >= 0; i = code.indexOf("async function sf$", i + 1)) {
+ const head = /^async function sf\$(\w+?)(\$\d+)?\(\.\.\.__a\) /.exec(code.slice(i));
+ if (!head) continue;
+ const open = i + head[0].length;
+ const end = close(code, open);
+ const call = code.indexOf("__rt.serverCall(", open);
+ if (call < 0 || call > end) continue;
+ const gen = args(code, call + "__rt.serverCall".length).list[1] ?? "";
+ const p = gen.indexOf("(");
+ const pe = p < 0 ? -1 : close(gen, p);
+ const b = pe < 0 ? -1 : gen.indexOf("{", pe);
+ if (!gen.startsWith("function*") || b < 0) continue;
+ const body = inCode(gen.slice(b + 1, close(gen, b) - 1), (part) => part.replace(/\byield\b/g, "await"));
+ code = code.slice(0, i) + `async function ${head[2] ? "" : head[1]}(${gen.slice(p + 1, pe - 1)}) {\n"use server";${body}}` + code.slice(end);
+ }
+ // the name a server fn is called by is the function itself
+ code = code.replace(/^[ \t]*const v\$(\w+) = __rt\.serverRef\("\1", sf\$\1\);\n/gm, "").replace(/\bsf\$(\w+)\b/g, "$1");
+ code = contexts(code, used);
+ code = errorClasses(code);
+ code = code.replace(/^[ \t]*__rt\.reg\([^;]*\);\n/gm, "").replace(/^[ \t]*__rt\.hoisted\([^;]*\);\n/gm, "");
+ if ((code.match(/\b__o\b/g) ?? []).length === (code.match(/const __o = __rt\.owner\(\);/g) ?? []).length)
+ code = code.replace(/^[ \t]*const __o = __rt\.owner\(\);\n/gm, "");
+
+ code = eachCall(code, "__rt.source", (a) => {
+ const seed = unseed(a[1] ?? "undefined");
+ const prim = /^[[{]/.test(seed.trim()) ? "createStore" : "createSignal";
+ if (prim === "createStore") stores.add(JSON.parse(a[0]));
+ used.add(prim);
+ return `${prim}(${seed})`;
+ });
+ code = eachCall(code, "__rt.question", (a, at) => {
+ const [, fn, opts, mode = "", key] = a;
+ const name = JSON.parse(a[0]);
+ const flag = (f: string) => new RegExp(`\\b${f}: true`).test(mode);
+ const o = opts && opts !== "undefined" ? `, ${opts}` : "";
+ const f = unprev(fn);
+ if (flag("optimistic") && flag("structured")) return stores.add(name), used.add("createOptimisticStore"), `createOptimisticStore(${f}, ${key ? "[]" : "{}"}${key ? `, { key: ${key} }` : ""})`;
+ if (flag("optimistic") && flag("derived")) return used.add("createOptimistic"), `createOptimistic(${f}${o})`;
+ if (flag("optimistic")) {
+ // a truth signal, and the optimistic layer a guess writes over it
+ optimistic.add(name);
+ used.add("createSignal").add("createOptimistic");
+ void at;
+ return `createSignal(${f}${o})`;
+ }
+ if (flag("structured")) return stores.add(name), used.add("createStore"), `createStore(${f}, {})`;
+ used.add("createSignal");
+ return `createSignal(${f}${o})`;
+ });
+ // `const [v$x, w$x] = createSignal(fn)` with a guess: `const [x$truth, setX] = …; const [x, setOptimisticX] = createOptimistic(…)`
+ for (const name of optimistic) {
+ const decl = `const [v$${name}, w$${name}] = createSignal(`;
+ const i = code.indexOf(decl);
+ if (i < 0) continue;
+ const end = close(code, i + decl.length - 1);
+ const semi = code[end] === ";" ? end + 1 : end;
+ const ind = /[ \t]*$/.exec(code.slice(0, i))![0];
+ const call = code.slice(i + decl.length - "createSignal(".length, end);
+ code = code.slice(0, i) + `const [${name}$truth, ${setter(name)}] = ${call};\n${ind}const [${name}, setOptimistic${cap(name)}] = createOptimistic(() => ${name}$truth());` + code.slice(semi);
+ }
+
+ // `x key k = e` (ST-4): the answer as a memo, and a projection over it that keeps each row by its key
+ for (let i = code.indexOf("const v$"); i >= 0; i = code.indexOf("const v$", i + 1)) {
+ const m = /^const v\$(\w+) = __rt\.keyed\(/.exec(code.slice(i));
+ if (!m) continue;
+ const { list, end } = args(code, i + m[0].length - 1);
+ const semi = code[end] === ";" ? end + 1 : end;
+ const ind = /[ \t]*$/.exec(code.slice(0, i))![0];
+ const name = m[1];
+ stores.add(name);
+ used.add("createMemo").add("createProjection");
+ code = code.slice(0, i) + `const ${name}$answer = createMemo(${list[2]});\n${ind}const v$${name} = createProjection(() => ${name}$answer(), [], { key: ${list[1]} });` + code.slice(semi);
+ }
+ // `x = draft(pre x -> seed) { … }` (ST-3): a projection whose function writes its draft
+ for (let i = code.indexOf("const v$"); i >= 0; i = code.indexOf("const v$", i + 1)) {
+ const m = /^const v\$(\w+) = __rt\.draft\(/.exec(code.slice(i));
+ if (!m) continue;
+ const { list, end } = args(code, i + m[0].length - 1);
+ stores.add(m[1]);
+ used.add("createProjection");
+ code = code.slice(0, i) + `const v$${m[1]} = createProjection(${list[1]}, ${unseed(list[0])})` + code.slice(end);
+ }
+ // a draft write: `{ let __t = d; __t[k] = v; }` is `d[k] = v;`
+ code = code.replace(/\{\s*let __t = ([\w$]+);\s*__t((?:\[[^\n]*?\]|\.\w+)+) = ([^;\n]+);\s*\}/g, "$1$2 = $3;");
+ // Prettier breaks a long chain after `__rt`: join it back, so each helper is found by its name
+ code = code.replace(/\b__rt\s+\./g, "__rt.");
+ // a template part and `str` format alike
+ code = code.replace(/\b__B\.str\(|\b__rt\.fmt\(/g, "String(");
+
+ code = eachCall(code, "__rt.memo", (a) => {
+ // `...rest` in a prop pattern: Solid's omit is already a live view of props, so the memo around it adds nothing
+ const omitted = /^\(__prev\)\s*=>\s*__rt\.omit\(([\s\S]*)\)$/.exec(a[1]);
+ if (omitted && close(a[1], a[1].indexOf("__rt.omit(") + 9) === a[1].length) {
+ stores.add(JSON.parse(a[0]));
+ used.add("omit");
+ return `omit(${omitted[1]})`;
+ }
+ used.add("createMemo");
+ return `createMemo(${unprev(a[1])}${a[2] && a[2] !== "undefined" ? `, ${a[2]}` : ""})`;
+ });
+ // `deferred x = e` (V-16): a memo that lags its inputs on purpose
+ code = eachCall(code, "__rt.deferred", (a) => {
+ used.add("createDeferred");
+ return `createDeferred(${unprev(a[1])}${a[2] && a[2] !== "undefined" ? `, ${a[2]}` : ""})`;
+ });
+ code = code.replace(/!__rt\.eq\(/g, "__rt.neq(");
+ code = eachCall(code, "__rt.neq", (a) => `((${a[0]}) !== (${a[1]}))`);
+ code = eachCall(code, "__rt.eq", (a) => `((${a[0]}) === (${a[1]}))`);
+ code = eachCall(code, "__rt.awaited", (a) => a[0]);
+ code = eachCall(code, "__rt.show", (a) => a[0]);
+ code = eachCall(code, "__rt.snapshot", (a) => (used.add("untrack"), `untrack(${a[0]})`));
+ code = eachCall(code, "__rt.refresh", (a) => (used.add("refresh"), `refresh(${a[1]})`));
+ code = eachCall(code, "__rt.scopedClass", (a) => `[${a[0]}, ${a[1]}]`);
+ // `__rt.effect(n, () => [a(), b()], ($p) => untrack(() => { … $p[0] … }))` (EF-1): Solid's createEffect, whose
+ // second function is not tracked and takes what the first returned, here named as the .rx names them
+ code = eachCall(code, "__rt.effect", (a) => {
+ const n = Number(a[0]);
+ const apply = /^\(\$p\)\s*=>\s*(?:__rt\.)?untrack\(/.exec(a[2] ?? "");
+ const list = a[1]?.indexOf("[") ?? -1;
+ if (!apply || list < 0 || !Number.isInteger(n)) return undefined;
+ const inner = args(a[2], apply[0].length - 1).list[0] ?? "";
+ const body = /^\(\)\s*=>\s*([\s\S]*)$/.exec(inner);
+ if (!body) return undefined;
+ const inputs = args(a[1], list).list;
+ const read = n === 0 ? "() => {}" : n === 1 ? `() => ${inputs[0]}` : `() => [${inputs.join(", ")}]`;
+ const params = n === 0 ? "()" : n === 1 ? "($0)" : `([${inputs.map((_, i) => `$${i}`).join(", ")}])`;
+ used.add("createEffect");
+ return `createEffect(${read}, ${params} => ${body[1].replace(/\$p\[(\d+)\]/g, "$$$1")})`;
+ });
+ for (const h of ["untrack", "latest", "isPending", "affects", "onFlush", "onSettled", "until", "action"])
+ code = code.replace(new RegExp(`__rt\\.${h}\\(`, "g"), () => (used.add(h), `${h}(`));
+
+ // `(() => { return X; })()`: what was left of a region's function once its owner line went
+ for (let i = code.indexOf("(() => {"); i >= 0; i = code.indexOf("(() => {", i + 1)) {
+ const bodyOpen = i + "(() => ".length;
+ const bodyEnd = close(code, bodyOpen);
+ if (code.slice(bodyEnd, bodyEnd + 3) !== ")()") continue;
+ const m = /^\{\s*return ([\s\S]*);\s*\}$/.exec(code.slice(bodyOpen, bodyEnd));
+ if (m && !/^\s*\(?\s*$/.test(m[1])) code = code.slice(0, i) + unparen(m[1]) + code.slice(bodyEnd + 3);
+ }
+
+ // `=> { return X; }` is `=> X`: innermost first, so again until an outer one has no return left inside it
+ for (let before = ""; before !== code; ) {
+ before = code;
+ for (let i = code.indexOf("=> {"); i >= 0; i = code.indexOf("=> {", i + 1)) {
+ const bodyOpen = i + 3;
+ const bodyEnd = close(code, bodyOpen);
+ const m = /^\{\s*return ([\s\S]*);\s*\}$/.exec(code.slice(bodyOpen, bodyEnd));
+ if (m && !/^\s*\(?\s*$/.test(m[1]) && !/\breturn\b/.test(m[1])) {
+ const x = unparen(m[1]);
+ code = code.slice(0, bodyOpen) + (x.startsWith("{") ? `(${x})` : x) + code.slice(bodyEnd);
+ }
+ }
+ }
+ // `{if x { … x … }}` narrows x: the branch's `n$x` is x again
+ code = code.replace(/^[ \t]*const n\$([\w$]+) = __item;\n/gm, "");
+ code = inCode(code, (part) => part.replace(/\bn\$([\w$]+)\b/g, "$1"));
+ // a branch's unused item parameter: `{(__item) => X}` is `{X}`
+ for (let i = code.indexOf("(__item) => "); i >= 0; i = code.indexOf("(__item) => ", i + 1)) {
+ const body = i + "(__item) => ".length;
+ const end = "([{".includes(code[body]) ? close(code, body) : code.indexOf("\n", body);
+ // a block body stays a function: `{{ … }}` is not JSX
+ // an inner branch's own `(__item) =>` is not a read of this one
+ if (/\b__item\b(?!\) =>)/.test(code.slice(body, end < 0 ? undefined : end))) continue;
+ code = code.slice(0, i) + (code[body] === "{" ? "() => " : "") + code.slice(body);
+ }
+ // an errored fallback that names no error is the fallback itself
+ for (let i = code.indexOf("fallback={(__err) => "); i >= 0; i = code.indexOf("fallback={(__err) => ", i + 1)) {
+ const body = i + "fallback={(__err) => ".length;
+ const end = close(code, i + "fallback=".length) - 1;
+ if (!/\b__err\b/.test(code.slice(body, end))) code = code.slice(0, i) + "fallback={" + code.slice(body);
+ }
+
+ // writers and names
+ for (const name of optimistic) code = code.replace(new RegExp(`w\\$${name}\\.guess\\(`, "g"), `setOptimistic${cap(name)}(`);
+ // a store's writer, as Solid's setter takes it: a function that changes its draft. A guess on an optimistic store is
+ // that same setter
+ const along = (name: string, keys: string, value: string) => {
+ const target = "draft" + args(keys, 0).list.map((k) => (/^"[A-Za-z_$][\w$]*"$/.test(k) ? `.${k.slice(1, -1)}` : `[${k}]`)).join("");
+ return `w$${name}.set((draft) => {\n${target} = ${/^(\([\w$]*\)|[\w$]+)\s*=>/.test(value) ? `(${value})(${target})` : value};\n})`;
+ };
+ for (const name of stores) {
+ code = eachCall(code, `w$${name}.path`, (a) => (a.length === 2 && a[0].startsWith("[") ? along(name, a[0], a[1]) : undefined));
+ code = eachCall(code, `w$${name}.guess`, (a) => {
+ if (a.length === 2 && a[1].startsWith("[")) return along(name, a[1], a[0]);
+ if (a.length !== 1) return undefined;
+ return `w$${name}.set(${/^(\([\w$]*\)|[\w$]+)\s*=>/.test(a[0]) ? a[0] : `() => ${a[0].startsWith("{") ? `(${a[0]})` : a[0]}`})`;
+ });
+ }
+ code = inCode(code, (part) =>
+ part
+ .replace(/\bw\$(\w+)\.set\(/g, (_, n) => `${setter(n)}(`)
+ .replace(/\bw\$(\w+)\b/g, (_, n) => setter(n))
+ .replace(/\ba\$(\w+)\$(\d+)\b/g, (_, n, k) => (k === "0" ? `${n}$await` : `${n}$await${k}`))
+ .replace(/\bp\$(\w+)\b/g, (_, n) => `prev${cap(n)}`)
+ .replace(/\b[vV]\$(\w+)\b/g, "$1"),
+ );
+ // a store, or omit's view of props, is read as itself, not called: within the block that declares it
+ for (const n of stores) {
+ const decl = new RegExp(`const (?:\\[${n}, \\w+\\]|${n}) = (?:create(?:Store|OptimisticStore|Projection)|omit)\\(`, "g");
+ for (const m of [...code.matchAll(decl)].reverse()) {
+ let open = (m.index ?? 0) - 1;
+ while (open >= 0 && !(code[open] === "{" && close(code, open) > (m.index ?? 0))) open--;
+ const end = open < 0 ? code.length : close(code, open);
+ const from = open < 0 ? 0 : open;
+ code = code.slice(0, from) + inCode(code.slice(from, end), (part) => part.replace(new RegExp(`(?<=^|[^\\w$.]|\\.\\.\\.)${n}\\(\\)`, "g"), n)) + code.slice(end);
+ }
+ }
+
+ // JSX text: `type={"button"}` and `{"Clear"}` as plain text where nothing changes by it
+ code = code.replace(/=\{("[^"\\{}]*")\}/g, "=$1").replace(/\{"([^"\\{}<>&\n]*[^"\\{}<>&\s])"\}/g, (all, t, at, str) => (/^\S/.test(t) ? t : all));
+ // a fragment around one element, or braces around one element, says nothing
+ for (let before = ""; before !== code; ) {
+ before = code;
+ code = unwrapOne(code, "<>", ">", () => true);
+ code = unwrapOne(code, "{", "}", (now, at) => /[>}]\s*$/.test(now.slice(0, at)));
+ }
+
+ // another module's names: `import __m0 from "./x.rx"` + `const __i0 = __rt.module(__m0, __m0); const A = __i0["B"];`
+ for (const m of [...code.matchAll(/^import (__m\d+) from ("[^"]+");\n/gm)]) {
+ const inst = new RegExp(`^[ \\t]*const (__i\\d+) = __rt\\.module\\(${m[1]}, ${m[1]}\\);\\n`, "m").exec(code);
+ if (!inst) continue;
+ const names: string[] = [];
+ code = code.replace(new RegExp(`^[ \\t]*const ([\\w$]+) = ${inst[1]}\\["([\\w$]+)"\\];\\n`, "gm"), (_, local, name) => (names.push(local === name ? name : `${name} as ${local}`), ""));
+ code = code.replace(inst[0], "").replace(m[0], names.length ? `import { ${names.join(", ")} } from ${m[2]};\n` : "");
+ }
+ // a module named ./api is the app's server: `const x = __rt.api("x")` is a name imported from it
+ const api: string[] = [];
+ code = code.replace(/^[ \t]*const ([\w$]+) = __rt\.(?:api|jsError)\("([\w$]+)"\);\n/gm, (_, local, name) => (api.push(local === name ? name : `${name} as ${local}`), ""));
+ if (api.length) code = `import { ${api.join(", ")} } from "./api";\n` + code;
+ // `log` is the one builtin JavaScript has a name for: the console's. A module that imported the name gets the same
+ const logs = new Set();
+ code = code.replace(/^[ \t]*const ([\w$]+) = __B\.log;\n/gm, (_, n) => (logs.add(n), ""));
+ for (const n of logs) code = inCode(code, (part) => part.replace(new RegExp(`(? \{([\s\S]*)\breturn ([\s\S]*?);\s*\};\s*\}\s*$/.exec(code);
+ if (wrap && !/__rt|__B/.test(wrap[1] + wrap[2])) {
+ const one = /^\(?\s*(?:<>\s*)?<(\w+) children=\{\[\]\} \/>\s*(?:<\/>\s*)?\)?$/.exec(wrap[2].trim());
+ // a module-level provide wraps the app: the root is a component of its own
+ code = code.slice(0, wrap.index) + wrap[1].replace(/^\t\t/gm, "") + (one ? `export default ${one[1]};\n` : `export default function Root() {\nreturn ${wrap[2].trim()};\n}\n`);
+ }
+
+ // a component used with no children is passed none, not an empty list
+ code = inCode(code, (part) => part.replace(/\s+children=\{\[\]\}(?=\s*\/?>)/g, ""));
+ // a provided value is an accessor, so `use c` alone is what useContext returns
+ code = code.replace(/createMemo\(\(\) => (useContext\([\w$]+\))\(\)\)/g, "$1");
+ for (const n of used) if (!new RegExp(`\\b${n}\\(`).test(code)) used.delete(n);
+ if (/\binstanceof NotReadyError\b/.test(code)) used.add("NotReadyError");
+ for (const c of ["Errored", "Loading", "For", "Show", "Repeat"]) if (new RegExp(`<${c}[\\s>]`).test(code)) used.add(c);
+ const head = used.size ? `import { ${[...used].sort().join(", ")} } from "solid-js";\n` : "";
+ return head + code;
+}
diff --git a/site/playground/src/style.css b/site/playground/src/style.css
new file mode 100644
index 00000000..e7219619
--- /dev/null
+++ b/site/playground/src/style.css
@@ -0,0 +1,140 @@
+/* palette and type from reactivescript.dev (site/index.html) */
+:root {
+ --bg: #0c1829;
+ --tile: #12233d;
+ --panel: #15294a;
+ --line: #23406b;
+ --text: #e8eef7;
+ --muted: #9fb2cc;
+ --blue: #5b9be6;
+ --amber: #f0b44c;
+ --red: #ff8a80;
+ --green: #a8d59b;
+ --violet: #c9a7f2;
+ --comment: #6f86a6;
+ --mono: ui-monospace, "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace;
+ --sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ color-scheme: dark;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 15px/1.5 var(--sans); }
+a { color: var(--blue); text-decoration: none; }
+a:hover { text-decoration: underline; }
+button, select, input { font: inherit; color: inherit; }
+#app { height: 100%; }
+.loading { color: var(--muted); padding: 12px 16px; }
+.loading p { margin: 0 0 8px; }
+.loading pre.err { margin: 0 0 10px; }
+.diags p.loading { padding: 0; margin: 8px 0 0; font-size: 14px; min-height: 1.5em; }
+
+.shell { display: flex; flex-direction: column; height: 100%; }
+.bar { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; padding: 10px 16px; border-bottom: 1px solid var(--line); background: var(--tile); }
+.brand { display: flex; align-items: center; gap: 10px; color: var(--text); font-weight: 600; letter-spacing: -0.01em; }
+.brand:hover { text-decoration: none; }
+.brand b { color: var(--amber); font-weight: 600; }
+.field { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 13px; }
+select { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 5px 8px; }
+.spacer { flex: 1; }
+.ms { font: 12px var(--mono); color: var(--muted); }
+.btn { padding: 6px 14px; border-radius: 9px; border: 1px solid var(--line); background: none; font-weight: 600; cursor: pointer; }
+.btn.primary { background: var(--blue); border-color: var(--blue); color: var(--bg); }
+.blurb { margin: 0; padding: 8px 16px; color: var(--muted); border-bottom: 1px solid var(--line); font-size: 14px; }
+
+.grid { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr); }
+.grid[hidden] { display: none; }
+.pane { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
+.editor-pane { border-right: 1px solid var(--line); }
+
+.tabs { flex: none; box-sizing: border-box; height: 42px; display: flex; align-items: flex-end; gap: 2px; padding: 6px 10px 0; border-bottom: 1px solid var(--line); overflow-x: auto; }
+.tab { display: inline-flex; align-items: center; background: none; border: 1px solid transparent; border-bottom: 0; border-radius: 8px 8px 0 0; padding: 0; color: var(--muted); font: 13px var(--mono); cursor: pointer; white-space: nowrap; }
+.tabs > button.tab, .tab > button { background: none; border: 0; padding: 6px 12px; cursor: pointer; color: inherit; font: inherit; }
+.tab.on { background: var(--tile); border-color: var(--line); color: var(--text); margin-bottom: -1px; padding-bottom: 1px; }
+.tab .x { padding: 6px 8px 6px 0; color: var(--muted); }
+.tab.add { padding: 6px 10px; }
+
+.editor { position: relative; flex: 1 1 auto; min-height: 200px; background: var(--tile); }
+.editor textarea, .editor .backdrop {
+ position: absolute; inset: 0; margin: 0; padding: 14px 16px; border: 0; overflow: auto;
+ font: 14px/1.6 var(--mono); font-variant-ligatures: none; tab-size: 2; white-space: pre; word-wrap: normal;
+}
+.editor textarea { background: transparent; color: transparent; caret-color: var(--text); resize: none; outline: none; }
+.editor textarea::selection { background: rgba(91, 155, 230, 0.35); color: transparent; }
+.editor .backdrop { color: var(--text); pointer-events: none; }
+.hover { position: absolute; z-index: 3; max-width: min(560px, calc(100% - 12px)); padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); pointer-events: none; }
+.hover pre { margin: 0; font: 12.5px/1.5 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
+.hover p { margin: 6px 0 0; padding-top: 6px; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; white-space: pre-wrap; }
+.complete { position: absolute; z-index: 4; list-style: none; margin: 0; padding: 4px; min-width: 180px; max-width: 360px; max-height: 208px; overflow: auto; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); font: 13px/1.5 var(--mono); }
+.complete li { display: flex; justify-content: space-between; gap: 16px; padding: 2px 8px; border-radius: 5px; cursor: pointer; white-space: nowrap; }
+.complete li.on { background: var(--blue); color: var(--bg); }
+.complete li i { font-style: normal; font-size: 11.5px; color: var(--muted); }
+.complete li.on i { color: var(--bg); }
+.sq { text-decoration: underline wavy var(--red); text-decoration-skip-ink: none; text-underline-offset: 3px; }
+.eline.bad { background: rgba(255, 138, 128, 0.12); box-shadow: inset 3px 0 var(--red); display: inline-block; min-width: 100%; }
+.hl-k { color: var(--blue); } .hl-w { color: var(--amber); } .hl-s { color: var(--green); } .hl-c { color: var(--comment); } .hl-t { color: var(--violet); }
+
+.label { font: 600 12px var(--sans); text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); }
+.label .hint { text-transform: none; letter-spacing: 0; font-weight: 400; margin-left: 6px; }
+.diags { flex: 0 0 auto; max-height: 40%; min-height: 96px; overflow: auto; padding: 10px 16px 14px; border-top: 1px solid var(--line); }
+.diags ul { list-style: none; margin: 8px 0 0; padding: 0; }
+.diags li { padding: 8px 0; border-bottom: 1px solid var(--line); font-size: 14px; }
+.diags .where { background: none; border: 0; padding: 0; color: var(--muted); font: 12px var(--mono); cursor: pointer; margin-right: 8px; }
+.diags .where:hover { color: var(--text); text-decoration: underline; }
+.diags .code { font: 600 12px var(--mono); color: var(--red); margin-right: 6px; }
+.diags .rule { font: 12px var(--mono); color: var(--amber); margin-right: 8px; }
+.diags .msg { display: block; margin-top: 2px; }
+.diags .ok { color: var(--green); margin: 8px 0 0; font-size: 14px; }
+.count { display: inline-block; min-width: 20px; padding: 0 6px; margin-left: 6px; border-radius: 10px; background: var(--panel); color: var(--green); text-align: center; }
+.count.bad { color: var(--red); }
+
+.out-head { flex: none; box-sizing: border-box; min-height: 42px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 6px 16px; border-bottom: 1px solid var(--line); }
+.cl { min-height: 1.55em; }
+.cl.link { cursor: pointer; }
+.cl.link:hover { background: rgba(91, 155, 230, 0.08); }
+.cl.on { background: rgba(91, 155, 230, 0.18); }
+.explain { padding: 6px 16px 16px; border-top: 1px solid var(--line); }
+table.map { width: 100%; border-collapse: collapse; margin: 6px 0 0; font-size: 13px; }
+table.map th, table.map td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
+table.map th { color: var(--muted); font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
+table.map td:first-child { white-space: nowrap; }
+table.map code { font: 12px var(--mono); background: var(--panel); padding: 1px 5px; border-radius: 5px; }
+.out-head .hint { color: var(--muted); font-size: 13px; }
+.output { flex: 1 1 auto; min-height: 160px; overflow: auto; background: var(--tile); }
+.output.stale { opacity: 0.55; }
+.stale-note { margin: 0; padding: 6px 16px; background: #1d1626; color: var(--red); font-size: 13px; border-bottom: 1px solid #5a2a33; }
+pre.code { margin: 0; padding: 14px 16px; font: 13px/1.55 var(--mono); font-variant-ligatures: none; tab-size: 2; white-space: pre; }
+
+pre.err { margin: 8px 16px; padding: 10px 12px; border: 1px solid #5a2a33; background: #1d1626; color: var(--red); border-radius: 10px; white-space: pre-wrap; font: 12px/1.5 var(--mono); max-height: 160px; overflow: auto; }
+.diags pre.err { margin: 8px 0 0; }
+.checks { list-style: none; margin: 8px 0 0; padding: 0; }
+.checks li { padding: 8px 0; border-top: 1px solid var(--line); font-size: 14px; }
+.checks .where { color: var(--muted); font: 12px var(--mono); margin-right: 8px; }
+.checks .code { font: 600 12px var(--mono); color: var(--red); margin-right: 6px; }
+.checks .rule { font: 12px var(--mono); color: var(--amber); margin-right: 8px; }
+.checks .msg { display: block; margin-top: 2px; }
+.explain .ok { color: var(--green); margin: 8px 0 0; font-size: 14px; }
+.btn:disabled { opacity: 0.45; cursor: default; }
+a.btn { color: var(--text); font-size: 13px; padding: 4px 10px; }
+a.btn:hover { text-decoration: none; border-color: var(--blue); }
+.btn.off { opacity: 0.45; cursor: default; font-size: 13px; padding: 4px 10px; }
+.out-head .btn { font-size: 13px; padding: 3px 10px; border-radius: 7px; }
+pre.code.helper { padding: 10px 0 0; }
+
+/* highlight.js tokens in the site's colours */
+.hljs-keyword, .hljs-built_in, .hljs-literal { color: var(--blue); }
+.hljs-string, .hljs-regexp { color: var(--green); }
+.hljs-comment { color: var(--comment); font-style: italic; }
+.hljs-number { color: var(--amber); }
+.hljs-title, .hljs-title.function_ { color: #e8c58a; }
+.hljs-attr, .hljs-property { color: #9fd0f0; }
+.hljs-tag, .hljs-name, .hljs-selector-class, .hljs-selector-tag { color: var(--violet); }
+.hljs-variable, .hljs-params { color: var(--text); }
+
+@media (max-width: 900px) {
+ html, body, #app, .shell { height: auto; }
+ .grid { display: block; }
+ .pane { min-height: auto; }
+ .editor-pane { border-right: 0; border-bottom: 1px solid var(--line); }
+ .editor { flex: none; height: 360px; }
+ .diags { max-height: none; }
+ .output { flex: none; height: 440px; }
+ }
diff --git a/site/playground/src/torx.ts b/site/playground/src/torx.ts
new file mode 100644
index 00000000..287c21bd
--- /dev/null
+++ b/site/playground/src/torx.ts
@@ -0,0 +1,1539 @@
+// Solid 2.0 written back as .rx: the inverse of solidify, for the forms that view produces. A prototype: what it
+// does not recognise is reported with its line, never guessed.
+
+type Node = { type: string; start: number; end: number; loc?: { start: { line: number } }; [k: string]: any };
+export type RxProblem = { line: number; message: string };
+
+type Binding =
+ | { kind: "read" } // a signal or memo accessor: `x()` is `x`
+ | { kind: "store" } // read as itself
+ | { kind: "await"; text: string } // `x$await()`: the hoisted await, written back in place
+ | { kind: "setter"; of: string; guess?: boolean }
+ | { kind: "import"; from: string; async?: boolean; asyncMembers?: Set } // async: declared so in this file, so a reactive call is an await
+ | { kind: "handler"; fn: Node } // a setup function that writes or has statements: an action
+ | { kind: "mutable" } // a `let` in a component's setup: a source (.rx has no other writable name there), read by peek in reactive scope
+ | { kind: "equation" } // a module's own declaration: read as itself, and a reactive read
+ | { kind: "server" } // a "use server" function: a call from reactive scope is an await (12 SF-2)
+ | { kind: "input"; as: string } // an effect's parameter: its input, by position ($0, $1)
+ | { kind: "error" } // `class E extends Error`: an error declaration (R-f-1); `new E(a)` is `E(a)`
+ | { kind: "context"; as: string } // `createContext(…)`: a context (07), named as .rx names it
+ | { kind: "plain" };
+
+const SOLID = new Set(["solid-js", "@solidjs/web", "solid-js/store"]);
+const INDENT = " ";
+// .rx has no ambient names: what JavaScript gives every module is imported like anything else
+const GLOBALS = new Set(
+ "Array Object Math JSON Date Number Boolean Promise Map Set WeakMap WeakSet Symbol RegExp Error Intl URL URLSearchParams console setTimeout clearTimeout setInterval clearInterval requestAnimationFrame cancelAnimationFrame queueMicrotask structuredClone document window globalThis navigator location history localStorage sessionStorage fetch crypto performance alert confirm prompt parseInt parseFloat isNaN isFinite encodeURIComponent decodeURIComponent".split(" "),
+);
+
+// .rx's own builtins: the view writes them bare, and they stay bare
+const RX_BUILTINS = new Set(["len", "str", "map", "filter", "sum", "fail", "fetch", "every", "indexOf"]);
+
+/** The module the plain TypeScript of a Solid file moves to: what is not reactive stays what it was. */
+export const HELPERS = "helpers.ts";
+
+/** What a module's .d.rx says of a name it exports: a pure fn, an io fn, or a type. */
+export type Declared = (from: string, name: string) => "pure" | "io" | "type" | undefined;
+
+/** A .d.rx file's exports, by name. */
+export function declaredIn(drx: string): Map {
+ const m = new Map();
+ for (const x of drx.matchAll(/^export\s+(pure\s+)?(fn|type|const|source)\s+([\w$]+)/gm)) m.set(x[3], x[2] === "type" ? "type" : x[1] || x[2] !== "fn" ? "pure" : "io");
+ return m;
+}
+
+/** Another module's Solid view, parsed, by the path an import names; undefined when it is not one of the program's. */
+export type Modules = (from: string) => Node | undefined;
+
+export function toRx(ast: Node, src: string, opts: { declared?: Declared; modules?: Modules } = {}): { code: string; problems: RxProblem[]; files: Record } {
+ const problems: RxProblem[] = [];
+ const scopes: Map[] = [new Map()];
+ const pureImports = new Set(); // by local name: what reactive scope reads is imported pure, the rest is io
+ let imperative = 0;
+ const awaiting = new WeakSet();
+ // a store setter's draft: `setCart((draft) => { … })`, its parameter standing for the store while its body is read
+ const aliases = new Map; wrote?: boolean; guess?: boolean }>();
+ let exact = 0; // a write's target is printed as written, never as the local that holds its value
+ // `x++` inside a statement: the write, placed after it
+ const hoisted: ({ stmt: Node; after: string[]; before: string[] } | null)[] = [];
+ const squeeze = (t: string) => t.replace(/\s+/g, "");
+ /** A function with the "use server" directive. */
+ const isServer = (f: Node | null | undefined) => !!f && (isFn(f) || f.type === "FunctionDeclaration") && f.body?.type === "BlockStatement" && (f.body.directives ?? []).some((d: Node) => d.value?.value === "use server");
+ // what each server fn's body imports, and which are asked from reactive scope: those imports have to be pure (SF-1b)
+ const serverCalls = new Map>();
+ const askedServers = new Set();
+ let inServer: string | undefined;
+ const globals = new Map(); // each one used, and whether reactive scope reads it (a pure import)
+ let assigns = false; // a plain JavaScript assignment was written as assign(target, key, value)
+ let reactive = 0; // reads of reactive names so far: a source's first value that has one is a peek
+ let derived = 0; // inside a derived computation (a projection's function): reactive scope, which cannot write
+ const comments: Node[] = ast.comments ?? [];
+ /** The comments between `from` and `n`, as // lines. */
+ const leading = (n: Node, from: number): string[] =>
+ comments
+ .filter((c) => c.start >= from && c.end <= n.start)
+ .flatMap((c) => (c.type === "CommentLine" ? [`//${c.value}`] : (c.value as string).split("\n").map((l) => `// ${l.replace(/^\s*\*?\s?/, "")}`)))
+ .map((l) => l.trimEnd())
+ .filter((l) => l !== "//");
+
+ const lookup = (name: string) => {
+ for (let i = scopes.length - 1; i >= 0; i--) if (scopes[i].has(name)) return scopes[i].get(name);
+ };
+ const bind = (name: string, b: Binding) => scopes[scopes.length - 1].set(name, b);
+ const fail = (n: Node, message: string) => (problems.push({ line: n.loc?.start.line ?? 0, message }), "");
+ const text = (n: Node) => src.slice(n.start, n.end);
+ const callee = (n: Node | null | undefined) =>
+ n && (n.type === "CallExpression" || n.type === "OptionalCallExpression") && n.callee.type === "Identifier" ? (n.callee.name as string) : undefined;
+ const isFn = (n: Node | undefined) => !!n && (n.type === "ArrowFunctionExpression" || n.type === "FunctionExpression");
+ const isJsx = (n: Node | undefined) => !!n && (n.type === "JSXElement" || n.type === "JSXFragment");
+ const unwrap = (n: Node): Node => (n.type === "ParenthesizedExpression" || n.type === "TSNonNullExpression" ? unwrap(n.expression) : n);
+ /** `() => e`, `() => { return e }`: the `e`. */
+ const returned = (f: Node): Node | undefined => {
+ if (!isFn(f) && f?.type !== "FunctionDeclaration") return;
+ if (f.body.type !== "BlockStatement") return f.body;
+ return f.body.body.length === 1 && f.body.body[0].type === "ReturnStatement" ? f.body.body[0].argument : undefined;
+ };
+ const params = (f: Node) => f.params.map(text).join(", ");
+ /** An arrow's parameters: .rx writes them without types. */
+ const bare = (f: Node) => f.params.map((q: Node) => (q.typeAnnotation ? src.slice(q.start, q.typeAnnotation.start).replace(/\?$/, "") : text(q))).join(", ");
+ /** `ThemeContext` is the context .rx calls `theme`. */
+ const contextName = (js: string) => js.replace(/Context$/, "").replace(/^./, (c) => c.toLowerCase()) || js;
+ const renamed = new Map(); // an imported context: its .rx name
+ const preludeAliases = new Set(); // `const keep = filter`: a builtin imported under another name (09)
+ /** The .rx name of the context `n` names, or undefined if it is not one. */
+ const contextOf = (n: Node | undefined): string | undefined => {
+ if (n?.type !== "Identifier") return;
+ const b = lookup(n.name);
+ if (b?.kind === "context") return b.as;
+ if (b?.kind === "import") return renamed.set(n.name, contextName(n.name)), contextName(n.name);
+ };
+ /** `if (!(e instanceof A || e instanceof B)) throw e;` (or with `e()`): the classes a typed catch takes. */
+ const rethrows = (st: Node | undefined, p: string, called: boolean): string[] | undefined => {
+ if (st?.type !== "IfStatement" || st.alternate) return;
+ const then = st.consequent.type === "BlockStatement" && st.consequent.body.length === 1 ? st.consequent.body[0] : st.consequent;
+ const isP = (x: Node) => (called ? x.type === "CallExpression" && !x.arguments.length && x.callee.type === "Identifier" && x.callee.name === p : x.type === "Identifier" && x.name === p);
+ const t = unwrap(st.test);
+ if (then?.type !== "ThrowStatement" || !isP(unwrap(then.argument)) || t.type !== "UnaryExpression" || t.operator !== "!") return;
+ const out: string[] = [];
+ const walk = (x: Node): boolean => {
+ x = unwrap(x);
+ if (x.type === "LogicalExpression" && x.operator === "||") return walk(x.left) && walk(x.right);
+ if (x.type === "BinaryExpression" && x.operator === "instanceof" && isP(unwrap(x.left)) && x.right.type === "Identifier") return out.push(x.right.name), true;
+ return false;
+ };
+ return walk(t.argument) ? out : undefined;
+ };
+ /** What another module exports, read from its Solid view as this module's own declarations are read. */
+ const exportedKinds = (mod: Node): Map => {
+ const out = new Map();
+ for (const st of mod.program.body as Node[]) {
+ const d = st.type === "ExportNamedDeclaration" ? st.declaration : undefined;
+ if (d?.type === "ClassDeclaration" && d.superClass?.type === "Identifier" && d.superClass.name === "Error") out.set(d.id.name, { kind: "error" });
+ if (d?.type !== "VariableDeclaration") continue;
+ for (const v of d.declarations as Node[]) {
+ const name = callee(v.init);
+ const get = v.id.type === "ArrayPattern" ? v.id.elements[0]?.name : v.id.type === "Identifier" ? v.id.name : undefined;
+ if (!get) continue;
+ if (v.id.type === "ArrayPattern" && (name === "createSignal" || name === "createOptimistic")) out.set(get, { kind: "read" });
+ else if (v.id.type === "ArrayPattern" && (name === "createStore" || name === "createOptimisticStore")) out.set(get, { kind: "store" });
+ else if (v.id.type === "Identifier" && (name === "createMemo" || name === "createDeferred")) out.set(get, { kind: "read" });
+ else if (v.id.type === "Identifier" && (name === "createProjection" || name === "omit")) out.set(get, { kind: "store" });
+ else if (v.id.type === "Identifier" && name === "createContext") out.set(get, { kind: "context", as: contextName(get) });
+ }
+ }
+ return out;
+ };
+
+ /** `{ loadingValue: v }` among a primitive's options: `-> v`, the first paint (R-7). */
+ const paintOf = (o: Node | undefined): Node | undefined =>
+ o?.type === "ObjectExpression" ? o.properties.find((q: Node) => q.type === "ObjectProperty" && !q.computed && (q.key.name ?? q.key.value) === "loadingValue")?.value : undefined;
+ let paint: string | undefined; // a first paint for the `.catch` about to be read: it goes between the await and the catch
+ /** `(e) => alt`, or `(e) => { if (!(e instanceof A)) throw e; return alt }`: a catch clause (R-f-4, 07). */
+ const catchClause = (f: Node | undefined): { p: string; classes?: string[]; alt: Node } | undefined => {
+ if (!isFn(f) || f!.params.length !== 1 || f!.params[0].type !== "Identifier") return;
+ const p = f!.params[0].name as string;
+ if (f!.body.type !== "BlockStatement") return { p, alt: f!.body };
+ const st: Node[] = f!.body.body;
+ const classes = st.length === 2 && st[1].type === "ReturnStatement" && st[1].argument ? rethrows(st[0], p, false) : undefined;
+ return classes ? { p, classes, alt: st[1].argument } : undefined;
+ };
+ const clause = (c: { p: string; classes?: string[]; alt: Node }) => {
+ scopes.push(new Map([[c.p, { kind: "plain" } as Binding]]));
+ const alt = expr(c.alt);
+ scopes.pop();
+ return `catch (${c.p}${c.classes ? `: ${c.classes.join(" | ")}` : ""}) => ${alt}`;
+ };
+ /** `createMemo(() => { try { return x } catch (e) { if (e instanceof NotReadyError || …) throw e; return alt } })`: `x catch (e) => alt`. */
+ const caughtMemo = (f: Node | undefined): { x: Node; c: { p: string; classes?: string[]; alt: Node } } | undefined => {
+ const t = isFn(f) && f!.body.type === "BlockStatement" && f!.body.body.length === 1 ? f!.body.body[0] : undefined;
+ const ret = t?.type === "TryStatement" && !t.finalizer && t.block.body.length === 1 ? t.block.body[0] : undefined;
+ const h = t?.handler;
+ if (ret?.type !== "ReturnStatement" || !ret.argument || h?.param?.type !== "Identifier" || h.body.body.length !== 2 || h.body.body[1].type !== "ReturnStatement") return;
+ const p = h.param.name as string;
+ const first: Node = h.body.body[0];
+ const then = first.type === "IfStatement" && !first.alternate ? (first.consequent.type === "BlockStatement" && first.consequent.body.length === 1 ? first.consequent.body[0] : first.consequent) : undefined;
+ if (then?.type !== "ThrowStatement" || unwrap(then.argument).name !== p) return;
+ const parts: Node[] = [];
+ const flat = (x: Node): void => {
+ x = unwrap(x);
+ if (x.type === "LogicalExpression" && x.operator === "||") flat(x.left), flat(x.right);
+ else parts.push(x);
+ };
+ flat(first.test);
+ const ready = parts[0];
+ if (!(ready?.type === "BinaryExpression" && ready.operator === "instanceof" && unwrap(ready.left).name === p && ready.right.name === "NotReadyError")) return;
+ let classes: string[] | undefined;
+ if (parts.length === 2) {
+ classes = rethrows({ ...first, test: parts[1], consequent: then }, p, false);
+ if (!classes) return;
+ } else if (parts.length !== 1) return;
+ return { x: ret.argument, c: { p, classes, alt: h.body.body[1].argument } };
+ };
+
+ /** `class E extends Error { constructor(a) { super(m); this.name = "E"; this.a = a; } }` as `error E(a) => m`. */
+ function errorDecl(c: Node): string[] {
+ const name = c.id.name as string;
+ const members: Node[] = c.body.body;
+ const ctor = members.find((m) => m.kind === "constructor");
+ if (members.length !== (ctor ? 1 : 0)) return fail(c, `${name}: an error class with members besides its constructor has no .rx form`), [];
+ if (!ctor) return [`error ${name}`];
+ const ps: string[] = ctor.params.map((q: Node) => (q.type === "Identifier" ? q.name : ""));
+ if (ps.some((q) => !q)) return fail(ctor, `${name}: an error's fields are named parameters`), [];
+ let message: Node | undefined;
+ for (const st of ctor.body.body as Node[]) {
+ const e = st.type === "ExpressionStatement" ? unwrap(st.expression) : undefined;
+ if (e?.type === "CallExpression" && e.callee.type === "Super" && e.arguments.length <= 1) message = e.arguments[0];
+ else if (e?.type === "AssignmentExpression" && e.left.type === "MemberExpression" && e.left.object.type === "ThisExpression" && !e.left.computed) {
+ const f = e.left.property.name as string;
+ if (f === "name" && e.right.type === "StringLiteral" && e.right.value === name) continue;
+ if (f !== "name" && e.right.type === "Identifier" && e.right.name === f && ps.includes(f)) continue;
+ return fail(st, `${name}: a field that is not its parameter has no .rx form`), [];
+ } else return fail(st, `${name}: an error's constructor only calls super and names its fields`), [];
+ }
+ scopes.push(new Map(ps.map((q) => [q, { kind: "plain" } as Binding])));
+ const m = message ? ` => ${expr(message)}` : "";
+ scopes.pop();
+ const typed = ctor.params.map((q: Node) => text(q)).join(", ");
+ return [`error ${name}${ps.length || message ? `(${typed})` : ""}${m}`];
+ }
+
+ // ---- text placement: an expression's text keeps the source's indentation until it is placed
+
+ const lineIndent = (at: number) => /^[ \t]*/.exec(src.slice(src.lastIndexOf("\n", at - 1) + 1))![0];
+ const place = (s: string, base: string, indent: string) =>
+ s
+ .split("\n")
+ .map((l, i) => (i === 0 ? l : indent + (l.startsWith(base) ? l.slice(base.length) : l.trimStart()).replace(/^\t+/, (t) => INDENT.repeat(t.length))))
+ .join("\n")
+ // a newline ends a .rx expression, so an operator that leads a line moves to the end of the one before
+ .replace(/([^,([{\s])\n([ \t]*)(\?\?|\?|:|&&|\|\||[-+*/%]|[!=]==?|[<>]=?) /g, "$1 $3\n$2")
+ .replace(/([^,([{\s])\n[ \t]*(\??\.)(?=[\w$])/g, "$1$2");
+ const indented = (lines: string[], indent: string) => lines.map((l) => (l ? indent + l : l));
+
+ // ---- expressions: the source text, with the Solid forms inside it rewritten
+
+ /** `e` as an operand: in parentheses unless it is a name or a call. */
+ const operand = (s: string) => (/^[\w$.]+(\([^()]*\))?$/.test(s) ? s : `(${s})`);
+
+ function rewrite(n: Node, parent?: Node): string | undefined {
+ if (aliases.size && !exact && /MemberExpression$/.test(n.type)) {
+ const local = aliases.get(root(n))?.written.get(squeeze(text(n)));
+ if (local) return local;
+ }
+ // `x as T`, `x!`: TypeScript's, not .rx's
+ if (n.type === "TSAsExpression" || n.type === "TSSatisfiesExpression" || n.type === "TSNonNullExpression") return expr(n.expression, parent);
+ const name = callee(n);
+ const head = !!parent && ((/MemberExpression$/.test(parent.type) && parent.object === n) || (/CallExpression$/.test(parent.type) && parent.callee === n));
+ const tight = head || (!!parent && /Binary|Logical|Unary|Await|Spread/.test(parent.type));
+ if (name !== undefined) {
+ const b = lookup(name);
+ const a: Node[] = n.arguments;
+ if (b?.kind === "read" && a.length === 0) return reactive++, name;
+ if (b?.kind === "store" && a.length === 0) return reactive++, name;
+ if (b?.kind === "handler" && !imperative) return fail(n, `${name} writes and is called while rendering: reactive scope cannot write in .rx (R-io-3)`);
+ if (b?.kind === "await" && a.length === 0) return tight ? `(${b.text})` : b.text;
+ if (b?.kind === "import" && inServer) serverCalls.get(inServer)?.add(name);
+ if (b?.kind === "server" && !imperative && !awaiting.has(n) && !(parent && /Await|Yield/.test(parent.type))) {
+ awaiting.add(n);
+ askedServers.add(name);
+ const s = `await ${expr(n)}`;
+ return tight ? `(${s})` : s;
+ }
+ if (b?.kind === "import" && !imperative) {
+ pureImports.add(name);
+ if (b.async && !awaiting.has(n) && !(parent && /Await|Yield/.test(parent.type))) {
+ awaiting.add(n);
+ const s = `await ${expr(n)}`;
+ return tight ? `(${s})` : s;
+ }
+ }
+ if (b?.kind === "setter") return fail(n, `${name}(…) is a write: it can only be a statement in a handler or an action`);
+ if (name === "untrack" && a.length === 1) {
+ const inner = isFn(a[0]) ? returned(a[0]) : undefined;
+ const of = inner ? expr(inner) : a[0].type === "Identifier" && lookup(a[0].name) ? a[0].name : undefined;
+ if (of === undefined) return fail(n, "untrack of something that is not a signal, a memo or a function");
+ return imperative ? (tight && inner ? operand(of) : of) : `peek(${of})`;
+ }
+ if ((name === "latest" || name === "isPending") && a.length === 1) {
+ const inner = isFn(a[0]) ? returned(a[0]) : a[0].type === "Identifier" ? a[0] : undefined;
+ if (!inner) return fail(n, `${name} of something that is not a function or an accessor`);
+ const of = inner.type === "Identifier" ? inner.name : expr(inner);
+ const s = `${name === "latest" ? "latest" : "pending?"} ${operand(of)}`;
+ return head ? `(${s})` : s;
+ }
+ if (name === "String" && a.length === 1) return `str(${expr(a[0])})`;
+ if (/^create[A-Z]|^(action|omit|merge)$/.test(name) && lookup(name)?.kind === "plain")
+ return fail(n, `${name} is only read as a declaration or a statement, not inside an expression`);
+ }
+ if (/CallExpression$/.test(n.type) && /MemberExpression$/.test(n.callee.type) && !n.callee.computed) {
+ const m = n.callee.property.name as string;
+ // `console.log(…)` is .rx's log: a builtin, where `console` itself would have to be imported
+ if (m === "log" && n.callee.object.type === "Identifier" && n.callee.object.name === "console" && !lookup("console")) return `log(${n.arguments.map((x: Node) => expr(x)).join(", ")})`;
+ const cc = m === "catch" && !imperative && n.arguments.length === 1 ? catchClause(n.arguments[0]) : undefined;
+ if (cc) {
+ const at = paint;
+ paint = undefined;
+ awaiting.add(n.callee.object);
+ const on = expr(n.callee.object, n).replace(/^await\s+/, "");
+ const s = `await ${on}${at ? ` -> ${at}` : ""} ${clause(cc)}`;
+ return tight ? `(${s})` : s;
+ }
+ if (m === "then" || m === "catch" || m === "finally") return fail(n, `.${m}(…): .rx has no promise chaining; an action's failure is caught in its body, try { … } catch (e) { … }`);
+ const o = n.callee.object.type === "Identifier" ? lookup(n.callee.object.name) : undefined;
+ if (o?.kind === "import" && o.asyncMembers?.has(m) && !imperative && !awaiting.has(n) && !(parent && /Await|Yield/.test(parent.type))) {
+ awaiting.add(n);
+ const head2 = !!parent && ((/MemberExpression$/.test(parent.type) && parent.object === n) || (/CallExpression$/.test(parent.type) && parent.callee === n));
+ const s = `await ${expr(n)}`;
+ return head2 || (!!parent && /Binary|Logical|Unary|Spread/.test(parent.type)) ? `(${s})` : s;
+ }
+ }
+ if (n.type === "Identifier") {
+ const b = lookup(n.name);
+ const key = parent && ((/MemberExpression$/.test(parent.type) && parent.property === n && !parent.computed) || (parent.type === "ObjectProperty" && parent.key === n && !parent.computed));
+ if (!key && b?.kind === "read") return fail(n, `the accessor ${n.name} is passed as a value: .rx has names, not accessors`);
+ if (!key && b?.kind === "setter") return fail(n, `the setter ${n.name} is passed as a value: a write is a statement in .rx`);
+ if (!key && aliases.has(n.name) && b?.kind === "plain") return aliases.get(n.name)!.store;
+ if (!key && b?.kind === "input") return b.as;
+ // a plain `let` never subscribes its readers: as a source, reactive scope reads it with peek
+ if (!key && b?.kind === "mutable" && (!imperative || derived)) return `peek(${n.name})`;
+ if (!key && (b?.kind === "store" || b?.kind === "equation")) reactive++;
+ if (!key && b?.kind === "import" && !imperative) pureImports.add(n.name);
+ if (!key && !b && RX_BUILTINS.has(n.name)) return;
+ if (!key && !b && GLOBALS.has(n.name)) globals.set(n.name, !!globals.get(n.name) || !imperative);
+ return;
+ }
+ if (n.type === "YieldExpression" || n.type === "AwaitExpression") {
+ const s = `await ${expr(n.argument, n)}`;
+ // in imperative scope a run suspends only at a statement (AC-1): an await inside an expression is bound first
+ const h = hoisted[hoisted.length - 1];
+ if (imperative && parent && h) {
+ let v = "value";
+ for (let i = 2; lookup(v); i++) v = `value${i}`;
+ bind(v, { kind: "plain" });
+ h.before.push(...`let ${v} = ${s}`.split("\n"));
+ return v;
+ }
+ return tight ? `(${s})` : s;
+ }
+ // `GET(async function (id) { "use server"; … })`: a server fn as an expression (SF-1d)
+ if (isFn(n) && isServer(n)) return ["server fn (" + params(n) + ") {", ...serverBody(n).map((l) => "\t" + l), "}"].join("\n");
+ if (isFn(n)) {
+ if (n.type === "FunctionExpression") return fail(n, "a function expression: .rx has arrow functions only");
+ const shadow = new Map();
+ for (const p of n.params) for (const id of names(p)) shadow.set(id, { kind: "plain" });
+ scopes.push(shadow);
+ const lhs = n.params.length === 1 && n.params[0].type === "Identifier" && n.body.type !== "BlockStatement" ? n.params[0].name : `(${bare(n)})`;
+ let out: string;
+ if (n.body.type === "BlockStatement") {
+ imperative++;
+ out = `${lhs} => ${block(n.body.body)}`;
+ imperative--;
+ } else if (isWrite(unwrap(n.body))) {
+ imperative++;
+ out = `${lhs} => ${block([{ ...n.body, type: "ExpressionStatement", expression: n.body }])}`;
+ imperative--;
+ } else if (isJsx(unwrap(n.body))) {
+ out = fail(n, "a function that returns JSX: write it as a component, or ");
+ } else {
+ const body = expr(n.body, n);
+ out = `${lhs} => ${unwrap(n.body).type === "ObjectExpression" ? `(${body})` : body}`;
+ }
+ scopes.pop();
+ return out;
+ }
+ if (isJsx(n)) return fail(n, "JSX inside an expression: .rx markup stands on its own, in {if}, {for} or a component");
+ if (n.type === "UpdateExpression" && n.argument.type === "Identifier" && lookup(n.argument.name)?.kind === "mutable") {
+ const x = n.argument.name as string;
+ const h = hoisted[hoisted.length - 1];
+ if (!h) return fail(n, `${text(n)} here: .rx writes are statements; write ${x} := ${x} ${n.operator[0]} 1 on its own line`);
+ if (new RegExp(`(? expr(x)).join(", ")})`;
+ // `(() => { throw e; })()`: .rx's throw expression (07)
+ if (n.type === "CallExpression" && !n.arguments.length && unwrap(n.callee).type === "ArrowFunctionExpression") {
+ const f = unwrap(n.callee);
+ const only = f.body.type === "BlockStatement" && f.body.body.length === 1 ? f.body.body[0] : undefined;
+ if (!f.params.length && only?.type === "ThrowStatement") return tight ? `(throw ${expr(only.argument)})` : `throw ${expr(only.argument)}`;
+ }
+ // `useContext(c)()`: the context's value, read where it is (07)
+ if (n.type === "CallExpression" && !n.arguments.length && callee(n.callee) === "useContext" && lookup("useContext")?.kind === "plain") {
+ const c = contextOf(n.callee.arguments[0]);
+ if (c) return tight ? `(use ${c})` : `use ${c}`;
+ }
+ if (n.type === "ThisExpression" || n.type === "NewExpression" || n.type === "ClassExpression") return fail(n, `${n.type.replace("Expression", "").toLowerCase()} has no .rx form`);
+ return;
+ }
+
+ /** A call that is a statement in .rx: a setter, a store path write, affects, refresh. */
+ function isWrite(e: Node): boolean {
+ const name = callee(e);
+ if (name && (lookup(name)?.kind === "setter" || ((name === "affects" || name === "refresh") && lookup(name)?.kind === "plain"))) return true;
+ if (e.type === "AssignmentExpression" && /MemberExpression$/.test(e.left.type)) return true;
+ return e.type === "CallExpression" && e.callee.type === "MemberExpression" && e.callee.object.type === "Identifier" && lookup(e.callee.object.name)?.kind === "setter";
+ }
+
+ /** A server fn's statements: imperative scope, on the server. */
+ function serverBody(f: Node): string[] {
+ imperative++;
+ scopes.push(new Map(f.params.flatMap(names).map((n: string) => [n, { kind: "plain" } as Binding])));
+ const lines = f.body.body.flatMap(stmt);
+ scopes.pop();
+ imperative--;
+ return lines;
+ }
+
+ function names(p: Node): string[] {
+ if (p.type === "Identifier") return [p.name];
+ if (p.type === "AssignmentPattern") return names(p.left);
+ if (p.type === "RestElement") return names(p.argument);
+ if (p.type === "ObjectPattern") return p.properties.flatMap((q: Node) => names(q.type === "RestElement" ? q : q.value));
+ if (p.type === "ArrayPattern") return p.elements.filter(Boolean).flatMap(names);
+ return [];
+ }
+
+ /** `n` as .rx, its later lines still carrying the source's indentation. */
+ function raw(n: Node, parent?: Node): string {
+ const whole = rewrite(n, parent);
+ if (whole !== undefined) return whole.replace(/\n/g, "\n" + lineIndent(n.start));
+ const edits: { start: number; end: number; text: string }[] = [];
+ // `a?.b` is `a.b` (every .rx member read is optional) and `===` is `==` (E-6)
+ const tokens = (m: Node) => {
+ if (m.type === "OptionalMemberExpression" && m.optional) {
+ const at = src.indexOf("?.", m.object.end);
+ if (at >= 0 && at < m.property.start) edits.push({ start: at, end: at + 2, text: m.computed ? "" : "." });
+ } else if (m.type === "BinaryExpression" && (m.operator === "===" || m.operator === "!==")) {
+ const at = src.indexOf(m.operator, m.left.end);
+ if (at >= 0 && at < m.right.start) edits.push({ start: at, end: at + 3, text: m.operator.slice(0, 2) });
+ }
+ };
+ const walk = (m: Node) => {
+ for (const k of Object.keys(m)) {
+ if (k === "loc" || k === "typeAnnotation" || k === "typeParameters" || k === "returnType") continue;
+ const v = m[k];
+ for (const c of Array.isArray(v) ? v : [v]) {
+ if (!c || typeof c.type !== "string" || typeof c.start !== "number") continue;
+ const r = rewrite(c, m);
+ if (r !== undefined) edits.push({ start: c.start, end: c.end, text: r.replace(/\n/g, "\n" + lineIndent(c.start)) });
+ else tokens(c), walk(c);
+ }
+ }
+ };
+ tokens(n);
+ walk(n);
+ let out = "";
+ let at = n.start;
+ for (const e of edits.sort((a, b) => a.start - b.start)) {
+ out += src.slice(at, e.start) + e.text;
+ at = e.end;
+ }
+ return out + src.slice(at, n.end);
+ }
+ /** `n` as .rx, placed at column 0: later lines are relative to the first. */
+ const expr = (n: Node, parent?: Node) => place(raw(n, parent), lineIndent(n.start), "");
+
+ // ---- statements (imperative scope)
+
+ function target(of: string, path: Node | undefined, n: Node): string {
+ if (!path) return of;
+ if (path.type !== "ArrayExpression") return fail(n, "a store path that is not written out as an array");
+ return of + path.elements.map((k: Node) => (k.type === "StringLiteral" && /^[A-Za-z_$][\w$]*$/.test(k.value) ? `.${k.value}` : `[${expr(k)}]`)).join("");
+ }
+
+ const MUTATORS: Record string> = {
+ push: (v, a) => `[...${v}, ${a}]`,
+ unshift: (v, a) => `[${a}, ...${v}]`,
+ pop: (v) => `${v}.slice(0, -1)`,
+ shift: (v) => `${v}.slice(1)`,
+ splice: (v, a) => `${v}.toSpliced(${a})`,
+ sort: (v, a) => `${v}.toSorted(${a})`,
+ reverse: (v) => `${v}.toReversed()`,
+ };
+ /** A name for a local or a parameter that nothing in `fn` already uses. */
+ const fresh = (want: string, fn: Node) => {
+ const used = (n: string) => !!lookup(n) || new RegExp(`(? (/MemberExpression$/.test(path.type) && !path.computed ? (path.property.name as string) : "v");
+ /** A write's target, as written: the draft's parameter is the store, and no local stands in for it. */
+ const exactly = (n: Node) => {
+ exact++;
+ const out = expr(n);
+ exact--;
+ return out;
+ };
+
+ /** One statement of a draft's body, `draft.a.b = v` and the like: writes along the store's path (W-1, W-6, AC-1d). */
+ function draftWrite(e: Node, s: Node): string[] | undefined {
+ const assign = e.type === "AssignmentExpression" || e.type === "UpdateExpression";
+ const path = e.type === "AssignmentExpression" ? e.left : e.type === "UpdateExpression" ? e.argument : e.type === "CallExpression" && e.callee.type === "MemberExpression" ? e.callee.object : undefined;
+ const a = path && aliases.get(root(path));
+ if (!a || !/MemberExpression$/.test(path.type)) return;
+ const g = a.guess ? "guess " : "";
+ if (!assign) {
+ const m = MUTATORS[e.callee.property.name];
+ if (!m || e.callee.computed) return;
+ // `list.push(x)`: a write to the next index appends in place, as push does. After another write in this run the
+ // length it reads would be stale (AC-1d), so there the list is written functionally
+ if (e.callee.property.name === "push" && e.arguments.length === 1 && e.arguments[0].type !== "SpreadElement" && !a.wrote) {
+ a.wrote = true;
+ return `${g}${exactly(path)}[${expr(path)}.length] := ${expr(e.arguments[0])}`.split("\n");
+ }
+ a.wrote = true;
+ const v = fresh(last(path), a.fn);
+ return `${g}${exactly(path)} := ${v} => ${m(v, e.arguments.map((x: Node) => expr(x)).join(", "))}`.split("\n");
+ }
+ const op = e.type === "UpdateExpression" ? e.operator[0] : e.operator.slice(0, -1);
+ const by = e.type === "UpdateExpression" ? "1" : expr(e.right);
+ const key = squeeze(text(path));
+ const done = (lines: T) => ((a.wrote = true), lines);
+ // `draft.a = ((v) => …)(draft.a)`: a functional write, as the view prints `x := v => …`
+ const iife = e.type === "AssignmentExpression" && e.operator === "=" ? unwrap(e.right) : undefined;
+ const f = iife?.type === "CallExpression" ? unwrap(iife.callee) : undefined;
+ if (iife && f && isFn(f) && f.params.length === 1 && f.params[0].type === "Identifier" && iife.arguments.length === 1 && squeeze(text(iife.arguments[0])) === key)
+ return done(`${g}${exactly(path)} := ${expr(f)}`.split("\n"));
+ // read again below: the checker has a read after this run's own write as stale, so the value goes in a local
+ const again = squeeze(src.slice(s.end, a.fn.end)).includes(key);
+ if (again) {
+ const value = op ? `${expr(path)} ${op} ${operand(by)}` : by;
+ const local = fresh(last(path), a.fn);
+ a.written.set(key, local);
+ return done([...`let ${local} = ${value}`.split("\n"), `${g}${exactly(path)} := ${local}`]);
+ }
+ if (!op) return done(`${g}${exactly(path)} := ${by}`.split("\n"));
+ const v = fresh(last(path), a.fn);
+ return done(`${g}${exactly(path)} := ${v} => ${v} ${op} ${operand(by)}`.split("\n"));
+ }
+ /** `(draft) => { draft.x = 1 }`: a function that changes its argument and returns nothing. */
+ const isDraft = (f: Node | undefined) => {
+ if (!f || !isFn(f) || f.params.length !== 1 || f.params[0].type !== "Identifier") return false;
+ if (f.body.type === "BlockStatement") return !f.body.body.some((x: Node) => x.type === "ReturnStatement" && x.argument);
+ const b = unwrap(f.body);
+ return b.type === "AssignmentExpression" || b.type === "UpdateExpression" || (b.type === "CallExpression" && b.callee.type === "MemberExpression" && root(b.callee.object) === f.params[0].name && b.callee.property.name in MUTATORS);
+ };
+
+ /**
+ * A draft change that is one functional write of the whole value: a list method on the draft itself, or one row
+ * found and changed. A guess has to be one (a guess along a path is not lowered), and a row reached through a local
+ * has no path to write along.
+ */
+ function wholeWrite(b: Binding & { kind: "setter" }, f: Node): string[] | undefined {
+ const param = f.params[0].name as string;
+ const stmts: Node[] = f.body.type === "BlockStatement" ? f.body.body : [{ ...f.body, type: "ExpressionStatement", expression: f.body }];
+ const head = `${b.guess ? "guess " : ""}${b.of} := ${param} =>`;
+ scopes.push(new Map([[param, { kind: "plain" } as Binding]]));
+ try {
+ const only = stmts.length === 1 && stmts[0].type === "ExpressionStatement" ? unwrap(stmts[0].expression) : undefined;
+ if (only?.type === "CallExpression" && only.callee.type === "MemberExpression" && only.callee.object.type === "Identifier" && only.callee.object.name === param && !only.callee.computed && only.callee.property.name in MUTATORS)
+ return `${head} ${MUTATORS[only.callee.property.name](param, only.arguments.map((x: Node) => expr(x)).join(", "))}`.split("\n");
+ // `const row = draft.find(…); row.a = 1; row.b = 2`
+ const first = stmts[0];
+ const d = first?.type === "VariableDeclaration" && first.declarations.length === 1 ? first.declarations[0] : undefined;
+ const found = d && d.id.type === "Identifier" && d.init ? unwrap(d.init) : undefined;
+ if (!found || found.type !== "CallExpression" || found.callee.type !== "MemberExpression" || found.callee.object.type !== "Identifier" || found.callee.object.name !== param || found.callee.property.name !== "find" || stmts.length < 2) return;
+ const row = d.id.name as string;
+ bind(row, { kind: "plain" });
+ const fields: string[] = [];
+ const set: string[] = [];
+ for (const x of stmts.slice(1)) {
+ const e = x.type === "ExpressionStatement" ? unwrap(x.expression) : undefined;
+ const left = e?.type === "AssignmentExpression" ? e.left : e?.type === "UpdateExpression" ? e.argument : undefined;
+ if (!e || !left || left.type !== "MemberExpression" || left.computed || left.object.type !== "Identifier" || left.object.name !== row) return;
+ const k = left.property.name as string;
+ const from = e.type === "AssignmentExpression" ? e.right : undefined;
+ // a value that reads a field this change already wrote would read the old one in an object literal
+ if (from && set.some((p) => new RegExp(`(? ${each} == ${row} ? { ...${row}, ${fields.join(", ")} } : ${each})`, "}"];
+ } finally {
+ scopes.pop();
+ }
+ }
+
+ function stmt(s: Node): string[] {
+ hoisted.push(/^(Expression|Return|Throw)Statement$|^VariableDeclaration$/.test(s.type) ? { stmt: s, after: [], before: [] } : null);
+ const lines = statement(s);
+ const h = hoisted.pop();
+ return [...(h?.before ?? []), ...lines, ...(h?.after ?? [])];
+ }
+
+ function statement(s: Node): string[] {
+ switch (s.type) {
+ case "ExpressionStatement": {
+ const e = unwrap(s.expression);
+ const name = callee(e);
+ const b = name ? lookup(name) : undefined;
+ if (b?.kind === "setter" && e.arguments.length === 1 && lookup(b.of)?.kind === "store" && isDraft(e.arguments[0])) {
+ const whole = wholeWrite(b, e.arguments[0]);
+ if (whole) return whole;
+ const f = e.arguments[0] as Node;
+ const alias = f.params[0].name as string;
+ const outer = aliases.get(alias);
+ aliases.set(alias, { store: b.of, fn: f, written: new Map(), guess: b.guess });
+ scopes.push(new Map([[alias, { kind: "plain" } as Binding]]));
+ const lines = (f.body.type === "BlockStatement" ? f.body.body : [{ ...f.body, type: "ExpressionStatement", expression: f.body }]).flatMap(stmt);
+ scopes.pop();
+ outer ? aliases.set(alias, outer) : aliases.delete(alias);
+ return lines;
+ }
+ if (b?.kind === "setter" && e.arguments.length === 1 && !derived) {
+ // a run suspends only at a statement (AC-1): an awaited value is bound first, then written
+ if (/Yield|Await/.test(unwrap(e.arguments[0]).type)) {
+ const v = fresh(b.of.replace(/\W.*$/, "") || "v", s);
+ return [...`let ${v} = ${expr(e.arguments[0])}`.split("\n"), `${b.guess ? "guess " : ""}${b.of} := ${v}`];
+ }
+ return [`${b.guess ? "guess " : ""}${b.of} := ${expr(e.arguments[0])}`];
+ }
+ if (e.type === "UnaryExpression" && e.operator === "delete") return fail(e, `${text(e)}: .rx has no delete; write undefined or false to the key`), [];
+ if (derived && ((b?.kind === "setter" && e.arguments.length === 1) || ((e.type === "AssignmentExpression" || e.type === "UpdateExpression") && lookup(root(e.type === "AssignmentExpression" ? e.left : e.argument))?.kind === "mutable")))
+ return fail(e, `${text(e)} inside a derived computation: reactive scope cannot write in .rx; a previous value is read with pre x`), [];
+ const along = draftWrite(e, s);
+ if (along) return along;
+ // a `let` of the component's setup is a source
+ const x = e.type === "AssignmentExpression" ? e.left : e.type === "UpdateExpression" ? e.argument : undefined;
+ if (x?.type === "Identifier" && lookup(x.name)?.kind === "mutable") {
+ if (e.type === "UpdateExpression") return [`${x.name} := ${x.name} ${e.operator[0]} 1`];
+ return `${x.name} := ${e.operator === "=" ? expr(e.right) : `${x.name} ${e.operator.slice(0, -1)} ${operand(expr(e.right))}`}`.split("\n");
+ }
+ // `input.value = ""`: plain JavaScript's assignment is not an .rx statement; a helper makes it
+ if (e.type === "AssignmentExpression" && /MemberExpression$/.test(e.left.type) && !drafts.has(root(e.left)) && !["store", "read", "mutable", "equation", "setter"].includes(lookup(root(e.left))?.kind ?? "")) {
+ assigns = true;
+ const key = e.left.computed ? expr(e.left.property) : JSON.stringify(e.left.property.name);
+ const value = e.operator === "=" ? expr(e.right) : `${expr(e.left)} ${e.operator.slice(0, -1)} ${operand(expr(e.right))}`;
+ return `assign(${expr(e.left.object)}, ${key}, ${value})`.split("\n");
+ }
+ // `setX.path(["a", "b"], v)`: a write along a store's path
+ if (e.type === "CallExpression" && e.callee.type === "MemberExpression" && e.callee.object.type === "Identifier" && e.callee.property.name === "path") {
+ const w = lookup(e.callee.object.name);
+ if (w?.kind === "setter" && e.arguments.length === 2) return [`${w.guess ? "guess " : ""}${target(w.of, e.arguments[0], e)} := ${expr(e.arguments[1])}`];
+ }
+ if ((name === "affects" || name === "refresh") && e.arguments.length === 1 && e.arguments[0].type === "Identifier") return [`${name} ${e.arguments[0].name}`];
+ if (e.type === "AssignmentExpression" && e.operator === "=" && drafts.has(root(e.left))) return [`${expr(e.left)} := ${expr(e.right)}`];
+ return expr(e).split("\n");
+ }
+ case "VariableDeclaration":
+ return s.declarations.flatMap((d: Node) => {
+ for (const id of names(d.id)) bind(id, { kind: "plain" });
+ return `${s.kind === "const" ? "const" : "let"} ${text(d.id)}${d.init ? ` = ${expr(d.init)}` : ""}`.split("\n");
+ });
+ case "ReturnStatement":
+ return (s.argument ? `return ${expr(s.argument, s)}` : "return").split("\n");
+ case "ThrowStatement":
+ return `throw ${expr(s.argument, s)}`.split("\n");
+ case "IfStatement": {
+ const out = [`if (${expr(s.test)}) {`, ...indented(body(s.consequent), INDENT)];
+ if (s.alternate && !(s.alternate.type === "BlockStatement" && !s.alternate.body.length)) out.push("} else {", ...indented(body(s.alternate), INDENT));
+ return [...out, "}"];
+ }
+ case "TryStatement": {
+ const out = ["try {", ...indented(body(s.block), INDENT)];
+ const p = s.handler?.param?.type === "Identifier" ? (s.handler.param.name as string) : undefined;
+ // `if (!(e instanceof A)) throw e;` first: a typed catch, which rethrows the other classes (R-f-6)
+ const classes = p ? rethrows(s.handler.body.body[0], p, false) : undefined;
+ const handler = classes ? { ...s.handler.body, body: s.handler.body.body.slice(1) } : s.handler?.body;
+ if (s.handler) out.push(`} catch${s.handler.param ? ` (${classes ? `${p}: ${classes.join(" | ")}` : text(s.handler.param)})` : ""} {`, ...indented(body(handler), INDENT));
+ if (s.finalizer) out.push("} finally {", ...indented(body(s.finalizer), INDENT));
+ return [...out, "}"];
+ }
+ case "BlockStatement":
+ return body(s);
+ case "EmptyStatement":
+ return [];
+ default:
+ fail(s, `${s.type.replace(/Statement|Declaration/, "").toLowerCase()} statement: no .rx form in this prototype`);
+ return [];
+ }
+ }
+ const body = (s: Node): string[] => {
+ scopes.push(new Map());
+ const out = (s.type === "BlockStatement" ? s.body : [s]).flatMap(stmt);
+ scopes.pop();
+ return out;
+ };
+ const root = (n: Node): string => (n.type === "Identifier" ? n.name : /MemberExpression$/.test(n.type) ? root(n.object) : "");
+ const drafts = new Set();
+
+ /** A handler's or an arrow's block: one line when it is short. */
+ function block(stmts: Node[]): string {
+ scopes.push(new Map());
+ const lines = stmts.flatMap(stmt);
+ scopes.pop();
+ if (!lines.length) return "{ }";
+ const one = `{ ${lines.join("; ")} }`;
+ if (lines.every((l) => !/^[\s}]|\{$/.test(l)) && one.length <= 72) return one;
+ return ["{", ...indented(lines, "\t"), "}"].join("\n");
+ }
+
+ // ---- markup
+
+ const isHandler = (name: string) => /^on[A-Z:]/.test(name);
+ const stripScope = (s: string) => s.split(/\s+/).filter((c) => c && !/^tsrx-[0-9a-f]+$/.test(c)).join(" ");
+ const tagName = (n: Node): string => (n.type === "JSXMemberExpression" ? `${tagName(n.object)}.${n.property.name}` : n.type === "JSXNamespacedName" ? `${n.namespace.name}:${n.name.name}` : n.name);
+ const attrOf = (el: Node, name: string): Node | undefined => el.openingElement.attributes.find((a: Node) => a.type === "JSXAttribute" && a.name.name === name);
+ const valueOf = (a: Node | undefined): Node | undefined => (a?.value?.type === "JSXExpressionContainer" ? a.value.expression : a?.value ?? undefined);
+
+ function attr(a: Node): string | undefined {
+ if (a.type === "JSXSpreadAttribute") return `{...${expr(a.argument)}}`;
+ const name = tagName(a.name);
+ const v = a.value as Node | null;
+ if (!v) return name;
+ if (v.type === "StringLiteral") {
+ if (name !== "class") return `${name}=${text(v)}`;
+ const c = stripScope(v.value);
+ return c ? `class="${c}"` : undefined;
+ }
+ let e = unwrap(v.expression);
+ if (name === "children" && e.type === "ArrayExpression" && !e.elements.length) return;
+ // `class={[e, "tsrx-…"]}`: the scoped class the compiler added
+ if (name === "class" && e.type === "ArrayExpression" && e.elements.length === 2 && e.elements[1]?.type === "StringLiteral" && !stripScope(e.elements[1].value)) e = unwrap(e.elements[0]);
+ if (name === "class" && e.type === "StringLiteral") return stripScope(e.value) ? `class="${stripScope(e.value)}"` : undefined;
+ if (isJsx(e)) return fail(e, `JSX in the ${name} attribute: pass it as children, or make it a component`), undefined;
+ if (name === "ref") return fail(a, "ref: element refs are not in this prototype"), undefined;
+ if (isHandler(name)) imperative++;
+ const s = expr(e);
+ if (isHandler(name)) imperative--;
+ return `${name}={${s}}`;
+ }
+
+ type Item = { inline: string } | { lines: string[] };
+ const inlineText = (s: string) => (/[{}<>]/.test(s) ? `{${JSON.stringify(s)}}` : s);
+
+ /** A block of markup with its own declarations: `() => { const x = createMemo(…); return
}`, as .rx lines. */
+ function region(f: Node): string[] {
+ const stmts: Node[] = f.body.body;
+ const view = stmts[stmts.length - 1];
+ if (view?.type !== "ReturnStatement" || !view.argument) return fail(f, "a block of markup that does not end with one return of it"), [];
+ scopes.push(new Map());
+ const setup = stmts.slice(0, -1);
+ declare(setup, true);
+ const lines = setup.flatMap((x) => decl(x, setup));
+ const out = markup([unwrap(view.argument)]);
+ scopes.pop();
+ return [...lines, ...out];
+ }
+ /** `(() => { …; return })()`: a region the view keeps as a call. */
+ const regionCall = (e: Node) =>
+ e.type === "CallExpression" && !e.arguments.length && isFn(unwrap(e.callee)) && !unwrap(e.callee).params.length && unwrap(e.callee).body.type === "BlockStatement" ? unwrap(e.callee) : undefined;
+
+ function child(c: Node): Item[] {
+ if (c.type === "JSXText") {
+ // JSX's own rule: lines trimmed, blank ones dropped, the rest joined by a space
+ const lines = (c.value as string).split("\n");
+ const kept = lines.map((l, i) => (i === 0 ? l : l.replace(/^[ \t]+/, ""))).map((l, i) => (i === lines.length - 1 ? l : l.replace(/[ \t]+$/, "")));
+ const s = kept.filter((l) => l).join(" ");
+ return s ? [{ inline: s }] : [];
+ }
+ if (c.type === "JSXExpressionContainer") {
+ const e = unwrap(c.expression);
+ if (e.type === "JSXEmptyExpression") return [];
+ if (e.type === "StringLiteral") return [{ inline: e.value }];
+ if (isJsx(e)) return child(e);
+ const r = regionCall(e);
+ if (r) return [{ lines: region(r) }];
+ if (e.type === "ConditionalExpression" && (isJsx(unwrap(e.consequent)) || isJsx(unwrap(e.alternate)))) return [{ lines: ifBlock(expr(e.test), markup([unwrap(e.consequent)]), markup([unwrap(e.alternate)])) }];
+ if (e.type === "LogicalExpression" && e.operator === "&&" && isJsx(unwrap(e.right))) return [{ lines: ifBlock(expr(e.left), markup([unwrap(e.right)]), []) }];
+ if (e.type === "NullLiteral") return [];
+ return [{ inline: `{${expr(e)}}` }];
+ }
+ if (c.type === "JSXFragment") return c.children.flatMap(child);
+ if (c.type === "JSXElement") return [{ lines: element(c) }];
+ if (c.type === "NullLiteral") return [];
+ fail(c, `${c.type} as a child`);
+ return [];
+ }
+
+ /** Children as lines: text and readers run together on a line, elements and control forms stand on their own. */
+ function markup(nodes: Node[]): string[] {
+ const items = nodes.flatMap((n) => (isJsx(n) || n.type.startsWith("JSX") ? child(n) : n.type === "NullLiteral" ? [] : [{ inline: `{${expr(n)}}` } as Item]));
+ const out: string[] = [];
+ let run: string[] = [];
+ const flush = () => {
+ if (!run.length) return;
+ // a space at either end of a line would be trimmed: keep it in a string
+ const first = run[0], last = run[run.length - 1];
+ if (!first.startsWith("{") && /^\s/.test(first)) run[0] = `{${JSON.stringify(first)}}`;
+ if (run.length > 1 && !last.startsWith("{") && /\s$/.test(last)) run[run.length - 1] = `{${JSON.stringify(last)}}`;
+ else if (run.length === 1 && !run[0].startsWith("{") && /\s$/.test(run[0])) run[0] = `{${JSON.stringify(first)}}`;
+ out.push(run.join(""));
+ run = [];
+ };
+ for (const it of items) {
+ if ("inline" in it) run.push(it.inline.startsWith("{") ? it.inline : inlineText(it.inline));
+ else flush(), out.push(...it.lines);
+ }
+ flush();
+ return out.flatMap((l) => l.split("\n"));
+ }
+
+ const ifBlock = (test: string, then: string[], other: string[]) =>
+ other.length ? [`{if ${test} {`, ...indented(then, INDENT), "} else {", ...indented(other, INDENT), "}}"] : [`{if ${test} {`, ...indented(then, INDENT), "}}"];
+
+ function element(el: Node): string[] {
+ const tag = tagName(el.openingElement.name);
+ const known = lookup(tag)?.kind === "plain" && SOLID_TAGS.has(tag);
+ const kids = () => markup(el.children);
+ const only = (...allowed: string[]) => {
+ for (const a of el.openingElement.attributes) if (a.type !== "JSXAttribute" || !allowed.includes(a.name.name)) fail(a, `<${tag}> with ${a.type === "JSXAttribute" ? a.name.name : "a spread"}: no .rx form in this prototype`);
+ };
+ const fallback = (): { head: string; lines: string[] } => {
+ const f = valueOf(attrOf(el, "fallback"));
+ if (!f || f.type === "NullLiteral") return { head: "", lines: [] };
+ const u = unwrap(f);
+ if (isFn(u)) {
+ const p = u.params[0];
+ const st: Node[] = u.body.type === "BlockStatement" ? u.body.body : [];
+ // `{ if (!(e() instanceof A)) throw e(); return <… /> }`: a typed boundary, which passes the rest up (R-f-4)
+ const classes = tag === "Errored" && p?.type === "Identifier" && st.length === 2 && st[1].type === "ReturnStatement" ? rethrows(st[0], p.name, true) : undefined;
+ if (classes && st[1].argument) {
+ scopes.push(new Map([[p.name, { kind: "read" } as Binding]]));
+ const lines = markup([unwrap(st[1].argument)]);
+ scopes.pop();
+ return { head: `(${p.name}: ${classes.join(" | ")})`, lines };
+ }
+ const b = returned(u);
+ if (!b && u.body.type === "BlockStatement" && !(p && uses([u.body], p.name))) return { head: "", lines: region(u) };
+ if (!b) return fail(u, `a <${tag}> fallback with statements`), { head: "", lines: [] };
+ scopes.push(new Map(p?.type === "Identifier" ? [[p.name, { kind: "read" } as Binding]] : []));
+ const lines = markup([unwrap(b)]);
+ scopes.pop();
+ return { head: p?.type === "Identifier" ? `(${p.name})` : "", lines };
+ }
+ return { head: "", lines: markup([u]) };
+ };
+ if (known && tag === "Show") {
+ only("when", "fallback");
+ const when = valueOf(attrOf(el, "when"));
+ if (!when) return fail(el, " without when"), [];
+ const fnKid = el.children.map((c: Node) => (c.type === "JSXExpressionContainer" ? unwrap(c.expression) : undefined)).find((x: Node | undefined) => x && isFn(x));
+ if (fnKid) {
+ // a branch that declares its own names: the view keeps it a function, its parameter unread
+ const p = fnKid.params[0];
+ if (fnKid.params.length > 1 || (p && (p.type !== "Identifier" || (p.name !== "__item" && uses([fnKid.body], p.name)))) || fnKid.body.type !== "BlockStatement")
+ return fail(el, " with a function child: read the value by name instead"), [];
+ return ifBlock(expr(when), region(fnKid), fallback().lines);
+ }
+ return ifBlock(expr(when), kids(), fallback().lines);
+ }
+ if (known && tag === "For") {
+ only("each", "fallback");
+ const each = valueOf(attrOf(el, "each"));
+ const f = el.children.map((c: Node) => (c.type === "JSXExpressionContainer" ? unwrap(c.expression) : c)).find(isFn);
+ const b = f && returned(f);
+ // a body with declarations before its view: the loop's own equations, as `{for x in xs { y = …; }}`
+ const block = f && !b && f.body.type === "BlockStatement" && f.body.body[f.body.body.length - 1]?.type === "ReturnStatement";
+ if (!each || !(b || block) || f.params.length !== 1 || f.params[0].type !== "Identifier") return fail(el, " needs each and one (item) => … child"), [];
+ scopes.push(new Map([[f.params[0].name, { kind: "plain" } as Binding]]));
+ const lines = b ? markup([unwrap(b)]) : region(f);
+ scopes.pop();
+ const loop = [`{for ${f.params[0].name} in ${expr(each)} {`, ...indented(lines, INDENT), "}}"];
+ // .rx's for has no fallback: the empty list is an if
+ const empty = fallback().lines;
+ return empty.length ? ifBlock(`${operand(expr(each))}.length > 0`, loop, empty) : loop;
+ }
+ if (known && (tag === "Errored" || tag === "Loading")) {
+ only(...(tag === "Loading" ? ["fallback", "on"] : ["fallback"]));
+ const f = fallback();
+ const on = tag === "Loading" ? valueOf(attrOf(el, "on")) : undefined;
+ const word = tag === "Errored" ? "errored" : on ? `loading on(${expr(on)})` : "loading";
+ const one = f.lines.length === 1 && f.lines[0].length <= 60;
+ return one
+ ? [`{${word} fallback${f.head} { ${f.lines[0]} } {`, ...indented(kids(), INDENT), "}}"]
+ : [`{${word} fallback${f.head} {`, ...indented(f.lines, INDENT), "} {", ...indented(kids(), INDENT), "}}"];
+ }
+ if (known) return fail(el, `<${tag}>: no .rx form in this prototype`), [];
+ if (lookup(tag)?.kind === "context") return fail(el, `<${tag} value>: a provider inside the view; .rx's provide covers a whole component, at the top of its view`), [];
+ const attrs = el.openingElement.attributes.map(attr).filter((a: string | undefined): a is string => a !== undefined);
+ const flat = attrs.join(" ");
+ const inner = el.openingElement.selfClosing ? [] : kids();
+ const end = inner.length ? ">" : "/>";
+ const head = flat.includes("\n") || tag.length + flat.length > 96 ? [`<${tag}`, ...attrs.flatMap((a: string) => indented(a.split("\n"), INDENT)), end] : [`<${tag}${flat ? " " + flat : ""}${inner.length ? ">" : " />"}`];
+ if (!inner.length) return head;
+ if (head.length === 1 && inner.length === 1 && !/^\{(if|for|errored|loading) /.test(inner[0]) && head[0].length + inner[0].length + tag.length + 3 <= 100) return [`${head[0]}${inner[0]}${tag}>`];
+ return [...head, ...indented(inner, INDENT), `${tag}>`];
+ }
+ const SOLID_TAGS = new Set(["Show", "For", "Errored", "Loading", "Switch", "Match", "Repeat", "Dynamic", "Portal"]);
+
+ // ---- declarations (a component's body, or the module's)
+
+ /** The prop pattern a component's first lines spell out, when every use of `props` is one of them. */
+ function propPattern(fn: Node, stmts: Node[]): { pattern: string; taken: Set } | undefined {
+ const p = fn.params[0];
+ if (!p || p.type !== "Identifier") return;
+ const fields: string[] = [];
+ const taken = new Set();
+ let rest = "";
+ const member = (m: Node | undefined) => (m && /MemberExpression$/.test(m.type) && m.object.type === "Identifier" && m.object.name === p.name && !m.computed ? (m.property.name as string) : undefined);
+ for (const s of stmts) {
+ const d = s.type === "VariableDeclaration" && s.declarations.length === 1 ? s.declarations[0] : undefined;
+ if (!d || d.id.type !== "Identifier" || !d.init) continue;
+ const name = callee(d.init);
+ const e = name === "createMemo" ? returned(d.init.arguments[0]) : undefined;
+ const u = e && unwrap(e);
+ if (u && member(u) !== undefined) {
+ fields.push(member(u) === d.id.name ? d.id.name : `${member(u)}: ${d.id.name}`);
+ taken.add(s);
+ } else if (u?.type === "ConditionalExpression" && unwrap(u.test).type === "BinaryExpression" && /^===?$/.test(unwrap(u.test).operator) && member(unwrap(u.test).left) !== undefined && text(unwrap(u.test).right) === "undefined" && member(unwrap(u.alternate)) === member(unwrap(u.test).left)) {
+ const k = member(unwrap(u.test).left)!;
+ fields.push(`${k === d.id.name ? k : `${k}: ${d.id.name}`} = ${expr(u.consequent)}`);
+ taken.add(s);
+ } else if (name === "omit" && d.init.arguments[0]?.type === "Identifier" && d.init.arguments[0].name === p.name && d.init.arguments.slice(1).every((a: Node) => a.type === "StringLiteral")) {
+ rest = d.id.name;
+ taken.add(s);
+ }
+ }
+ if (!taken.size) return;
+ // any other read of props keeps the plain parameter
+ let others = 0;
+ const count = (n: Node) => {
+ if (taken.has(n)) return;
+ if (n.type === "Identifier" && n.name === p.name) others++;
+ for (const k of Object.keys(n)) {
+ if (k === "loc") continue;
+ for (const c of Array.isArray(n[k]) ? n[k] : [n[k]]) if (c && typeof c.type === "string") count(c);
+ }
+ };
+ stmts.forEach(count);
+ if (others) return;
+ return { pattern: `{ ${[...fields, ...(rest ? [`...${rest}`] : [])].join(", ")} }`, taken };
+ }
+
+ const typeArg = (call: Node) => (call.typeParameters?.params?.length === 1 ? `: ${text(call.typeParameters.params[0])}` : call.typeArguments?.params?.length === 1 ? `: ${text(call.typeArguments.params[0])}` : "");
+
+ /** Names a declaration list makes, so a use above its declaration still reads as what it is. */
+ function declare(stmts: Node[], setup = false) {
+ const later: Node[] = [];
+ for (const s of stmts) {
+ if (s.type === "ClassDeclaration" && s.id && s.superClass?.type === "Identifier" && s.superClass.name === "Error") bind(s.id.name, { kind: "error" });
+ if (s.type === "FunctionDeclaration" && s.id) bind(s.id.name, isServer(s) ? { kind: "server" } : setup && !returned(s) ? { kind: "handler", fn: s } : { kind: "plain" });
+ if (s.type !== "VariableDeclaration") continue;
+ for (const d of s.declarations) {
+ const name = callee(d.init);
+ if (d.id.type === "ArrayPattern" && d.id.elements.length >= 1 && d.id.elements.length <= 2 && d.id.elements.every((e: Node | null) => e?.type === "Identifier")) {
+ // `const [value] = createSignal(…)`: a setter nobody names
+ const [get, set = `set$${d.id.elements[0].name}`] = d.id.elements.map((e: Node) => e.name as string);
+ if (name === "createSignal") {
+ const truth = /^(.+)\$truth$/.exec(get);
+ bind(get, { kind: "read" });
+ bind(set, { kind: "setter", of: truth ? truth[1] : get });
+ } else if (name === "createStore" || name === "createOptimisticStore") {
+ bind(get, { kind: "store" });
+ bind(set, { kind: "setter", of: get, guess: name === "createOptimisticStore" });
+ } else if (name === "createOptimistic") {
+ bind(get, { kind: "read" });
+ bind(set, { kind: "setter", of: get, guess: true });
+ }
+ } else if (d.id.type === "Identifier") {
+ if (isServer(d.init) || (/CallExpression$/.test(d.init?.type ?? "") && d.init.arguments.some(isServer))) bind(d.id.name, { kind: "server" });
+ else if (name === "createMemo" || name === "createDeferred" || name === "useContext") bind(d.id.name, { kind: "read" });
+ else if (name === "createContext") bind(d.id.name, { kind: "context", as: contextName(d.id.name) });
+ else if (d.init?.type === "ArrowFunctionExpression" && d.init.body.type === "BlockStatement" && !returned(d.init) && (setup || !d.init.async)) bind(d.id.name, { kind: "handler", fn: d.init });
+ else if (setup && d.init?.type === "ArrowFunctionExpression") (bind(d.id.name, { kind: "plain" }), later.push(d));
+ else if (s.kind === "let" && (setup || d.init) && !isFn(d.init) && !/^create[A-Z]/.test(name ?? "")) bind(d.id.name, { kind: "mutable" });
+ else if (name === "createProjection" || name === "omit" || name === "merge") bind(d.id.name, { kind: "store" });
+ else bind(d.id.name, { kind: "plain" });
+ }
+ }
+ }
+ // `const add = () => setItems(…)`: one expression, but a write, so not a fn
+ for (const d of later) if (isWrite(unwrap(d.init.body))) bind(d.id.name, { kind: "handler", fn: d.init });
+ }
+
+ /** A function of the setup that writes, as an action: the .rx form of a named procedure. */
+ function actionDecl(id: string, f: Node): string[] {
+ imperative++;
+ scopes.push(new Map(f.params.flatMap(names).map((n: string) => [n, { kind: "plain" } as Binding])));
+ const lines = (f.body.type === "BlockStatement" ? f.body.body : [{ ...f.body, type: "ExpressionStatement", expression: f.body }]).flatMap(stmt);
+ scopes.pop();
+ imperative--;
+ return [`action ${id}(${params(f)}) {`, ...indented(lines, INDENT), "}"];
+ }
+
+ /** `createMemo(load)`: a function passed by name is asked with no arguments. */
+ const byName = (f: Node | undefined) => f?.type === "Identifier" && (lookup(f.name)?.kind === "import" || lookup(f.name)?.kind === "plain");
+ const asked = (f: Node) => {
+ const b = lookup(f.name);
+ if (b?.kind === "import") pureImports.add(f.name);
+ return `${b?.kind === "import" && b.async ? "await " : ""}${f.name}()`;
+ };
+
+ const isPeek = (s: string) => {
+ if (!s.startsWith("peek(") || !s.endsWith(")")) return false;
+ let depth = 0;
+ for (let i = 4; i < s.length; i++) if ((depth += s[i] === "(" ? 1 : s[i] === ")" ? -1 : 0) === 0) return i === s.length - 1;
+ return false;
+ };
+ /** A source's first value: a snapshot, so one that reads a reactive name is a peek (E-4). */
+ const first = (n: Node) => {
+ const before = reactive;
+ const s = expr(n);
+ return reactive > before && !isPeek(s) ? `peek(${s})` : s;
+ };
+
+ /** `effect (inputs) { … }` over a function's statements, its parameters standing for the inputs. */
+ function effectBlock(inputs: string, f: Node, bound: Map): string[] {
+ imperative++;
+ scopes.push(bound);
+ const lines = (f.body.type === "BlockStatement" ? f.body.body : [{ ...f.body, type: "ExpressionStatement", expression: f.body }]).flatMap(stmt);
+ scopes.pop();
+ imperative--;
+ return [`effect (${inputs}) {`, ...indented(lines, INDENT), "}"];
+ }
+
+ /** `createEffect(compute, effect)`: what compute returns is the inputs, and effect's parameter reads them (EF-1). */
+ function effectDecl(e: Node): string[] {
+ const [compute, effect] = e.arguments as Node[];
+ if (!isFn(compute) || !isFn(effect)) return fail(e, "createEffect needs its two functions written in place: what it reads, then what it does"), [];
+ if (effect.params.length > 1) return fail(effect, "an effect that takes its previous value: .rx has pre x for the value before"), [];
+ const value = returned(compute);
+ if (compute.body.type === "BlockStatement" && !value && compute.body.body.length) return fail(compute, "an effect whose first function has statements: its inputs are expressions in .rx"), [];
+ const u = value && unwrap(value);
+ const param = effect.params[0] as Node | undefined;
+ const bound = new Map();
+ let inputs: string[] = [];
+ // `() => [a(), b()]` read as `([a, b]) => …`: one input each
+ if (u?.type === "ArrayExpression" && param?.type === "ArrayPattern" && param.elements.every((x: Node | null) => !x || x.type === "Identifier") && u.elements.every((x: Node | null) => x && x.type !== "SpreadElement")) {
+ inputs = u.elements.map((x: Node) => expr(x));
+ param.elements.forEach((x: Node | null, i: number) => x && bound.set(x.name, { kind: "input", as: `$${i}` }));
+ } else if (u) {
+ inputs = [expr(u)];
+ if (param?.type === "Identifier") bound.set(param.name, { kind: "input", as: "$0" });
+ else if (param) return fail(param, "an effect that takes its value apart in its parameter: name it, and read its fields"), [];
+ }
+ return effectBlock(inputs.join(", "), effect, bound);
+ }
+
+ /** `async function f(a) { "use server"; … }`: `server fn f(a) { … }` (12 SF-1). */
+ function serverDecl(id: string, f: Node): string[] {
+ const outer = inServer;
+ inServer = id;
+ serverCalls.set(id, new Set());
+ const lines = serverBody(f);
+ inServer = outer;
+ return [`server fn ${id}(${params(f)}) {`, ...indented(lines, INDENT), "}"];
+ }
+
+ function decl(s: Node, all: Node[]): string[] {
+ if (s.type === "ClassDeclaration" && lookup(s.id?.name)?.kind === "error") return errorDecl(s);
+ if (s.type === "FunctionDeclaration" && isServer(s)) return serverDecl(s.id.name, s);
+ if (s.type === "FunctionDeclaration") {
+ const h = lookup(s.id.name);
+ return h?.kind === "handler" ? actionDecl(s.id.name, s) : fnDecl(s.id.name, s);
+ }
+ if (s.type === "TSTypeAliasDeclaration" || s.type === "TSInterfaceDeclaration") return place(text(s), lineIndent(s.start), "").split("\n");
+ if (s.type === "ExpressionStatement") {
+ const e = unwrap(s.expression);
+ const name = callee(e);
+ if (name === "createEffect") return effectDecl(e);
+ // in a component's setup, "once this has settled" and "when this goes away" are an effect with no inputs (EF-4, EF-5)
+ if ((name === "onSettled" || name === "onMount") && isFn(e.arguments[0]) && !e.arguments[0].params.length) return effectBlock("", e.arguments[0], new Map());
+ if (name === "onCleanup" && isFn(e.arguments[0]) && !e.arguments[0].params.length) return ["effect () {", ...indented(`return ${expr(e.arguments[0])}`.split("\n"), INDENT), "}"];
+ if (name === "createRenderEffect") return fail(s, "createRenderEffect: a render effect has no .rx form; effect (inputs) { … } runs after the view"), [];
+ return fail(s, `${text(s).split("\n")[0]}: a statement in a component's setup has no .rx form`), [];
+ }
+ if (s.type !== "VariableDeclaration") return fail(s, `${s.type.replace(/Statement|Declaration/, "").toLowerCase()} in a component's setup: no .rx form in this prototype`), [];
+ return s.declarations.flatMap((d: Node): string[] => {
+ const init = d.init as Node | undefined;
+ const name = callee(init);
+ const a: Node[] = init?.arguments ?? [];
+ const question = (f: Node, awaited: boolean) => {
+ if (f.type === "Identifier") return asked(f);
+ const e = returned(f);
+ if (!e) return fail(f, "a derived value with statements: .rx equations are one expression");
+ const s = expr(e);
+ return awaited && !/^await\b/.test(s) && /Call/.test(unwrap(e).type) ? `await ${s}` : s;
+ };
+ if (d.id.type === "ArrayPattern" && name) {
+ const get = d.id.elements[0]?.name as string;
+ if (name === "createSignal") {
+ const truth = /^(.+)\$truth$/.exec(get);
+ // `createSignal(fn)`: a source with a question. The view's `x$truth` is one whose question is asked: an await
+ if (isFn(a[0]) || byName(a[0])) {
+ const v = paintOf(a[1]);
+ // a first paint stands for an answer still to come: the question is an await
+ const q = question(a[0], !!truth || !!v);
+ return `source ${truth ? truth[1] : get}${typeArg(init!)} = ${q}${v ? ` -> ${expr(v)}` : ""}`.split("\n");
+ }
+ return `source ${get}${typeArg(init!)} := ${a[0] ? first(a[0]) : "undefined"}`.split("\n");
+ }
+ if (name === "createStore") {
+ if (isFn(a[0])) return `source ${get}${typeArg(init!)} = ${question(a[0], false)}`.split("\n");
+ return `source ${get}${typeArg(init!)} := ${a[0] ? first(a[0]) : "{}"}`.split("\n");
+ }
+ if (name === "createOptimistic" || name === "createOptimisticStore") {
+ const e = isFn(a[0]) ? returned(a[0]) : undefined;
+ // over `x$truth`: the pair is one source, declared where its truth is
+ if (e && callee(e) === `${get}$truth`) return [];
+ // `{ key: "id" }`: each row keeps its identity by that field (ST-4)
+ const k = a[2]?.type === "ObjectExpression" ? a[2].properties.find((q: Node) => q.type === "ObjectProperty" && (q.key.name ?? q.key.value) === "key")?.value : undefined;
+ const keyed = k?.type === "StringLiteral" && /^[A-Za-z_$][\w$]*$/.test(k.value) ? ` key ${k.value}` : "";
+ if (isFn(a[0])) return `source ${get}${typeArg(init!)}${keyed} = ${question(a[0], false)}`.split("\n");
+ // over a plain value: a source whose question is that constant, which is what can take a guess (ST-5c)
+ return `source ${get}${typeArg(init!)} = ${a[0] ? expr(a[0]) : "undefined"}`.split("\n");
+ }
+ }
+ if (d.id.type === "Identifier" && !init && lookup(d.id.name)?.kind === "mutable") return [`source ${d.id.name}${d.id.typeAnnotation ? text(d.id.typeAnnotation) : ""} := undefined`];
+ if (d.id.type !== "Identifier" || !init) return fail(d, `${text(d).split("\n")[0]}: no .rx form in this prototype`), [];
+ const id = d.id.name as string;
+ if (name === "createContext") {
+ // the default is an accessor, as the provided value is
+ const dv = a[0] && isFn(a[0]) && !a[0].params.length ? returned(a[0]) : a[0];
+ return `context ${contextName(id)}${typeArg(init)} ${dv ? `= ${expr(dv)}` : ""}`.trimEnd().split("\n");
+ }
+ if (name === "useContext") {
+ const c = contextOf(a[0]);
+ return c ? [`${id} = use ${c}`] : (fail(d, `${id}: useContext of something that is not a context`), []);
+ }
+ if (name === "createDeferred") {
+ const e = returned(a[0]);
+ return e ? `deferred ${id} = ${expr(e)}`.split("\n") : (fail(d, `${id}: a deferred value with statements; .rx equations are one expression`), []);
+ }
+ if (name === "createMemo" && byName(a[0])) return `${id} = ${asked(a[0])}`.split("\n");
+ if (name === "createMemo" && caughtMemo(a[0])) {
+ const { x, c } = caughtMemo(a[0])!;
+ const text = expr(x);
+ const tail = clause(c);
+ // the await's own catch already says it: `await e -> v catch (e) => alt` is one clause
+ return `${id} = ${text.endsWith(tail) ? text : `${text} ${tail}`}`.split("\n");
+ }
+ if (name === "createMemo" && paintOf(a[1])) {
+ const e = returned(a[0]);
+ if (!e) return fail(d, `${id}: a memo with statements; .rx equations are one expression`), [];
+ const v = expr(paintOf(a[1])!);
+ const u = unwrap(e);
+ const caught = /CallExpression$/.test(u.type) && /MemberExpression$/.test(u.callee.type) && u.callee.property.name === "catch";
+ if (caught) paint = v;
+ let text = expr(e);
+ paint = undefined;
+ // a first paint stands for an answer still to come: with no await written, the call that asks it is one, on
+ // whichever branch it sits
+ const asked = (x: Node): string => {
+ const w = unwrap(x);
+ if (w.type === "ConditionalExpression") return `${expr(w.test)} ? ${asked(w.consequent)} : ${asked(w.alternate)}`;
+ return /Call/.test(w.type) ? `await ${expr(w)}` : expr(w);
+ };
+ if (!caught) text = `${/\bawait\b/.test(text) ? text : asked(u)} -> ${v}`;
+ // `i$x`: the answer a caught read of x reads, written back where it is read
+ if (/^i\$[\w$]+$/.test(id)) return bind(id, { kind: "await", text }), [];
+ return `${id} = ${text}`.split("\n");
+ }
+ if (name === "createMemo") {
+ const e = returned(a[0]);
+ if (!e) return fail(d, `${id}: a memo with statements; .rx equations are one expression`), [];
+ // `i$x`: the answer a caught read of x reads, written back where it is read
+ if (/^i\$[\w$]+$/.test(id)) {
+ const t = expr(e);
+ return bind(id, { kind: "await", text: /^await\b/.test(t) || !/Call/.test(unwrap(e).type) ? t : `await ${t}` }), [];
+ }
+ if (/\$await\d*$/.test(id)) {
+ // an await under a condition is asked only on its branch: `c ? ask : undefined`, read where c holds
+ const u = unwrap(e);
+ const s = expr(u.type === "ConditionalExpression" && unwrap(u.alternate).type === "Identifier" && unwrap(u.alternate).name === "undefined" ? u.consequent : e);
+ bind(id, { kind: "await", text: /^await\b/.test(s) ? s : `await ${s}` });
+ return [];
+ }
+ // `x$answer`, read only by the keyed projection under it
+ if (/\$answer$/.test(id) && all.some((o) => o.type === "VariableDeclaration" && o.declarations.some((p: Node) => callee(p.init) === "createProjection" && callee(returned(p.init.arguments[0])) === id))) return [];
+ return `${id} = ${expr(e)}`.split("\n");
+ }
+ if (name === "createProjection") {
+ const f = a[0];
+ const key = a[2]?.type === "ObjectExpression" ? a[2].properties.find((p: Node) => p.key?.name === "key")?.value : undefined;
+ if (key) {
+ const e = f && returned(f);
+ const inner = e && callee(e);
+ const answer = inner && all.flatMap((o) => (o.type === "VariableDeclaration" ? o.declarations : [])).find((p: Node) => p.id.name === inner && /\$answer$/.test(inner));
+ const of = answer ? returned(answer.init.arguments[0]) : e;
+ if (!of || key.type !== "StringLiteral") return fail(d, `${id}: a keyed projection this prototype does not read`), [];
+ return `${id} key ${key.value} = ${expr(of)}`.split("\n");
+ }
+ if (isFn(f) && f.params.length === 1 && f.params[0].type === "Identifier" && f.body.type === "BlockStatement") {
+ // .rx names a draft d: the function's own name for it stands for d
+ const param = f.params[0].name as string;
+ if (param !== "d") aliases.set(param, { store: "d", fn: f, written: new Map() });
+ drafts.add(param);
+ imperative++;
+ derived++;
+ scopes.push(new Map([[param, { kind: "plain" } as Binding]]));
+ const lines = f.body.body.flatMap(stmt);
+ scopes.pop();
+ derived--;
+ imperative--;
+ drafts.delete(param);
+ aliases.delete(param);
+ return [`${id} = draft(pre ${id} -> ${a[1] ? expr(a[1]) : "{}"}) {`, ...indented(lines, INDENT), "}"];
+ }
+ // `createProjection(() => value)`: a structured equation (ST-1), its value an object or a list
+ const value = isFn(f) && (f.params.length === 0 || (f.params[0].type === "Identifier" && !uses([f.body], f.params[0].name))) ? returned(f) : undefined;
+ if (value) return `${id} = ${expr(value)}`.split("\n");
+ return fail(d, `${id}: a projection this prototype does not read`), [];
+ }
+ if (name === "action") {
+ const f = a[0];
+ if (!isFn(f) || f.body.type !== "BlockStatement") return fail(d, `${id}: an action needs a function with a body`), [];
+ return actionDecl(id, f);
+ }
+ if (name === "omit") return fail(d, `${id} = omit(…): only read as the rest of a prop pattern`), [];
+ if (name && /^create[A-Z]/.test(name) && lookup(name)?.kind === "plain") return fail(d, `${name}: no .rx form in this prototype`), [];
+ const h = lookup(id);
+ if (isServer(init)) return serverDecl(id, init);
+ if (h?.kind === "server") {
+ // a wrapped one: the wrapper is applied where the equation is declared
+ const outer = inServer;
+ inServer = id;
+ serverCalls.set(id, new Set());
+ const wrapped = `${id} = ${expr(init)}`.split("\n");
+ inServer = outer;
+ return wrapped;
+ }
+ if (h?.kind === "handler") return actionDecl(id, h.fn);
+ if (h?.kind === "mutable") return `source ${id}${d.id.typeAnnotation ? text(d.id.typeAnnotation) : ""} := ${first(init)}`.split("\n");
+ if (init.type === "Identifier" && RX_BUILTINS.has(init.name) && !lookup(init.name)) return preludeAliases.add(`${init.name} as ${id}`), [];
+ if (isFn(init)) return fnDecl(id, init);
+ return `${id}${d.id.typeAnnotation ? text(d.id.typeAnnotation) : ""} = ${expr(init)}`.split("\n");
+ });
+ }
+
+ /** `if (c) return a; …; return d`: one expression, `c ? a : … : d`. */
+ const guarded = (f: Node): string | undefined => {
+ if (f.body?.type !== "BlockStatement") return;
+ const steps: Node[] = f.body.body;
+ const last = steps[steps.length - 1];
+ if (steps.length < 2 || last?.type !== "ReturnStatement" || !last.argument) return;
+ const arms: string[] = [];
+ const arm = (n: Node) => (/^(Conditional|Sequence|Assignment|ArrowFunction)Expression$/.test(unwrap(n).type) ? `(${expr(n)})` : expr(n));
+ for (const x of steps.slice(0, -1)) {
+ const then = x.type === "IfStatement" && !x.alternate ? (x.consequent.type === "BlockStatement" && x.consequent.body.length === 1 ? x.consequent.body[0] : x.consequent) : undefined;
+ if (then?.type === "ThrowStatement") {
+ arms.push(`${arm(x.test)} ? throw ${expr(then.argument)}`);
+ continue;
+ }
+ if (then?.type !== "ReturnStatement" || !then.argument) return;
+ arms.push(`${arm(x.test)} ? ${arm(then.argument)}`);
+ }
+ return [...arms, arm(last.argument)].join(" : ");
+ };
+ function fnDecl(name: string, f: Node): string[] {
+ if (!returned(f) && !f.async && !f.generator) {
+ scopes.push(new Map(f.params.flatMap(names).map((n: string) => [n, { kind: "plain" } as Binding])));
+ const g = guarded(f);
+ scopes.pop();
+ if (g !== undefined) {
+ scopes.push(new Map(f.params.flatMap(names).map((n: string) => [n, { kind: "plain" } as Binding])));
+ const out = `fn ${name}(${params(f)}) => ${guarded(f)}`.split("\n");
+ scopes.pop();
+ return out;
+ }
+ }
+ const e = returned(f);
+ if (!e) return fail(f, `${name}: a function with statements; .rx fn is one expression`), [];
+ if (f.async || f.generator) return fail(f, `${name}: an async function; in .rx an await is written where it is read`), [];
+ scopes.push(new Map(f.params.flatMap(names).map((n: string) => [n, { kind: "plain" } as Binding])));
+ const out = `fn ${name}(${params(f)}) => ${expr(e)}`.split("\n");
+ scopes.pop();
+ return out;
+ }
+
+ const returnsJsx = (f: Node) => {
+ const last = f.body.type === "BlockStatement" ? f.body.body[f.body.body.length - 1] : undefined;
+ const e = last?.type === "ReturnStatement" ? last.argument : f.body.type !== "BlockStatement" ? f.body : undefined;
+ return !!e && (isJsx(unwrap(e)) || unwrap(e).type === "NullLiteral");
+ };
+
+ /** A context's provider element: its .rx name, the value given, and what it wraps. */
+ function provider(el: Node | undefined): { name: string; value: string; kids: Node[] } | undefined {
+ if (el?.type !== "JSXElement" || el.openingElement.name.type !== "JSXIdentifier") return;
+ const attrs = el.openingElement.attributes;
+ const v = valueOf(attrOf(el, "value"));
+ const tag = el.openingElement.name.name as string;
+ // an imported component is not a context: only an import named …Context, given only a value, is read as one
+ if (attrs.length !== 1 || !v || (lookup(tag)?.kind === "import" && !/Context$/.test(tag))) return;
+ const c = contextOf({ ...el.openingElement.name, type: "Identifier" });
+ if (!c) return;
+ const f = unwrap(v);
+ const value = isFn(f) && !f.params.length && returned(f) ? expr(returned(f)!) : f.type === "Identifier" && lookup(f.name)?.kind === "read" ? (reactive++, f.name) : expr(f);
+ const kids = el.children.filter((k: Node) => !(k.type === "JSXText" && !k.value.trim()));
+ return { name: c, value, kids };
+ }
+ function component(name: string, f: Node, prefix: string): string[] {
+ scopes.push(new Map());
+ const stmts: Node[] = f.body.type === "BlockStatement" ? f.body.body : [{ ...f.body, type: "ReturnStatement", argument: f.body }];
+ const setup = stmts.slice(0, -1);
+ const view = stmts[stmts.length - 1];
+ declare(setup, true);
+ const p = f.params[0] as Node | undefined;
+ if (f.params.length > 1 || (p && p.type !== "Identifier")) fail(p ?? f, `${name}: a component takes one props parameter; destructuring it in Solid loses reactivity`);
+ const pattern = propPattern(f, setup);
+ let head = "";
+ if (pattern) head = pattern.pattern;
+ else if (p?.type === "Identifier" && uses(stmts, p.name)) head = text(p);
+ if (p?.type === "Identifier") bind(p.name, { kind: "plain" });
+ let at = f.body.start;
+ const lines = setup.flatMap((s) => {
+ const notes = leading(s, at);
+ at = s.end;
+ const d = pattern?.taken.has(s) ? [] : decl(s, setup);
+ return d.length ? [...notes, ...d] : [];
+ });
+ let root = view?.type === "ReturnStatement" && view.argument ? unwrap(view.argument) : undefined;
+ // `… ` around the whole view: `provide c = v` (07)
+ // the first provide is the innermost provider: read from the outside, they come last first
+ const provides: string[] = [];
+ for (let p = provider(root); p; p = provider(root)) {
+ provides.unshift(`provide ${p.name} = ${p.value}`);
+ root = p.kids.length === 1 ? p.kids[0] : { ...root!, type: "JSXFragment", children: p.kids };
+ }
+ lines.push(...provides);
+ const out = markup(root ? (root.type === "JSXFragment" ? root.children : [root]) : []);
+ if (view?.type !== "ReturnStatement") fail(view ?? f, `${name}: a component ends with one return of its markup`);
+ scopes.pop();
+ return [`${prefix}component ${name}(${head}) {`, ...indented(lines, INDENT), ...(lines.length && out.length ? [""] : []), ...indented(out, INDENT), "}"];
+ }
+ const uses = (nodes: Node[], name: string): boolean =>
+ nodes.some(function has(n: Node): boolean {
+ if ((n.type === "Identifier" || n.type === "JSXIdentifier") && n.name === name) return true;
+ return Object.keys(n).some((k) => k !== "loc" && (Array.isArray(n[k]) ? n[k] : [n[k]]).some((c: any) => c && typeof c.type === "string" && has(c)));
+ });
+
+ // ---- the module
+
+ const program: Node[] = ast.program.body;
+ const inner = (s: Node) => (s.type === "ExportNamedDeclaration" || s.type === "ExportDefaultDeclaration" ? s.declaration : s) as Node | null;
+ const declared = (d: Node): string[] => (d.type === "FunctionDeclaration" && d.id ? [d.id.name] : d.type === "VariableDeclaration" ? d.declarations.flatMap((v: Node) => names(v.id)) : []);
+ const fnOf = (d: Node, name: string): Node | undefined => (d.type === "FunctionDeclaration" ? d : d.type === "VariableDeclaration" ? d.declarations.find((v: Node) => v.id.name === name)?.init : undefined);
+ /** Declared async, or returning a promise it makes: a call from reactive scope is an await. */
+ const isAsync = (f: Node | undefined) => {
+ if (!f || (!isFn(f) && f.type !== "FunctionDeclaration")) return false;
+ const r = returned(f);
+ const u = r && unwrap(r);
+ return !!f.async || (!!u && ((u.type === "NewExpression" && u.callee.name === "Promise") || callee(u) === "fetch"));
+ };
+
+ type Top = { s: Node; d: Node; from: number; comps: [string, Node][]; js: boolean; hook?: boolean; both?: boolean };
+ const solidNames = program.filter((s) => s.type === "ImportDeclaration" && SOLID.has(s.source.value)).flatMap((s) => s.specifiers.map((sp: Node) => sp.local.name as string));
+ const tops: Top[] = [];
+ let defaultName = "";
+ let mounted = "";
+ let end = 0;
+ for (const s of program) {
+ const from = end;
+ end = s.end;
+ if (s.type === "ImportDeclaration") continue;
+ const d = inner(s);
+ if (!d) continue;
+ if (s.type === "ExportDefaultDeclaration" && d.type === "Identifier") {
+ defaultName = d.name;
+ continue;
+ }
+ // `render(() => , root)`: the entry's default component is what is mounted
+ if (s.type === "ExpressionStatement" && callee(s.expression) === "render") {
+ mounted = /<([A-Z][\w$]*)/.exec(text(s))?.[1] ?? "";
+ continue;
+ }
+ const fns: [string, Node][] =
+ d.type === "FunctionDeclaration" ? [[d.id?.name ?? "App", d]] : d.type === "VariableDeclaration" ? d.declarations.filter((v: Node) => isFn(v.init) && v.id.type === "Identifier").map((v: Node) => [v.id.name, v.init]) : isFn(d) ? [["App", d]] : [];
+ const comps = fns.filter(([name, f]) => /^[A-Z]/.test(name) && returnsJsx(f));
+ const all = comps.length && comps.length === (d.type === "VariableDeclaration" ? d.declarations.length : 1);
+ if (s.type === "ExportDefaultDeclaration" && !all) {
+ const left = [...new Set(text(s).match(/\b__rt\.\w+/g) ?? [])];
+ fail(s, left.length ? `the view still uses the runtime (${left.join(", ")}): no Solid form to read` : "the default export is not a component");
+ }
+ else {
+ if (s.type === "ExportDefaultDeclaration") defaultName = comps[0][0];
+ tops.push({ s, d, from, comps: all ? comps : [], js: false });
+ }
+ }
+ const decls = tops.map((t) => t.d);
+ for (const s of program) {
+ if (s.type !== "ImportDeclaration") continue;
+ // a name another module of the program exports is what it is there: a source or a memo is read as itself (09)
+ const mod = SOLID.has(s.source.value) ? undefined : opts.modules?.(s.source.value);
+ const kinds = mod ? exportedKinds(mod) : undefined;
+ for (const sp of s.specifiers) {
+ const k = sp.type === "ImportSpecifier" ? kinds?.get(sp.imported.name) : undefined;
+ if (k?.kind === "context") renamed.set(sp.local.name, k.as);
+ bind(sp.local.name, SOLID.has(s.source.value) ? { kind: "plain" } : k ?? { kind: "import", from: s.source.value });
+ }
+ }
+ declare(decls);
+
+ // plain TypeScript with no .rx form (statements, async, new) stays TypeScript, with what it reads, in its own module
+ for (const t of tops) {
+ if (t.comps.length || (t.d.type !== "VariableDeclaration" && t.d.type !== "FunctionDeclaration")) continue;
+ if (t.d.type === "VariableDeclaration" && t.d.declarations.some((v: Node) => /^create[A-Z]/.test(callee(v.init) ?? ""))) continue;
+ const before = problems.length;
+ const known = new Map(globals);
+ decl(t.d, decls);
+ t.js = problems.length > before || globals.size > known.size || declared(t.d).some((n) => lookup(n)?.kind === "handler");
+ problems.length = before;
+ globals.clear();
+ for (const [k, v] of known) globals.set(k, v);
+ // a function that makes signals or memos is not plain TypeScript: it cannot move, and it has no .rx form
+ if (t.js && solidNames.some((n) => uses([t.d], n))) (t.js = false), (t.hook = true);
+ }
+ for (let grew = true; grew; ) {
+ grew = false;
+ for (const t of tops) {
+ if (t.js || t.comps.length || !/^(Variable|Function)Declaration$/.test(t.d.type)) continue;
+ if (t.d.type === "VariableDeclaration" && t.d.declarations.some((v: Node) => /^create[A-Z]/.test(callee(v.init) ?? ""))) continue;
+ if (declared(t.d).some((n) => tops.some((o) => o.js && uses([o.d], n)))) t.js = grew = true;
+ }
+ }
+ // a type the helpers name goes with them, and stays here too if the .rx names it
+ for (const t of tops) {
+ if (!/^TS(TypeAlias|Interface)Declaration$/.test(t.d.type)) continue;
+ const name = t.d.id.name as string;
+ if (!tops.some((o) => o.js && o !== t && uses([o.d], name))) continue;
+ t.js = true;
+ t.both = tops.some((o) => !o.js && uses([o.d], name));
+ }
+ const rxTops = tops.filter((t) => !t.js || t.both);
+ const helperNames = tops.filter((t) => t.js).flatMap((t) => declared(t.d).filter((n) => uses(rxTops.map((o) => o.d), n)));
+ const helperFrom = "./" + HELPERS.replace(/\.\w+$/, "");
+ const asyncMembers = (d: Node, n: string) => {
+ const o = d.type === "VariableDeclaration" ? d.declarations.find((v: Node) => v.id.name === n)?.init : undefined;
+ const u = o && unwrap(o);
+ if (u?.type !== "ObjectExpression") return;
+ return new Set(u.properties.filter((q: Node) => q.key?.name && (q.type === "ObjectMethod" ? q.async : isAsync(q.value))).map((q: Node) => q.key.name));
+ };
+ for (const t of tops) if (t.js) for (const n of declared(t.d)) bind(n, { kind: "import", from: helperFrom, async: isAsync(fnOf(t.d, n)), asyncMembers: asyncMembers(t.d, n) });
+
+ for (const t of rxTops) if (!t.comps.length && !t.hook) for (const n of declared(t.d)) if (lookup(n)?.kind === "plain") bind(n, { kind: "equation" });
+ reactive = 0;
+
+ const comps = rxTops.flatMap((t) => t.comps.map(([name]) => name));
+ // a module that exports its components by name has no default of its own
+ const unnamed = rxTops.filter((t) => t.s.type !== "ExportNamedDeclaration").flatMap((t) => t.comps.map(([name]) => name));
+ // a module that exports names is another module's: it has no default of its own unless it says so
+ const named = program.some((st) => st.type === "ExportNamedDeclaration");
+ if (!defaultName) defaultName = comps.includes(mounted) ? mounted : comps.includes("App") ? "App" : named ? "" : unnamed[unnamed.length - 1] ?? "";
+ // `function Root() { return }` as the default: a module-level `provide c = v`, and App the default
+ let rootOf: Node | undefined;
+ const provided: string[] = [];
+ const rootFn = rxTops.flatMap((t) => t.comps).find(([name]) => name === defaultName)?.[1];
+ const rootBody: Node[] = rootFn?.body.type === "BlockStatement" ? rootFn.body.body : [];
+ if (rootFn && !rootFn.params.length && rootBody.length === 1 && rootBody[0].type === "ReturnStatement" && rootBody[0].argument) {
+ let el: Node | undefined = unwrap(rootBody[0].argument);
+ const lines: string[] = [];
+ for (let p = provider(el); p; p = provider(el)) lines.unshift(`provide ${p.name} = ${p.value}`), (el = p.kids.length === 1 ? unwrap(p.kids[0]) : undefined);
+ const inner = el?.type === "JSXElement" && el.openingElement.selfClosing && el.openingElement.name.type === "JSXIdentifier" ? (el.openingElement.name.name as string) : "";
+ const bare = el?.openingElement?.attributes.every((a: Node) => a.type === "JSXAttribute" && a.name.name === "children");
+ if (lines.length && comps.includes(inner) && inner !== defaultName && bare) (rootOf = rootFn), provided.push(...lines), (defaultName = inner);
+ }
+
+ const out: string[][] = [];
+ for (const t of rxTops) {
+ // `x$truth` declares the source; it is exported when its optimistic layer, `x`, is
+ const truth = t.d.type === "VariableDeclaration" ? (/^(.+)\$truth$/.exec(t.d.declarations[0]?.id?.elements?.[0]?.name ?? "")?.[1] ?? "") : "";
+ const layer = truth && tops.some((o) => o.s.type === "ExportNamedDeclaration" && o.d.type === "VariableDeclaration" && o.d.declarations.some((v: Node) => v.id.elements?.[0]?.name === truth));
+ const exported = t.s.type === "ExportNamedDeclaration" || layer ? "export " : "";
+ const notes = leading(t.s, t.from);
+ if (t.hook) {
+ fail(t.s, `${declared(t.d).join(", ")}: Solid primitives outside a component (a custom hook) have no .rx form in this prototype`);
+ for (const n of declared(t.d)) bind(n, { kind: "plain" });
+ } else if (t.comps.length) {
+ t.comps.forEach(([name, f], i) => out.push([...(i ? [] : notes), ...(f === rootOf ? provided : component(name, f, name === defaultName ? "export default " : exported))]));
+ } else {
+ const lines = decl(t.d, decls);
+ if (lines.length) out.push([...notes, exported + lines[0], ...lines.slice(1)]);
+ }
+ }
+ // one-line declarations sit together; a component stands apart
+ const chunks: { text: string; single: boolean }[] = [];
+ for (const lines of out) {
+ const single = lines.length === 1 && !/component /.test(lines[0]);
+ const prev = chunks[chunks.length - 1];
+ if (single && prev?.single) prev.text += "\n" + lines[0];
+ else chunks.push({ text: lines.join("\n"), single });
+ }
+
+ for (const name of askedServers) for (const local of serverCalls.get(name) ?? []) pureImports.add(local);
+ const usedBy = (nodes: Node[], s: Node) => s.specifiers.some((sp: Node) => uses(nodes, sp.local.name));
+ const imports: string[] = [];
+ const kept: string[] = [];
+ for (const s of program) {
+ if (s.type !== "ImportDeclaration" || SOLID.has(s.source.value)) continue;
+ const from = s.source.value as string;
+ if (usedBy(tops.filter((t) => t.js).map((t) => t.d), s)) kept.push(text(s));
+ if (s.importKind === "type" || !usedBy(rxTops.map((t) => t.d), s)) continue;
+ if (s.specifiers.some((sp: Node) => sp.type === "ImportNamespaceSpecifier")) fail(s, "import * as: .rx imports names");
+ const said = (sp: Node) => opts.declared?.(from, sp.type === "ImportSpecifier" ? sp.imported.name : "default");
+ // a TypeScript type the module's .d.rx does not declare has no .rx name
+ const used: Node[] = s.specifiers.filter((sp: Node) => !(sp.importKind === "type" && opts.declared && said(sp) !== "type"));
+ const spec = (sp: Node) => {
+ const r = (n: string) => renamed.get(sp.local.name) && n === sp.local.name ? renamed.get(n)! : renamed.has(sp.local.name) ? contextName(n) : n;
+ return sp.type === "ImportSpecifier" && sp.imported.name !== sp.local.name ? `${r(sp.imported.name)} as ${r(sp.local.name)}` : r(sp.local.name);
+ };
+ // another .rx module is named with its extension, or the compiler looks for a JavaScript one
+ const at = JSON.stringify(from.replace(/\.(tsx?|jsx?)$/, ""));
+ if (opts.declared && !/\.rx$/.test(from)) {
+ // the .d.rx decides: a pure fn imports pure, an io fn and a type do not
+ for (const pure of [true, false]) {
+ const group = used.filter((sp: Node) => (said(sp) === "pure" || (said(sp) === undefined && pureImports.has(sp.local.name))) === pure);
+ const def = group.find((sp: Node) => sp.type === "ImportDefaultSpecifier");
+ const named = group.filter((sp: Node) => sp.type === "ImportSpecifier").map(spec);
+ if (def) imports.push(`import ${pure ? "pure " : ""}${def.local.name} from ${at}`);
+ if (named.length) imports.push(`import ${pure ? "pure " : ""}{ ${named.join(", ")} } from ${at}`);
+ }
+ continue;
+ }
+ // one import statement is one purity, as it was written: pure when reactive scope reads any of its names
+ const pure = !/\.rx$/.test(from) && used.some((sp: Node) => pureImports.has(sp.local.name)) ? "pure " : "";
+ const def = used.find((sp: Node) => sp.type === "ImportDefaultSpecifier");
+ const named = used.filter((sp: Node) => sp.type === "ImportSpecifier").map(spec);
+ imports.push(`import ${pure}${def ? def.local.name : `{ ${named.join(", ")} }`} from ${at}`);
+ }
+ // what reactive scope reads is imported pure; the rest is io
+ const helpersPure = helperNames.some((n) => pureImports.has(n));
+ const pure = [...(helpersPure ? helperNames : []), ...[...globals].filter(([, p]) => p).map(([n]) => n)];
+ const io = [...(helpersPure ? [] : helperNames), ...[...globals].filter(([, p]) => !p).map(([n]) => n), ...(assigns ? ["assign"] : [])];
+ if (preludeAliases.size) imports.push(`import pure { ${[...preludeAliases].join(", ")} } from "./prelude"`);
+ if (pure.length) imports.push(`import pure { ${pure.join(", ")} } from ${JSON.stringify(helperFrom)}`);
+ if (io.length) imports.push(`import { ${io.join(", ")} } from ${JSON.stringify(helperFrom)}`);
+
+ const files: Record = {};
+ const helpers = tops
+ .filter((t) => t.js)
+ .map((t) => {
+ const first = comments.find((c) => c.start >= t.from && c.end <= t.s.start);
+ const exported = t.s.type !== "ExportNamedDeclaration" && declared(t.d).some((n) => helperNames.includes(n));
+ return src.slice(first ? first.start : t.s.start, t.s.start) + (exported ? "export " : "") + text(t.s);
+ });
+ if (assigns) helpers.push(`// plain JavaScript's assignment, for the .rx to call: only a source is written with :=\nexport const assign = (target: any, key: PropertyKey, value: unknown) => {\n target[key] = value;\n};`);
+ if (globals.size) helpers.push(`// what JavaScript gives every module, for the .rx to import\nexport const { ${[...globals.keys()].join(", ")} } = globalThis;`);
+ if (helpers.length) files[HELPERS] = [...kept, ...(kept.length ? [""] : []), helpers.join("\n")].join("\n") + "\n";
+
+ const head = imports.join("\n");
+ return { code: [head, ...chunks.map((c) => c.text.split("\n").map((l) => l.replace(/\s+$/, "")).join("\n"))].filter(Boolean).join("\n\n") + "\n", problems, files };
+}
diff --git a/site/playground/src/types.worker.ts b/site/playground/src/types.worker.ts
new file mode 100644
index 00000000..7e22dd0e
--- /dev/null
+++ b/site/playground/src/types.worker.ts
@@ -0,0 +1,111 @@
+// TypeScript's language service over the crate's TSX projection of each .rx (spec/13 TY-1c): what the editor
+// extension asks through Volar, here for two questions: the type under the pointer, and what can be written at the
+// caret. Loaded on the first of either.
+import ts from "typescript";
+
+const libs = import.meta.glob(
+ ["/node_modules/typescript/lib/lib.es5.d.ts", "/node_modules/typescript/lib/lib.es20{15,16,17,18,19,20,21,22}*.d.ts", "/node_modules/typescript/lib/lib.dom*.d.ts", "/node_modules/typescript/lib/lib.decorators*.d.ts"],
+ { query: "?raw", import: "default", eager: true },
+);
+// the types a projection reaches: Solid's JSX, and what that imports
+const packages = import.meta.glob(
+ [
+ "/node_modules/@solidjs/web/package.json",
+ "/node_modules/@solidjs/web/types/**/*.d.ts",
+ "/node_modules/solid-js/package.json",
+ "/node_modules/solid-js/types/**/*.d.ts",
+ "/node_modules/@solidjs/signals/package.json",
+ "/node_modules/@solidjs/signals/dist/types/**/*.d.ts",
+ "/node_modules/csstype/package.json",
+ "/node_modules/csstype/index.d.ts",
+ ],
+ { query: "?raw", import: "default", eager: true },
+);
+
+const fixed = new Map();
+for (const [path, text] of Object.entries(libs)) fixed.set("/lib/" + path.slice(path.lastIndexOf("/") + 1), text);
+for (const [path, text] of Object.entries(packages)) fixed.set(path, text);
+const dirs = new Set(["/"]);
+for (const f of fixed.keys()) for (let d = f.slice(0, f.lastIndexOf("/")); d; d = d.slice(0, d.lastIndexOf("/"))) dirs.add(d);
+
+let files: Record = {};
+const versions = new Map();
+const read = (f: string) => files[f] ?? fixed.get(f);
+
+const options: ts.CompilerOptions = {
+ jsx: ts.JsxEmit.Preserve,
+ jsxImportSource: "@solidjs/web",
+ strict: true,
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ lib: ["lib.es2022.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"],
+ allowJs: true,
+ skipLibCheck: true,
+ noEmit: true,
+ types: [],
+};
+
+const SOLID = "/node_modules/solid-js/types/index.d.ts";
+let exported: string[] | undefined;
+/** Every value solid-js exports: what a Solid file can be offered before it has imported it. */
+function solidExports(): string[] {
+ if (exported) return exported;
+ const program = service.getProgram();
+ const file = program?.getSourceFile(SOLID);
+ const checker = program?.getTypeChecker();
+ const module = file && checker?.getSymbolAtLocation(file);
+ if (!module || !checker) return [];
+ const value = (s: ts.Symbol) => ((s.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s) : s).flags & ts.SymbolFlags.Value) !== 0;
+ return (exported = checker.getExportsOfModule(module).filter(value).map((s) => s.name).filter((n) => /^[A-Za-z]/.test(n)));
+}
+
+const service = ts.createLanguageService({
+ getScriptFileNames: () => [...Object.keys(files).filter((f) => /\.(tsx?|m?js)$/.test(f)), SOLID],
+ getScriptVersion: (f) => String(versions.get(f) ?? 0),
+ getScriptSnapshot: (f) => {
+ const text = read(f);
+ return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text);
+ },
+ getCurrentDirectory: () => "/",
+ getCompilationSettings: () => options,
+ getDefaultLibFileName: () => "/lib/lib.d.ts",
+ fileExists: (f) => read(f) !== undefined,
+ readFile: read,
+ directoryExists: (d) => dirs.has(d.replace(/\/$/, "") || "/"),
+ getDirectories: (d) => [...dirs].filter((x) => x !== d && x.slice(0, x.lastIndexOf("/")) === d.replace(/\/$/, "")).map((x) => x.slice(x.lastIndexOf("/") + 1)),
+ useCaseSensitiveFileNames: () => true,
+});
+
+export type TypeRequest = { id: number; files: Record; file: string; offset: number; complete?: boolean; ambient?: boolean };
+/** `rank`: 0 what the module declares or imports, 1 what Solid exports and the pick would import, 2 what every module has. */
+export type Entry = { name: string; kind: string; rank?: number; importFrom?: string };
+export type TypeAnswer = { id: number; text?: string; doc?: string; entries?: Entry[]; member?: boolean; solid?: string[]; error?: string };
+
+const post = (a: TypeAnswer) => (self as unknown as Worker).postMessage(a);
+
+self.onmessage = (e: MessageEvent) => {
+ const { id, file, offset } = e.data;
+ for (const [f, text] of Object.entries(e.data.files)) if (files[f] !== text) versions.set(f, (versions.get(f) ?? 0) + 1);
+ files = e.data.files;
+ try {
+ if (e.data.complete) {
+ const c = service.getCompletionsAtPosition(file, offset, {});
+ // .rx has no ambient names: of what is in scope, only what the module declares or imports ("15" up is globals).
+ // TypeScript itself (`ambient`) has them all
+ const entries = (c?.entries ?? []).filter((x) => !x.name.startsWith("__") && (e.data.ambient || (x.kind !== "keyword" && (c!.isMemberCompletion || x.sortText < "15"))));
+ return post({
+ id,
+ entries: entries.sort((a, b) => a.sortText.localeCompare(b.sortText) || a.name.localeCompare(b.name)).map((x) => ({ name: x.name, kind: x.kind, rank: x.sortText < "15" ? 0 : 2 })),
+ member: !!c?.isMemberCompletion,
+ solid: e.data.ambient ? solidExports() : undefined,
+ });
+ }
+ const info = service.getQuickInfoAtPosition(file, offset);
+ const tags = (info?.tags ?? []).map((t) => `@${t.name} ${ts.displayPartsToString(t.text)}`.trim());
+ const answer: TypeAnswer = info ? { id, text: ts.displayPartsToString(info.displayParts), doc: [ts.displayPartsToString(info.documentation), ...tags].filter(Boolean).join("\n") } : { id };
+ post(answer);
+ } catch (err) {
+ post({ id, error: String((err as Error)?.message ?? err) });
+ }
+};
diff --git a/site/playground/tests/playground.check.mjs b/site/playground/tests/playground.check.mjs
new file mode 100644
index 00000000..f0f68171
--- /dev/null
+++ b/site/playground/tests/playground.check.mjs
@@ -0,0 +1,435 @@
+// Drives the running playground (`pnpm dev`) in headless Chromium. PLAYGROUND_URL overrides the address and
+// CHROMIUM the browser binary.
+import { chromium } from "playwright-core";
+import { existsSync } from "node:fs";
+import { homedir } from "node:os";
+
+const URL = process.env.PLAYGROUND_URL ?? "http://localhost:3020/";
+const exe =
+ process.env.CHROMIUM ??
+ [`${homedir()}/Library/Caches/ms-playwright/chromium_headless_shell-1243/chrome-headless-shell-mac-arm64/chrome-headless-shell`].find(existsSync);
+
+let failed = 0;
+const check = async (name, fn) => {
+ try {
+ await fn();
+ console.log(`ok ${name}`);
+ } catch (e) {
+ failed++;
+ console.log(`FAIL ${name}\n ${String(e.message).split("\n").join("\n ")}`);
+ }
+};
+const assert = (cond, msg) => {
+ if (!cond) throw new Error(msg);
+};
+
+const browser = await chromium.launch({ executablePath: exe });
+const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
+const pageErrors = [];
+page.on("pageerror", (e) => pageErrors.push(e.message));
+
+const editor = page.getByTestId("editor");
+const js = page.getByTestId("solid");
+const settle = () => page.waitForTimeout(300);
+const codes = () => page.getByTestId("diag-code").allInnerTexts();
+const type = async (text) => {
+ await editor.fill(text);
+ await page.waitForTimeout(400);
+};
+
+await page.goto(URL);
+await editor.waitFor();
+
+await check("the featured example reads as Solid primitives: two memos for label", async () => {
+ await js.getByText("createMemo", { exact: false }).first().waitFor({ timeout: 5000 });
+ const text = await js.innerText();
+ assert(text.includes("const [id, setId] = createSignal(1);"), "no createSignal for id");
+ assert(text.includes("const label$await = createMemo(() => fetchUser(id()));"), "no memo for the hoisted await");
+ assert(text.includes("const label = createMemo(() => label$await()?.name + suffix());"), "no memo for the rest of label");
+ assert(text.includes(" {
+ assert((await js.locator(".note").count()) === 0, "a note is shown in the view");
+ const table = await page.getByTestId("explain").innerText();
+ assert(table.includes("createMemo") && table.includes("an equation x = e"), `table: ${table}`);
+});
+
+await check("an object source reads as createStore", async () => {
+ await type(`export default component App() {\n source person := { first: "Ada", last: "Lovelace" }\n {person.first}
\n}\n`);
+ const text = await js.innerText();
+ assert(text.includes("const [person, setPerson] = createStore({"), `no createStore:\n${text}`);
+ assert(text.includes("person?.first") && !text.includes("person()"), "the store is called like a signal");
+});
+
+await check("a rest prop reads as omit, spread without a call", async () => {
+ await type(`component Badge({ label, tone = "info", ...rest }) {\n {label} \n}\nexport default component App() {\n \n}\n`);
+ const text = await js.innerText();
+ assert(text.includes('const rest = omit(props, "label", "tone");') && text.includes("{...rest}"), `no omit:\n${text}`);
+ assert(!text.includes("__rt") && !text.includes("rest()"), "omit is wrapped or called");
+ assert((await page.getByTestId("explain").innerText()).includes("omit"), "the table does not list omit");
+});
+
+await check("an effect reads as createEffect, its inputs named $0 and $1", async () => {
+ await type(`import { report } from "./io"\nexport default component App() {\n source count := 0\n double = count * 2\n effect (count, double) {\n report($0, $1)\n return () => { report("cleanup") }\n }\n effect () {\n report("mounted")\n }\n {count}
\n}\n`);
+ const text = (await js.innerText()).replace(/\s+/g, " ");
+ assert(text.includes("() => [count(), double()], ([$0, $1]) => { report($0, $1); return () => { report(\"cleanup\"); }; }"), `no createEffect over two inputs:\n${text}`);
+ assert(text.includes("createEffect(() => {}, () => report(\"mounted\"))"), `no createEffect without inputs:\n${text}`);
+ assert(!text.includes("__rt") && !text.includes("$p"), `the runtime's effect is still there:\n${text}`);
+});
+
+await check("the projection example reads as createProjection, keyed and draft", async () => {
+ await page.getByTestId("example").selectOption("projection");
+ await js.getByText("createProjection", { exact: false }).first().waitFor({ timeout: 5000 });
+ const text = await js.innerText();
+ assert(text.includes('const open = createProjection(() => open$answer(), [], { key: "id" });'), `no keyed projection:\n${text}`);
+ assert(text.includes("const marks = createProjection((d) => {") && text.includes("d[String(picked())] = true;"), `no draft projection:\n${text}`);
+ assert(text.includes(""), "the projection is called like a signal");
+});
+
+await check("typing updates the compiled output live", async () => {
+ await type(`export default component App() {
+ source count := 0
+ tripled = count * 3
+ { count := count + 1 }}>{tripled}
+}
+`);
+ const text = await js.innerText();
+ assert(text.includes("const tripled = createMemo(() => count() * 3);"), `the new equation is not in the output:\n${text}`);
+ assert((await codes()).length === 0, `unexpected diagnostics: ${await codes()}`);
+ await type((await editor.inputValue()).replace("count * 3", "count * 4"));
+ assert((await js.innerText()).includes("count() * 4"), "the edit did not reach the output");
+});
+
+await check("`double := 4` shows WRITE_TO_NON_SOURCE, with its rule and a guide link", async () => {
+ await type(`export default component App() {
+ source count := 0
+ double = count * 2
+ { double := 4 }}>{double}
+}
+`);
+ const link = page.getByTestId("diag-code").first();
+ await link.waitFor();
+ assert((await codes()).includes("WRITE_TO_NON_SOURCE"), `codes: ${await codes()}`);
+ const href = await link.getAttribute("href");
+ assert(href.endsWith("guide/diagnostics.md#write_to_non_source"), `href: ${href}`);
+ const row = await page.getByTestId("diagnostics").innerText();
+ assert(row.includes("[W-1]") && row.includes("double is an equation"), `row: ${row}`);
+ assert(await page.locator(".output.stale").count(), "the output is not marked stale");
+ const under = await page.locator(".editor .sq").allInnerTexts();
+ assert(under.join("").includes("double"), `the problem's span is not underlined: ${JSON.stringify(under)}`);
+});
+
+await check("clicking a line of the Solid view selects the .rx line it came from", async () => {
+ await page.getByTestId("example").selectOption("source");
+ await settle();
+ const picks = [
+ ["const double = createMemo(", "double = count * 2"],
+ ["const [count, setCount] = createSignal(", "source count := 0"],
+ ];
+ for (const [view, rx] of picks) {
+ await js.locator(".cl.link", { hasText: view }).first().click();
+ await page.waitForTimeout(100);
+ const picked = await editor.evaluate((el) => el.value.slice(el.selectionStart, el.selectionEnd));
+ assert(picked.trim().startsWith(rx), `clicking ${view} selected: ${JSON.stringify(picked)}`);
+ }
+ assert((await js.locator(".cl.on").count()) === 1, "the clicked line is not marked");
+});
+
+await check("every example compiles and reads as Solid primitives", async () => {
+ const ids = await page.getByTestId("example").locator("option:not([disabled])").evaluateAll((os) => os.map((o) => o.value));
+ assert(ids.length >= 5, `only ${ids.length} examples`);
+ for (const id of ids) {
+ await page.getByTestId("example").selectOption(id);
+ await settle();
+ assert((await codes()).length === 0, `${id}: ${await codes()}`);
+ assert(!(await page.locator(".output.stale").count()), `${id}: output stale`);
+ const text = await js.innerText();
+ assert(/create(Signal|Store)\(/.test(text) && !text.includes("__rt"), `${id}: not shown as Solid primitives:\n${text}`);
+ }
+});
+
+await check("an edited program survives a reload through the URL hash", async () => {
+ await type(`export default component App() {\n source shared := 41\n {shared + 1}
\n}\n`);
+ await page.waitForTimeout(500);
+ assert(page.url().includes("#code="), `url: ${page.url()}`);
+ await page.reload();
+ await editor.waitFor();
+ assert((await editor.inputValue()).includes("source shared := 41"), "the program did not come back");
+ await js.getByText("createSignal(41)", { exact: false }).waitFor({ timeout: 5000 });
+});
+
+await check("a program of two .rx modules shows both, and adding a file is kept in the URL", async () => {
+ await page.getByTestId("example").selectOption("source");
+ page.once("dialog", (d) => d.accept("util.rx"));
+ await page.getByTitle("Add a file").click();
+ await type("export bump = 10\n");
+ await page.getByRole("button", { name: "main.rx", exact: true }).click();
+ await type(`import { bump } from "./util.rx"\n\nexport default component App() {\n source n := 0\n total = n + bump\n {total}
\n}\n`);
+ await js.getByText("// /util.rx", { exact: false }).waitFor({ timeout: 5000 });
+ const text = await js.innerText();
+ assert(text.includes("const total = createMemo("), `entry not shown as primitives:\n${text}`);
+ assert(!(await page.getByTestId("solid-error").count()), await page.getByTestId("solid-error").innerText().catch(() => ""));
+ await page.waitForTimeout(500);
+ assert(page.url().includes("#code="), `the added file is not in the URL: ${page.url()}`);
+});
+
+await check("turning a two-module program around and back reads a source from the other module as itself", async () => {
+ await page.getByTestId("example").selectOption("source");
+ page.once("dialog", (d) => d.accept("store.rx"));
+ await page.getByTitle("Add a file").click();
+ await type(`export source count := 1\n\nexport action more() {\n count := count + 1\n}\n`);
+ await page.getByRole("button", { name: "main.rx", exact: true }).click();
+ const program = `import { count, more } from "./store.rx"\n\nexport default component App() {\n doubled = count * 2\n { more() }}>{count} {doubled}
\n}\n`;
+ await type(program);
+ await js.getByText("// /store.rx", { exact: false }).waitFor({ timeout: 5000 });
+ await page.getByTestId("mode").click();
+ await page.getByTestId("rx-out").getByText("doubled = count * 2", { exact: false }).first().waitFor({ timeout: 5000 });
+ await page.waitForTimeout(300);
+ await page.getByTestId("mode").click();
+ await editor.waitFor({ timeout: 5000 });
+ const rx = await editor.inputValue();
+ assert(rx.includes("doubled = count * 2") && rx.includes("{count} {doubled}") && !rx.includes("count()"), `the import is read as a call:\n${rx}`);
+ assert(!(await codes()).length, `codes: ${await codes()}`);
+});
+
+await check("Solid → .rx reads the Solid view back as .rx, lists what it cannot read", async () => {
+ await page.getByTestId("example").selectOption("await");
+ await js.getByText("label$await", { exact: false }).first().waitFor({ timeout: 5000 });
+ await page.getByTestId("mode").click();
+ const out = page.getByTestId("rx-out");
+ await out.getByText("fetchUser", { exact: false }).first().waitFor({ timeout: 5000 });
+ let rx = await out.innerText();
+ assert(rx.includes("label = (await fetchUser(id)).name + suffix") && rx.includes("{errored fallback(e) {"), `not the await example:\n${rx}`);
+ assert((await page.getByTestId("rx-check").innerText()).includes("The checker accepts it."), "the checker does not accept the .rx");
+ const solidEditor = page.getByTestId("solid-editor");
+ await solidEditor.fill(`import { createSignal, createRenderEffect } from "solid-js";\nexport default function App() {\n const [n, setN] = createSignal(0);\n createRenderEffect(() => n(), (v) => console.log(v));\n return setN(n() + 1)}>{n()}
;\n}\n`);
+ await page.getByTestId("rx-problems").getByText("render effect", { exact: false }).first().waitFor({ timeout: 5000 });
+ await solidEditor.fill(`import { createSignal, createMemo } from "solid-js";\nexport default function Counter() {\n const [count, setCount] = createSignal(0);\n const doubled = createMemo(() => count() * 2);\n return setCount(count() + 1)}>{doubled()} ;\n}\n`);
+ await out.getByText("doubled = count * 2", { exact: false }).first().waitFor({ timeout: 5000 });
+ // plain TypeScript beside the component moves to helpers.ts, and comes along into the editor
+ await solidEditor.fill(`import { createMemo } from "solid-js";\nconst wait = (ms) => new Promise((r) => setTimeout(r, ms));\nconst load = async () => (await wait(10), ["a"]);\nfunction App() {\n const items = createMemo(load);\n return {items().length}
;\n}\n`);
+ await out.getByText("items = await load()", { exact: false }).first().waitFor({ timeout: 5000 });
+ assert((await page.getByTestId("rx-helpers").innerText()).includes("export const load = async"), "no helpers.ts");
+ assert((await page.getByTestId("rx-check").innerText()).includes("UNHANDLED_FAILURE"), "the checker does not ask for a boundary");
+ await solidEditor.fill(`import { createSignal, createMemo } from "solid-js";\nexport default function Counter() {\n const [count, setCount] = createSignal(0);\n const doubled = createMemo(() => count() * 2);\n return setCount(count() + 1)}>{doubled()} ;\n}\n`);
+ await out.getByText("doubled = count * 2", { exact: false }).first().waitFor({ timeout: 5000 });
+ // turning the page back puts the .rx it read in the editor, and the Solid view of it on the right
+ await page.getByTestId("mode").click();
+ await editor.waitFor({ timeout: 5000 });
+ rx = await editor.inputValue();
+ assert(rx.includes("source count := 0") && rx.includes("onClick={() => { count := count + 1 }}"), `the editor did not get the .rx:\n${rx}`);
+ await js.getByText("const doubled = createMemo", { exact: false }).first().waitFor({ timeout: 5000 });
+});
+
+await check("the Solid → .rx side is kept in the URL, so a reload opens the page the same way round", async () => {
+ await page.getByTestId("example").selectOption("source");
+ await settle();
+ await page.getByTestId("mode").click();
+ const src = `import { createSignal } from "solid-js";\nexport default function Kept() {\n const [kept, setKept] = createSignal(7);\n return setKept(kept() + 1)}>{kept()}
;\n}\n`;
+ await page.getByTestId("solid-editor").fill(src);
+ await page.waitForTimeout(600);
+ await page.reload();
+ await page.getByTestId("solid-editor").waitFor({ timeout: 10000 });
+ assert((await page.getByTestId("solid-editor").inputValue()) === src, "the Solid source did not come back");
+ await page.getByTestId("rx-out").getByText("source kept := 7", { exact: false }).first().waitFor({ timeout: 5000 });
+ await page.getByTestId("mode").click();
+ await page.waitForTimeout(600);
+ await page.reload();
+ await editor.waitFor({ timeout: 10000 });
+ assert(!(await page.getByTestId("solid-editor").isVisible()), "the page did not stay turned back after a reload");
+});
+
+await check("hovering a name shows its type, and an attribute its documentation", async () => {
+ await page.getByTestId("example").selectOption("await");
+ await js.getByText("label$await", { exact: false }).first().waitFor({ timeout: 5000 });
+ // where a name is on screen: the editor's padding and character size, as the page lays them out
+ const point = (needle, nth = 0) =>
+ page.evaluate(
+ ([needle, nth]) => {
+ const ta = document.querySelector("[data-testid=editor]");
+ const bd = ta.previousElementSibling;
+ const cs = getComputedStyle(bd);
+ const probe = document.createElement("span");
+ probe.textContent = "0".repeat(100);
+ probe.style.cssText = "position:absolute;visibility:hidden";
+ bd.append(probe);
+ const b = probe.getBoundingClientRect();
+ probe.remove();
+ let i = -1;
+ for (let k = 0; k <= nth; k++) i = ta.value.indexOf(needle, i + 1);
+ const before = ta.value.slice(0, i);
+ const box = ta.getBoundingClientRect();
+ return { x: box.left + parseFloat(cs.paddingLeft) + (before.length - before.lastIndexOf("\n") - 1 + 1.5) * (b.width / 100) - ta.scrollLeft, y: box.top + parseFloat(cs.paddingTop) + (before.split("\n").length - 0.5) * b.height - ta.scrollTop };
+ },
+ [needle, nth],
+ );
+ // the tooltip for a name, once it says what is expected (the last one stays up until the next arrives)
+ const hover = async (needle, nth, ...expected) => {
+ const p = await point(needle, nth);
+ await page.mouse.move(p.x - 200, p.y + 150);
+ await page.mouse.move(p.x, p.y);
+ const tip = page.getByTestId("hover");
+ await tip.waitFor({ timeout: 30000 });
+ const said = () => tip.innerText().then((t) => t.replace(/\s+/g, " "));
+ for (let i = 0; i < 40; i++) {
+ const t = await said().catch(() => "");
+ if (expected.every((e) => t.includes(e))) return t;
+ await page.waitForTimeout(150);
+ }
+ throw new Error(`hovering ${needle}: expected ${expected.join(" and ")}, the tooltip says:\n${await said().catch(() => "(nothing)")}`);
+ };
+ await hover("label", 0, "label: string");
+ await hover("id", 0, "source id: number");
+ const fn = await hover("fetchUser", 1, "fetchUser(id: number): any");
+ assert(!fn.includes("import"), `a .d.rx function reads as an import:\n${fn}`);
+ await hover("class", 0, "class?:", "Class names to apply");
+ await page.mouse.move(5, 5);
+ await page.getByTestId("hover").waitFor({ state: "detached", timeout: 5000 });
+});
+
+await check("typing offers what fits: a store's fields after a dot, names in scope, and a keyword", async () => {
+ const program = `export default component App() {\n source user := { name: "Ada", age: 36 }\n source count := 0\n shown = \n {shown}
\n}\n`;
+ await type(program);
+ await editor.evaluate((el, at) => (el.focus(), el.setSelectionRange(at, at)), program.indexOf("shown = ") + 8);
+ const menu = page.getByTestId("complete");
+ // the list, once it holds exactly these names (it follows the typing)
+ const offers = async (...names) => {
+ let seen = [];
+ for (let i = 0; i < 100; i++) {
+ seen = (await menu.locator("li span").allInnerTexts().catch(() => [])).map((t) => t.trim());
+ if (seen.join() === names.join()) return;
+ await page.waitForTimeout(150);
+ }
+ throw new Error(`expected ${names.join(", ")}; the list holds ${seen.join(", ") || "nothing"}`);
+ };
+ await page.keyboard.type("user.");
+ await offers("age", "name");
+ await page.keyboard.type("na");
+ await offers("name");
+ await page.keyboard.press("Enter");
+ await page.keyboard.type(" + cou");
+ await offers("count");
+ await page.keyboard.press("Tab");
+ assert((await editor.inputValue()).includes(" shown = user.name + count\n"), `the names were not written:\n${await editor.inputValue()}`);
+ await page.keyboard.type(" + so");
+ await offers("source");
+ await page.keyboard.press("Escape");
+ await menu.waitFor({ state: "detached", timeout: 5000 });
+});
+
+await check("the Solid pane has TypeScript too: an accessor's type on hover, and a store's fields after a dot", async () => {
+ await page.getByTestId("mode").click();
+ const solidEditor = page.getByTestId("solid-editor");
+ const program = `import { createSignal, createStore } from "solid-js";\nexport default function App() {\n const [count, setCount] = createSignal(0);\n const [user] = createStore({ name: "Ada", age: 36 });\n return {count()}
;\n}\n`;
+ await solidEditor.fill(program);
+ const tips = page.getByTestId("hover");
+ const menus = page.getByTestId("complete");
+ // the pointer over `count` in `{count()}`: the pane's own editor, its own padding
+ const p = await solidEditor.evaluate((ta, at) => {
+ const bd = ta.previousElementSibling;
+ const cs = getComputedStyle(bd);
+ const probe = document.createElement("span");
+ probe.textContent = "0".repeat(100);
+ probe.style.cssText = "position:absolute;visibility:hidden";
+ bd.append(probe);
+ const b = probe.getBoundingClientRect();
+ probe.remove();
+ const before = ta.value.slice(0, at);
+ const box = ta.getBoundingClientRect();
+ return { x: box.left + parseFloat(cs.paddingLeft) + (before.length - before.lastIndexOf("\n") - 1 + 1.5) * (b.width / 100), y: box.top + parseFloat(cs.paddingTop) + (before.split("\n").length - 0.5) * b.height };
+ }, program.indexOf("{count()}") + 1);
+ await page.mouse.move(p.x - 200, p.y + 150);
+ await page.mouse.move(p.x, p.y);
+ let said = "";
+ for (let i = 0; i < 100 && !said.includes("const count: () => number"); i++) {
+ said = (await tips.innerText().catch(() => "")).replace(/\s+/g, " ");
+ await page.waitForTimeout(150);
+ }
+ assert(said.includes("const count: () => number"), `an accessor's type:\n${said || "(no tooltip)"}`);
+ await solidEditor.evaluate((el, at) => (el.focus(), el.setSelectionRange(at, at)), program.indexOf("{count()} ") + 10);
+ await page.keyboard.type("{user.");
+ let seen = [];
+ for (let i = 0; i < 100 && seen.join() !== "age,name"; i++) {
+ seen = (await menus.locator("li span").allInnerTexts().catch(() => [])).map((t) => t.trim());
+ await page.waitForTimeout(150);
+ }
+ assert(seen.join() === "age,name", `a store's fields: ${seen.join(", ") || "nothing"}`);
+ await page.keyboard.press("Enter");
+ assert((await solidEditor.inputValue()).includes("{count()} {user.age"), `the field was not written:\n${await solidEditor.inputValue()}`);
+ // a Solid primitive the file has not imported is offered, and picking it imports it
+ await solidEditor.evaluate((el, at) => (el.focus(), el.setSelectionRange(at, at)), (await solidEditor.inputValue()).indexOf(" return "));
+ await page.keyboard.type("const m = createMe");
+ seen = [];
+ for (let i = 0; i < 100 && !seen.includes("createMemo"); i++) {
+ seen = (await menus.locator("li span").allInnerTexts().catch(() => [])).map((t) => t.trim());
+ await page.waitForTimeout(150);
+ }
+ assert(seen[0] === "createMemo", `createMemo is not offered first: ${seen.join(", ") || "nothing"}`);
+ await page.keyboard.press("Enter");
+ const picked = await solidEditor.inputValue();
+ assert(picked.includes('import { createSignal, createStore, createMemo } from "solid-js";') && picked.includes("const m = createMemo return"), `the import was not added:\n${picked}`);
+ await page.getByTestId("mode").click();
+});
+
+await check("log is offered as a built-in, and reads as console.log in the Solid view", async () => {
+ const program = `export default component App() {\n source n := 0\n
{ }}>{n}
\n}\n`;
+ await type(program);
+ await editor.evaluate((el, at) => (el.focus(), el.setSelectionRange(at, at)), program.indexOf("{ }") + 2);
+ await page.keyboard.type("lo");
+ const menu = page.getByTestId("complete");
+ let seen = [];
+ for (let i = 0; i < 100 && seen[0] !== "log"; i++) {
+ seen = (await menu.locator("li span").allInnerTexts().catch(() => [])).map((t) => t.trim());
+ await page.waitForTimeout(150);
+ }
+ assert(seen[0] === "log", `log is not offered first: ${seen.join(", ") || "nothing"}`);
+ await page.keyboard.press("Enter");
+ await page.keyboard.type('("clicked", n)');
+ await js.getByText("console.log", { exact: false }).first().waitFor({ timeout: 5000 });
+ const text = (await js.innerText()).replace(/\s+/g, " ");
+ assert(text.includes('console.log("clicked", untrack(n));') && !text.includes("__"), `log in the view:\n${text}`);
+});
+
+await check("a server fn reads as a \"use server\" function, its awaits and imports as written", async () => {
+ await type(`import pure { findUser } from "./db"\n\nserver fn loadUser(id: number) {\n let row = await findUser(id)\n return { id, name: row.name }\n}\n\nexport default component App() {\n source id := 1\n user = await loadUser(id)\n {errored fallback(e) { {e.message}
} {\n {loading fallback { Loading
} {\n {user.name}
\n }}\n }}\n}\n`);
+ await js.getByText("use server", { exact: false }).first().waitFor({ timeout: 5000 });
+ const text = (await js.innerText()).replace(/\s+/g, " ");
+ assert(text.includes('async function loadUser(id) { "use server";') && text.includes("let row = await findUser(id);"), `the server fn:\n${text}`);
+ assert(text.includes("createMemo(() => loadUser(id()))") && !text.includes("__rt") && !text.includes("sf$") && !text.includes("setFindUser"), `what is left of the runtime:\n${text}`);
+});
+
+await check("a fallback with no error name and a branch with its own names show no placeholders", async () => {
+ await type(`import pure { fetchUser } from "./users"\n\nexport default component App() {\n source show := true\n source id := 1\n {errored fallback { Failed
} {\n {if show {\n user = await fetchUser(id)\n {loading fallback { Loading
} { {user.name}
}}\n }}\n }}\n}\n`);
+ await js.getByText("Failed", { exact: false }).first().waitFor({ timeout: 5000 });
+ const text = (await js.innerText()).replace(/\s+/g, " ");
+ assert(text.includes("Failed
}>") && text.includes("{() => {"), `the placeholders:\n${text}`);
+ assert(!text.includes("__err") && !text.includes("__item"), `a placeholder is left:\n${text}`);
+});
+
+await check("typed errors read as error classes and instanceof, and a context as createContext and its provider", async () => {
+ await type(`export error Big(n: number) => \`too big: \${n}\`\n\nexport context theme: string = "light"\n\nfn check(n: number) => n > 3 ? throw Big(n) : n\n\ncomponent Badge() {\n t = use theme\n {t} \n}\n\nexport default component App() {\n source n := 0\n checked = check(n)\n provide theme = n > 1 ? "dark" : "light"\n \n { n := n + 1 }}>+ \n {errored fallback(e) { {e.message}
} {\n {errored fallback(e: Big) { big {e.n}
} { {checked}
}}\n }}\n \n \n}\n`);
+ await js.getByText("createContext", { exact: false }).first().waitFor({ timeout: 5000 });
+ const text = (await js.innerText()).replace(/\s+/g, " ");
+ for (const want of ["class Big extends Error {", "if (n > 3) throw new Big(n);", "if (!(e() instanceof Big)) throw e();", 'createContext(() => "light")', "const t = useContext(ThemeContext);", " (n() > 1 ? \"dark\" : \"light\")}>"])
+ assert(text.includes(want), `missing ${want}:\n${text}`);
+ assert(!text.includes("__rt") && !text.includes("__B"), `the runtime is left:\n${text}`);
+});
+
+await check("a first paint reads as loadingValue, and a catch on an await as the promise's catch", async () => {
+ await type(`export default component App() {\n source id := 1\n name = await fetch("u:" + id) -> "nobody"\n size = await fetch("s:" + id) -> 10 catch (e) => 0\n {errored fallback(e) { {e.message}
} {\n { id := id + 1 }}>{name} {size}
\n }}\n}\n`);
+ assert((await codes()).length === 0, `codes: ${await codes()}`);
+ await js.getByText("loadingValue", { exact: false }).first().waitFor({ timeout: 5000 });
+ const text = (await js.innerText()).replace(/\s+/g, " ");
+ for (const want of ['{ loadingValue: "nobody" }', ".catch((e) => 0)", "if (e instanceof NotReadyError) throw e;"]) assert(text.includes(want), `missing ${want}:\n${text}`);
+ assert(!text.includes("__rt"), `the runtime is left:\n${text}`);
+});
+
+await check("no uncaught page errors", async () => {
+ assert(pageErrors.length === 0, pageErrors.join("\n"));
+});
+
+await browser.close();
+console.log(failed ? `\n${failed} failed` : "\nall passed");
+process.exit(failed ? 1 : 0);
diff --git a/site/playground/tests/roundtrip.check.mts b/site/playground/tests/roundtrip.check.mts
new file mode 100644
index 00000000..6cbe4dce
--- /dev/null
+++ b/site/playground/tests/roundtrip.check.mts
@@ -0,0 +1,161 @@
+// Both directions, checked for lost text as well as a matching view:
+// .rx first: rx → Solid → rx' rx' must keep rx's comments, strings and names
+// Solid first: tsx → rx → Solid → rx'' rx'' must equal rx (a fixed point), and rx must keep tsx's comments, strings and names
+// Run after `pnpm wasm`: node tests/roundtrip.check.mts [-v]
+import { readFileSync } from "node:fs";
+import { loadRxc } from "../src/rxc.ts";
+import { presets } from "../src/presets.ts";
+import { solidify } from "../src/solidify.ts";
+import { toRx } from "../src/torx.ts";
+import { extra, samples } from "./torx.samples.mts";
+import * as prettier from "prettier/standalone";
+import * as babel from "prettier/plugins/babel";
+import * as estree from "prettier/plugins/estree";
+
+const verbose = process.argv.includes("-v");
+const call = loadRxc(new WebAssembly.Module(readFileSync(new URL("../public/rxc.wasm", import.meta.url))));
+const fmt = (c: string) => prettier.format(c, { parser: "babel", plugins: [babel, estree as any], printWidth: 100, useTabs: true });
+const parse = (code: string) => (babel as any).parsers["babel-ts"].parse(code, {});
+
+async function view(files: Record) {
+ const out = call("app", { entry: "/main.rx", target: "dom", jsx: true }, files);
+ if (!out.modules) throw new Error(out.error ?? JSON.stringify(out.diagnostics));
+ return fmt(solidify(await fmt(out.modules["/main.rx"].jsx)));
+}
+const back = (solid: string) => toRx(parse(solid), solid);
+const squeeze = (s: string) => s.replace(/\s+/g, " ").trim();
+
+// What a reader would miss: comments, string and template text, and the names the author chose.
+type Facts = { comments: Set; strings: Set; names: Set; types: Set };
+// names .rx spells differently by design: Solid's API, its setters, and `props`
+const SOLID_API = /^(create[A-Z]\w*|on[A-Z]\w*|set[A-Z]\w*|props|render|action|refresh|isPending|untrack|batch|Show|For|Loading|Errored|Switch|Match|Index)$/;
+function solidFacts(code: string): Facts {
+ const ast = parse(code);
+ const f: Facts = { comments: new Set(), strings: new Set(), names: new Set(), types: new Set() };
+ for (const c of ast.comments ?? []) for (const l of String(c.value).split("\n")) if (l.replace(/^\s*\*?/, "").trim()) f.comments.add(squeeze(l.replace(/^\s*\*?/, "")));
+ const walk = (n: any, parent?: any) => {
+ if (!n || typeof n !== "object") return;
+ if (Array.isArray(n)) return n.forEach((x) => walk(x, parent));
+ if (typeof n.type !== "string") return;
+ if (n.type === "StringLiteral" && parent?.type !== "ImportDeclaration" && n.value.trim()) f.strings.add(n.value);
+ if (n.type === "TemplateElement" && n.value.cooked.trim()) f.strings.add(n.value.cooked);
+ if (n.type === "JSXText" && n.value.trim()) f.strings.add(squeeze(n.value));
+ const declared = (id: any) => {
+ if (!id) return;
+ if (id.type === "Identifier" && !SOLID_API.test(id.name)) f.names.add(id.name);
+ if (id.type === "ArrayPattern") id.elements.forEach(declared);
+ if (id.type === "ObjectPattern") id.properties.forEach((p: any) => declared(p.value ?? p.argument));
+ if (id.type === "AssignmentPattern") declared(id.left);
+ if (id.type === "RestElement") declared(id.argument);
+ };
+ if (n.type === "TSTypeAliasDeclaration") f.types.add(`type ${n.id.name}`);
+ if (n.type === "TSTypeAnnotation" || n.type === "TSTypeParameterInstantiation") f.types.add(squeeze(code.slice(n.start, n.end).replace(/^:|^<|>$/g, "")));
+ if (n.type === "VariableDeclarator") declared(n.id);
+ if (n.type === "FunctionDeclaration") declared(n.id);
+ if (/Function/.test(n.type)) n.params?.forEach(declared);
+ for (const k of Object.keys(n)) if (!["loc", "start", "end", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "range"].includes(k)) walk(n[k], n);
+ };
+ walk(ast.program);
+ return f;
+}
+// .rx has no JS parser here: comments, quoted strings, and declared names by pattern
+function rxFacts(code: string): Facts {
+ const f: Facts = { comments: new Set(), strings: new Set(), names: new Set(), types: new Set() };
+ for (const m of code.matchAll(/^\s*type (\w+)/gm)) f.types.add(`type ${m[1]}`);
+ for (const m of code.matchAll(/\bsource \w+: ([^=\n]+?) :?=/g)) f.types.add(squeeze(m[1]));
+ for (const m of code.matchAll(/(?:^|[^:])\/\/(.*)$/gm)) if (m[1].trim()) f.comments.add(squeeze(m[1]));
+ for (const m of code.matchAll(/"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'/g)) if ((m[1] ?? m[2]).trim()) f.strings.add(m[1] ?? m[2]);
+ for (const m of code.replace(/(^|[^:])\/\/.*$/gm, "$1").matchAll(/\b(?:source|const|let|component|action|fn|guess)\s+([A-Za-z_$][\w$]*)/g)) f.names.add(m[1]);
+ return f;
+}
+const missing = (want: Facts, haystack: string) => {
+ const h = squeeze(haystack);
+ const word = (n: string) => new RegExp(`(^|[^\\w$])${n.replace(/\$/g, "\\$")}([^\\w$]|$)`).test(haystack);
+ return {
+ comments: [...want.comments].filter((c) => !h.includes(c)),
+ strings: [...want.strings].filter((s) => !h.includes(squeeze(s)) && !haystack.includes(JSON.stringify(s).slice(1, -1))),
+ names: [...want.names].filter((n) => !word(n)),
+ types: [...want.types].filter((t) => !h.includes(t)),
+ };
+};
+// the compiled view is untyped JavaScript with no comments, so a trip through it drops both by design
+const BY_DESIGN = new Set(["comments", "types"]);
+const report = (m: ReturnType, only?: "real" | "design") =>
+ Object.entries(m)
+ .filter(([k, v]) => v.length && (only === undefined || BY_DESIGN.has(k) === (only === "design")))
+ .map(([k, v]) => ` lost ${k}: ${v.map((x) => JSON.stringify(x)).join(", ")}`)
+ .join("\n");
+
+let failed = 0;
+const line = (ok: boolean, label: string, detail = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label}`);
+ if (!ok) failed++;
+ if (detail) console.log(detail);
+};
+
+console.log("# .rx first: rx → Solid → rx'");
+const rxCases = [...presets.map((p) => [p.id, p.files] as const), ...Object.entries(extra).map(([k, v]) => [k, { "main.rx": v }] as const)];
+for (const [id, files] of rxCases) {
+ const fs = Object.fromEntries(Object.entries(files).map(([k, v]) => ["/" + k, v]));
+ const rx0 = fs["/main.rx"];
+ const solid = await view(fs);
+ const rx1 = back(solid);
+ const lost = missing(rxFacts(rx0), rx1.code + Object.values(rx1.files).join("\n"));
+ const textSame = squeeze(rx1.code) === squeeze(rx0);
+ const r = report(lost, "real");
+ const design = report(lost, "design");
+ line(!rx1.problems.length && !r, `${id}${textSame ? " (same text)" : ""}`, [
+ rx1.problems.map((p) => ` problem line ${p.line}: ${p.message}`).join("\n"),
+ r,
+ design && ` through the view, by design\n${design}`,
+ !textSame && verbose ? `--- rx\n${rx0}--- rx'\n${rx1.code}` : "",
+ ].filter(Boolean).join("\n"));
+}
+
+console.log("\n# Solid first: tsx → rx → Solid → rx'' → Solid'");
+const unscoped = async (code: string) =>
+ fmt(code.replace(/class=\{\[([^\n]*), "tsrx-[0-9a-f]+"\]\}/g, "class={$1}").replace(/ ?tsrx-[0-9a-f]+/g, "").replace(/\s+class=""/g, ""));
+const order = (code: string) => [...code.matchAll(/^\s*(?:export default )?(?:source|component|action|guess|type)?\s*([A-Za-z_$][\w$]*)\s*(?::[^=\n]*)?(?::=|=|\(|\{)/gm)].map((m) => m[1]);
+// a module named ./api lowers to __rt.api test flights, which the view cannot be read back from
+const unApi = (s: (typeof samples)[string]) => ({ ...s, solid: s.solid.replaceAll('"./api"', '"./server"'), files: s.files && Object.fromEntries(Object.entries(s.files).map(([k, v]) => [k.replace(/^\/api\./, "/server."), v])) });
+for (const [id, s0] of Object.entries(samples)) {
+ const s = unApi(s0);
+ if (s.problems) {
+ console.log(`skip ${id}: torx refuses it on purpose (${s.problems} problems)`);
+ continue;
+ }
+ if (s.diagnostics) {
+ console.log(`skip ${id}: the .rx is meant to fail the checker (${s.diagnostics.join(", ")}), so it has no view`);
+ continue;
+ }
+ const rx1 = back(s.solid);
+ const helpers = Object.fromEntries(Object.entries(rx1.files).map(([k, v]) => ["/" + k, v]));
+ const fs = { ...(s.files ?? {}), ...helpers, "/main.rx": rx1.code };
+ const all = (r: { code: string; files: Record }) => r.code + Object.values(r.files).join("\n");
+ const notes: string[] = [];
+ let ok = false;
+ try {
+ const solid1 = await view(fs);
+ const rx2 = back(solid1);
+ const solid2 = await view({ ...fs, ...Object.fromEntries(Object.entries(rx2.files).map(([k, v]) => ["/" + k, v])), "/main.rx": rx2.code });
+ ok = !rx2.problems.length && (await unscoped(solid1)) === (await unscoped(solid2));
+ if (!ok) notes.push(` views differ after a second trip` + rx2.problems.map((p) => `\n problem line ${p.line}: ${p.message}`).join(""));
+ // tsx → rx goes through no view, so it must keep comments, strings and types; a draft's or an effect's
+ // parameter names give way to store paths and $0 by design
+ const lostRx = missing(solidFacts(s.solid), all(rx1));
+ if (lostRx.comments.length || lostRx.strings.length || lostRx.types.length) ok = false;
+ const a = report(lostRx);
+ const b = report(missing(rxFacts(rx1.code), all(rx2)));
+ if (a) notes.push(" tsx → rx\n" + a);
+ if (b) notes.push(" rx → Solid → rx''\n" + b);
+ const o1 = order(rx1.code).join(" "), o2 = order(rx2.code).join(" ");
+ if (o1 !== o2) notes.push(` rx → Solid → rx'' reorders declarations\n ${o1}\n ${o2}`);
+ if (verbose) notes.push(`--- tsx\n${s.solid}--- rx\n${rx1.code}--- rx''\n${rx2.code}`);
+ } catch (e) {
+ notes.push(` the .rx does not compile: ${(e as Error).message.slice(0, 300)}`);
+ }
+ console.log(`${ok ? "ok " : "FAIL"} ${id}`);
+ if (!ok) failed++;
+ if (notes.length) console.log(notes.join("\n"));
+}
+process.exit(failed ? 1 : 0);
diff --git a/site/playground/tests/roundtrip.corpus.mts b/site/playground/tests/roundtrip.corpus.mts
new file mode 100644
index 00000000..4b0dd85c
--- /dev/null
+++ b/site/playground/tests/roundtrip.corpus.mts
@@ -0,0 +1,131 @@
+// Round trip over a corpus of .rx apps, to find bugs: each directory with a main.rx is an app.
+// rx → Solid view (per module) → rx' (torx) → Solid view' the two views must match
+// Every failure is put in the layer that broke, with its first lines, and written to OUT as JSON.
+// node tests/roundtrip.corpus.mts ... [LIMIT=n] [OUT=file] [SHOW=kind]
+import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { join, relative } from "node:path";
+import { loadRxc } from "../src/rxc.ts";
+import { solidify } from "../src/solidify.ts";
+import { declaredIn, toRx } from "../src/torx.ts";
+import * as prettier from "prettier/standalone";
+import * as babel from "prettier/plugins/babel";
+import * as estree from "prettier/plugins/estree";
+
+const call = loadRxc(new WebAssembly.Module(readFileSync(new URL("../public/rxc.wasm", import.meta.url))));
+const fmt = (c: string) => prettier.format(c, { parser: "babel", plugins: [babel, estree as any], printWidth: 100, useTabs: true });
+const parse = (code: string) => (babel as any).parsers["babel-ts"].parse(code, {});
+const LIMIT = Number(process.env.LIMIT ?? Infinity);
+const SHOW = process.env.SHOW;
+
+function apps(roots: string[]): string[] {
+ const found: string[] = [];
+ const walk = (d: string) => {
+ let names: string[];
+ try {
+ names = readdirSync(d);
+ } catch {
+ return;
+ }
+ if (names.includes("main.rx")) found.push(d);
+ for (const n of names) if (n !== "node_modules" && !n.startsWith(".git") && statSync(join(d, n)).isDirectory()) walk(join(d, n));
+ };
+ roots.forEach(walk);
+ return found;
+}
+const load = (d: string) =>
+ Object.fromEntries(readdirSync(d).filter((n) => /\.(rx|ts|js|mjs)$/.test(n) && statSync(join(d, n)).isFile()).map((n) => ["/" + n, readFileSync(join(d, n), "utf8")]));
+
+type Out = { modules?: Record; error?: string; diagnostics?: { code: string; message?: string; msg?: string; line?: number; file?: string }[] };
+const compile = (files: Record): Out => call("app", { entry: "/main.rx", target: "dom", jsx: true }, files);
+const unscoped = (code: string) =>
+ code.replace(/class=\{\[([^\n]*), "tsrx-[0-9a-f]+"\]\}/g, "class={$1}").replace(/ ?tsrx-[0-9a-f]+/g, "").replace(/\s+class=""/g, "");
+async function views(out: Out) {
+ const v: Record = {};
+ for (const [k, m] of Object.entries(out.modules ?? {})) if (m.jsx !== undefined && k.endsWith(".rx")) v[k] = await fmt(unscoped(await fmt(solidify(await fmt(m.jsx)))));
+ return v;
+}
+const diag = (out: Out) => (out.diagnostics ?? []).map((d) => `${d.file ?? ""}:${d.line ?? "?"} ${d.code} ${(d.message ?? d.msg ?? "").slice(0, 160)}`).join("\n") || (out.error ?? "");
+
+type Finding = { app: string; kind: string; module?: string; detail: string; rx?: string; view?: string; rx2?: string };
+const findings: Finding[] = [];
+const seen = new Set();
+let ran = 0, skipped = 0, dup = 0;
+const counts: Record = {};
+const note = (f: Finding) => {
+ findings.push(f);
+ counts[f.kind] = (counts[f.kind] ?? 0) + 1;
+ if (!SHOW || SHOW === f.kind) console.log(`${f.kind.padEnd(14)} ${f.app}${f.module ? " " + f.module : ""}\n ${f.detail.split("\n").slice(0, 4).join("\n ")}`);
+};
+
+for (const d of apps(process.argv.slice(2))) {
+ if (ran >= LIMIT) break;
+ const files = load(d);
+ const hash = createHash("sha1").update(JSON.stringify(files)).digest("hex");
+ if (seen.has(hash)) {
+ dup++;
+ continue;
+ }
+ seen.add(hash);
+ const app = relative(process.cwd(), d);
+ let out0: Out;
+ try {
+ out0 = compile(files);
+ } catch (e) {
+ note({ app, kind: "rxc-throws", detail: String(e) });
+ continue;
+ }
+ if (!out0.modules) {
+ skipped++;
+ continue;
+ }
+ ran++;
+ let v0: Record;
+ try {
+ v0 = await views(out0);
+ } catch (e) {
+ note({ app, kind: "view-unparsable", detail: (e as Error).message });
+ continue;
+ }
+ const files2 = { ...files };
+ let broke = false;
+ for (const [mod, view] of Object.entries(v0)) {
+ let r: ReturnType;
+ try {
+ // the other modules' views: what each exports, so a source read across modules reads as itself
+ // and its .d.rx files: a pure fn imports pure, an io fn does not
+ const declared = (from: string, name: string) => {
+ const d = files["/" + from.replace(/^\.\//, "").replace(/\.\w+$/, "") + ".d.rx"];
+ return d === undefined ? undefined : declaredIn(d).get(name);
+ };
+ r = toRx(parse(view), view, { declared, modules: (from) => (v0["/" + from.replace(/^\.\//, "")] === undefined ? undefined : parse(v0["/" + from.replace(/^\.\//, "")])) });
+ } catch (e) {
+ note({ app, module: mod, kind: "torx-throws", detail: (e as Error).stack ?? String(e), view });
+ broke = true;
+ continue;
+ }
+ if (r.problems.length) {
+ note({ app, module: mod, kind: "torx-refuses", detail: r.problems.map((p) => `line ${p.line}: ${p.message}`).join("\n"), rx: files[mod], view });
+ broke = true;
+ continue;
+ }
+ files2[mod] = r.code;
+ for (const [k, v] of Object.entries(r.files)) files2["/" + k] = v;
+ }
+ if (broke) continue;
+ const out2 = compile(files2);
+ if (!out2.modules) {
+ note({ app, kind: "rx2-rejected", detail: diag(out2), rx2: Object.entries(files2).filter(([k]) => k.endsWith(".rx")).map(([k, v]) => `--- ${k}\n${v}`).join("\n") });
+ continue;
+ }
+ const v2 = await views(out2);
+ for (const mod of Object.keys(v0)) {
+ if (v0[mod] === v2[mod]) continue;
+ const a = v0[mod].split("\n"), b = (v2[mod] ?? "").split("\n");
+ const i = a.findIndex((l, j) => l !== b[j]);
+ note({ app, module: mod, kind: "view-differs", detail: `first difference at line ${i + 1}\n- ${a[i]?.trim()}\n+ ${b[i]?.trim()}`, rx: files[mod], rx2: files2[mod], view: v0[mod] });
+ }
+}
+console.log(`\n${ran} apps round-tripped, ${skipped} skipped (the original does not compile), ${dup} duplicates`);
+console.log(Object.entries(counts).map(([k, v]) => `${k}: ${v}`).join("\n") || "no findings");
+if (process.env.OUT) writeFileSync(process.env.OUT, JSON.stringify(findings, null, 1));
diff --git a/site/playground/tests/torx-dir.mts b/site/playground/tests/torx-dir.mts
new file mode 100644
index 00000000..bcf4c01d
--- /dev/null
+++ b/site/playground/tests/torx-dir.mts
@@ -0,0 +1,35 @@
+// A directory of Solid .tsx modules written back as .rx: App.tsx is main.rx, the rest keep their names.
+// node tests/torx-dir.mts (prints what torx could not read; exit 1 if anything)
+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { declaredIn, toRx } from "../src/torx.ts";
+import { existsSync } from "node:fs";
+import * as babel from "prettier/plugins/babel";
+
+const [from, to, drxDir = from] = process.argv.slice(2);
+// each ./x import is checked against x.d.rx, when there is one
+const declared = (mod: string, name: string) => {
+ const f = join(drxDir, mod.replace(/^\.\//, "") + ".d.rx");
+ return existsSync(f) ? declaredIn(readFileSync(f, "utf8")).get(name) : undefined;
+};
+mkdirSync(to, { recursive: true });
+const tsx = readdirSync(from).filter((n) => /\.tsx?$/.test(n));
+const stem = (n: string) => n.replace(/\.tsx?$/, "");
+const rxName = (n: string) => (stem(n) === "App" ? "main.rx" : `${stem(n)}.rx`);
+const local = new Map(tsx.map((n) => [stem(n), rxName(n)]));
+let problems = 0;
+const helpers: Record = {};
+for (const n of tsx) {
+ const src = readFileSync(join(from, n), "utf8");
+ const r = toRx((babel as any).parsers["babel-ts"].parse(src, {}), src, { declared });
+ for (const p of r.problems) console.log(`${n}:${p.line}: ${p.message}`);
+ problems += r.problems.length;
+ // a sibling module is imported by its .rx file name
+ const code = r.code.replace(/from "\.\/([\w$-]+)"/g, (all, m) => (local.has(m) ? `from "./${local.get(m)}"` : all));
+ writeFileSync(join(to, rxName(n)), code);
+ // each module's helpers, once: modules repeat the same small functions
+ for (const [k, v] of Object.entries(r.files)) for (const part of v.split(/\n(?=export |\/\/ |type )/)) if (!(helpers[k] ?? "").includes(part.trim())) helpers[k] = (helpers[k] ? helpers[k].trimEnd() + "\n" : "") + part.trim() + "\n";
+}
+for (const [k, v] of Object.entries(helpers)) writeFileSync(join(to, k), v);
+console.log(`${tsx.length} modules, ${problems} problems`);
+process.exit(problems ? 1 : 0);
diff --git a/site/playground/tests/torx.check.mts b/site/playground/tests/torx.check.mts
new file mode 100644
index 00000000..7dfd4afe
--- /dev/null
+++ b/site/playground/tests/torx.check.mts
@@ -0,0 +1,68 @@
+// Round trip: .rx → the Solid view → .rx (toRx) → the Solid view again; the two views must match.
+// Run after `pnpm wasm`: node tests/torx.check.mts [-v]
+import { readFileSync } from "node:fs";
+import { loadRxc } from "../src/rxc.ts";
+import { presets } from "../src/presets.ts";
+import { solidify } from "../src/solidify.ts";
+import { toRx } from "../src/torx.ts";
+import { extra, samples } from "./torx.samples.mts";
+import * as prettier from "prettier/standalone";
+import * as babel from "prettier/plugins/babel";
+import * as estree from "prettier/plugins/estree";
+
+const verbose = process.argv.includes("-v");
+const call = loadRxc(new WebAssembly.Module(readFileSync(new URL("../public/rxc.wasm", import.meta.url))));
+const fmt = (c: string) => prettier.format(c, { parser: "babel", plugins: [babel, estree as any], printWidth: 100, useTabs: true });
+
+async function view(files: Record) {
+ const out = call("app", { entry: "/main.rx", target: "dom", jsx: true }, files);
+ if (!out.modules) throw new Error(out.error ?? JSON.stringify(out.diagnostics));
+ return fmt(solidify(await fmt(out.modules["/main.rx"].jsx)));
+}
+// a