Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
- `props` in a component declared without props (`component C()`) is `UNBOUND` (RG-4b); it read `undefined`.
- `guide/async.md`: "One store over the server"; the `GUESS_WHILE_LOADING` advice says what holds when a selection
changes while a guess is out (05 DV-22).
- Under `vite dev`, an edit inside a dependency's components re-renders them in place instead of reloading the page:
the module's top-level sources and every other component's state are kept. An edit to the module's top level or to
an entry still reloads. The runtime's new `@reactivescript/runtime/hot` entry does the swap; it needs a
`@solidjs/vite-plugin` with the front end's `hotUpdate` hook.

## 0.3.1

Expand Down
10 changes: 8 additions & 2 deletions compiler/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,14 @@ What happens to a `.rx` module in Vite:
The app mounts a program with `createApp` from `@reactivescript/runtime`
(`../runtime`, CP-4a), as the examples do.

Not yet: hot updates of `.rx` modules are untested; server rendering in Vite
needs a request-scoped app for server functions to run in.
Hot updates: with a Solid plugin that has the front end's `hotUpdate` hook,
an edit inside a dependency's components (markup, logic, `<style>`) swaps
them in place through `@reactivescript/runtime/hot`, keeping the module's
sources and every other component's state. An edit to a module's top level,
or to an entry, reloads the page.

Not yet: server rendering in Vite needs a request-scoped app for server
functions to run in.

### Releasing

Expand Down
2 changes: 1 addition & 1 deletion compiler/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
let path = &out.paths[name];
let text = read_disk(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] }));
modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name], "hot": out.module_hot.get(name).map(|(c, top)| json!({ "components": c, "top": top })) }));
}
Ok(json!({ "entry": set.entry, "css": out.css, "modules": modules }))
})()
Expand Down
50 changes: 49 additions & 1 deletion compiler/src/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,9 @@ pub struct Compiled {
pub css: String,
/// CSS-4: each module's own stylesheet, by its output name
pub module_css: IndexMap<String, String>,
/// a dependency's exported components and a fingerprint of the rest of its text, by output name: a dev server swaps the
/// components when the fingerprint holds
pub module_hot: IndexMap<String, (Vec<String>, String)>,
}

/// 09 MO-1: one ES module per `.rx` module. A dependency's module is a factory over the app (`__rt.module` runs it once per
Expand All @@ -205,6 +208,7 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
let mut files = IndexMap::new();
let mut paths = IndexMap::new();
let mut module_css = IndexMap::new();
let mut module_hot = IndexMap::new();
for path in &set.order {
let p = &set.programs[path];
let css0 = g.css.len();
Expand Down Expand Up @@ -239,13 +243,57 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
body.append(&mut g.top);
let mut fbody = vec![konst("__B", dot(id("__rt"), "B"))];
fbody.append(&mut inner);
if let Some(shape) = hot_shape(p, set.sources.get(path).map(String::as_str).unwrap_or("")) {
module_hot.insert(g.out(path), shape);
}
body.push(S::ExportDefault(Func { name: Some("module".into()), params: vec![P::Id("__rt".into())], directives: vec![], body: fbody, is_async: false, generator: false }));
}
module_css.insert(g.out(path), g.css[css0..].join("\n"));
files.insert(g.out(path), body);
paths.insert(g.out(path), path.clone());
}
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n"), module_css })
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n"), module_css, module_hot })
}

/// A dependency's exported components, and a hash of its text outside their bodies (each component's header stays in it);
/// `None` when that text names a JS import or calls an `.rx` one, which a replay would call again outside its record.
fn hot_shape(p: &Program, text: &str) -> Option<(Vec<String>, String)> {
use std::hash::{Hash, Hasher};
let names = |js: bool| -> Vec<String> {
p.decls.iter().filter_map(|d| match d { Decl::Import { resolved, names, .. } if resolved.is_none() == js => Some(names), _ => None }).flatten().map(|n| regex::escape(&n.alias)).collect()
};
let (js, rx) = (names(true), names(false));
let mut alts = vec![];
if !js.is_empty() {
alts.push(format!(r"\b(?:{})\b", js.join("|")));
}
if !rx.is_empty() {
alts.push(format!(r"\b(?:{})\s*\(", rx.join("|")));
}
let word = (!alts.is_empty()).then(|| regex::Regex::new(&alts.join("|")).ok()).flatten();
let mut h = std::collections::hash_map::DefaultHasher::new();
let mut components = vec![];
for d in &p.decls {
let span = d.span();
let (start, end) = (span.start as usize, span.end as usize);
let own = text.get(start..end).unwrap_or("");
match d {
Decl::Component { name, props, props_type, exported, is_default, .. } => {
(name, props, props_type, exported, is_default).hash(&mut h);
if *exported {
components.push(name.clone());
}
}
Decl::Import { .. } => own.hash(&mut h),
_ => {
if word.as_ref().is_some_and(|w| w.is_match(own)) {
return None;
}
own.hash(&mut h);
}
}
}
Some((components, format!("{:016x}", h.finish())))
}

struct Gen<'p> {
Expand Down
66 changes: 65 additions & 1 deletion compiler/test/vite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ function project(name, entry) {
return dir;
}
const config = (dir, entry) => ({
root: dir, configFile: false, logLevel: "warn", clearScreen: false,
// a cache per project: the default, under the nearest package.json, would serve one run's runtime to the next
root: dir, cacheDir: path.join(dir, ".vite"), configFile: false, logLevel: "warn", clearScreen: false,
plugins: [solid()],
server: { fs: { allow: [repo, path.dirname(deps), path.resolve(repo, "../solid-next"), pluginDir] } },
build: { outDir: "dist", sourcemap: true, emptyOutDir: true },
Expand Down Expand Up @@ -145,6 +146,69 @@ if (!filter || "styles".includes(filter)) { // CSS-4 under the dev server: a d
});
await server.close();
}
if (!filter || "hot".includes(filter)) { // a dependency's component edit swaps in place; a top-level or entry edit reloads
const dir = project("hot-dev", "hot/main.rx");
mkdirSync(path.join(dir, "src/hot"));
const main = path.join(dir, "src/hot/main.rx"), panel = path.join(dir, "src/hot/panel.rx");
writeFileSync(main, `import { Panel } from "./panel.rx"\nimport { Other } from "./other.rx"\nimport { Tick } from "./tick.rx"\n\nexport default component Main() {\n <main><Panel /><Other /><Tick /></main>\n}\n`);
writeFileSync(path.join(dir, "src/hot/other.rx"), `export component Other() {\n source n := 0\n <button class="other" onClick={() => { n := n + 1 }}>other {n}</button>\n}\n`);
// a top level that calls into JS: a replay would call it again, so its module always reloads
const tick = path.join(dir, "src/hot/tick.rx");
writeFileSync(path.join(dir, "src/hot/clock.mjs"), `export const now = () => "one";\n`);
writeFileSync(tick, `import pure { now } from "./clock"\n\nfirst = now()\n\nexport component Tick() {\n <p class="tick">{first}</p>\n}\n`);
const lib = path.join(dir, "src/hot/lib.mjs");
writeFileSync(lib, `export const word = () => "one";\n`);
const source = ({ top = "", label = "total", color = "rgb(0, 0, 255)", step = 1 } = {}) =>
`import pure { word } from "./lib"\n\n${top}source total := 0\n\nexport component Panel() {\n said = word()\n <style>\n .panel { color: ${color} }\n </style>\n <button class="panel" onClick={() => { total := total + ${step} }}>${label} {total}</button>\n <p class="said">{said}</p>\n}\n`;
writeFileSync(panel, source());
const server = await vite.createServer(config(dir, "hot/main.rx")); await server.listen(0);
await drive("hot (dev)", server.resolvedUrls.local[0], async page => {
const seen = async () => ({
panel: (await page.textContent(".panel").catch(() => "")).trim(), other: (await page.textContent(".other").catch(() => "")).trim(),
color: await page.$eval(".panel", e => getComputedStyle(e).color).catch(() => ""), kept: await page.evaluate(() => window.__kept === 1).catch(() => false),
said: (await page.textContent(".said").catch(() => "")).trim(),
});
const until = async (what, want) => {
let got;
for (let i = 0; i < 50; i++) { got = await seen(); if (Object.entries(want).every(([k, v]) => got[k] === v)) return; await page.waitForTimeout(100); }
throw new Error(`${what}: ${JSON.stringify(got)}, not ${JSON.stringify(want)}`);
};
for (let i = 0; i < 3; i++) await page.click(".panel");
for (let i = 0; i < 2; i++) await page.click(".other");
await page.evaluate(() => { window.__kept = 1; });
await until("before the edits", { panel: "total 3", other: "other 2" });
// the module-level source and the other module's component state survive; the page is not reloaded
writeFileSync(panel, source({ label: "sum" }));
await until("after a markup edit", { panel: "sum 3", other: "other 2", kept: true });
writeFileSync(panel, source({ label: "sum", color: "rgb(255, 0, 0)" }));
await until("after a <style> edit", { color: "rgb(255, 0, 0)", panel: "sum 3", other: "other 2", kept: true });
writeFileSync(panel, source({ label: "plus", color: "rgb(255, 0, 0)", step: 10 }));
await until("after a logic edit", { panel: "plus 3", kept: true });
await page.click(".panel"); await until("the new handler", { panel: "plus 13", other: "other 2", kept: true });
// a JS module the dependency imports changed: what its top level read from it may be stale, so the page reloads
writeFileSync(lib, `export const word = () => "two";\n`);
await until("after an import's edit", { said: "two", panel: "plus 0", kept: false });
await page.evaluate(() => { window.__kept = 1; }); await page.click(".other");
writeFileSync(tick, readFileSync(tick, "utf8").replace('class="tick"', 'class="tick edited"'));
await until("after an edit to a module whose top level calls JS", { other: "other 0", kept: false });
await page.evaluate(() => { window.__kept = 1; });
// the module's top level changed: a reload, with the module's new state
writeFileSync(panel, source({ top: "base = 1\n", label: "plus", color: "rgb(255, 0, 0)" }));
await until("after a top-level edit", { panel: "plus 0", other: "other 0", kept: false });
await page.evaluate(() => { window.__kept = 1; }); await page.click(".other");
writeFileSync(main, readFileSync(main, "utf8").replace("<main>", `<main class="edited">`));
await until("after an entry edit", { other: "other 0", kept: false });
if (!await page.$("main.edited")) throw new Error("the entry's edit did not reach the page");
// a dependency that stops compiling, then compiles again, swaps as before
writeFileSync(panel, source({ label: "plus" }) + "\nexport bad = missingName\n"); await page.waitForTimeout(800);
writeFileSync(panel, source({ label: "back" }));
await until("after the fix", { panel: "back 0" });
await page.evaluate(() => { window.__kept = 1; }); await page.click(".panel");
writeFileSync(panel, source({ label: "again" }));
await until("after an edit that follows a failed compile", { panel: "again 1", kept: true });
});
await server.close();
}
if (!filter || "cold".includes(filter)) { // a dependency asked for before its entry, as Vitest's `fsModuleCache` leaves it
const { default: rx } = await import(pathToFileURL(path.join(pkg, "vite.mjs")).href);
const root = project("cold", "shop/main.rx"), catalog = path.join(root, "src/shop/catalog.rx");
Expand Down
56 changes: 52 additions & 4 deletions compiler/vite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// changes. The crate's output imports its dependencies as `./x.rx?rx-dep`, and a dependency is served from the build
// of a program that contains it. A module several programs share is one module: its instance is keyed by its factory
// (11 CP-4b `module`), not by its place in a program.
import { createHash } from "node:crypto";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
Expand Down Expand Up @@ -58,6 +59,31 @@ function entriesOf(file, root) {
return [...seen].sort().sort((a, b) => top(b) - top(a));
}

/** A dependency's factory, wrapped for hot updates (the runtime's `hot` entry); lines are only added after the module's. */
function hotFooter(code, hot) {
// the code's own hash: a version re-run for an import's change, with its own code unchanged, reloads
const meta = { ...hot, code: createHash("sha1").update(code).digest("hex").slice(0, 16) };
const wrapped = code.replace(/^export default function module\(__rt\)/m, "function module(__rt)");
if (wrapped === code) return code;
return `${wrapped}
import { hotModule as __rxHotModule } from "@reactivescript/runtime/hot";
const __rxHot = __rxHotModule(import.meta.hot, module, ${JSON.stringify(meta)});
export default __rxHot.factory;
if (import.meta.hot) import.meta.hot.accept(__rxHot.accept);
`;
}

const hasHotRuntime = new Map();
/** Whether the project's `@reactivescript/runtime` has the `hot` entry the footer imports (0.3.1 and older do not). */
function hotRuntime(root) {
if (!hasHotRuntime.has(root)) {
let ok = true;
try { createRequire(path.join(root, "package.json")).resolve("@reactivescript/runtime/hot"); } catch { ok = false; }
hasHotRuntime.set(root, ok);
}
return hasHotRuntime.get(root);
}

/** @returns {import("@solidjs/vite-plugin").Frontend} */
export default function rx() {
const builds = new Map(); // entry\0target\0moduleName\0spa → { entry, target, moduleName, spa, out, stamps }
Expand All @@ -69,10 +95,13 @@ export default function rx() {
const out = JSON.parse(app(entry, target, moduleName, spa));
if (out.modules) out.modules = Object.fromEntries(Object.entries(out.modules).map(([p, m]) => [path.resolve(p), m]));
const files = out.modules ? Object.keys(out.modules) : out.diagnostics ? [...new Set([entry, ...out.diagnostics.map(d => d.file)])] : [entry];
if (out.modules) for (const f of files) if (f !== path.resolve(entry)) dependencies.add(f);
const b = { entry, target, moduleName, spa, out, stamps: new Map(files.map(f => [f, mtime(f)])) };
builds.set(key, b);
return b;
}
const restyling = new Set(); // dependencies whose stylesheet the plugin is about to ask for, after hotUpdate
const dependencies = new Set(); // every file a program built so far held as a dependency, kept when its program fails
const built = (file, target, moduleName, spa) =>
[...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.out.modules?.[file]);
/** A dependency: from a build of a program that has it, rebuilt if that program changed. */
Expand All @@ -91,20 +120,39 @@ export default function rx() {
throw new Error(`${file} is imported as an .rx dependency, but no program under ${root} contains it`);
}
return {
compile(_source, { id, moduleId, root, solid, addWatchFile }) {
// A dependency hot-swaps (rt-hot.ts) when no other module of any program that holds it compiles differently and its
// text outside its components' bodies is unchanged; then the entry, which watches every module of its program, is left
// out of the update, so the page keeps its state. Otherwise Vite's list stands, and the entry reloads the page.
hotUpdate({ file, modules }) {
file = path.resolve(file);
// the plugin compiles the changed file next, by its path alone, for its stylesheet
if (dependencies.has(file)) restyling.add(file);
const holding = [...builds.values()].filter(b => b.out.modules?.[file]);
if (!holding.length) return;
for (const b of holding) {
const before = b.out, after = build(b.entry, b.target, b.moduleName, b.spa).out;
const was = before.modules[file].hot, now = after.modules?.[file]?.hot;
if (!was || !now || was.top !== now.top || was.components.join() !== now.components.join()) return;
const paths = new Set([...Object.keys(before.modules), ...Object.keys(after.modules)]);
for (const p of paths) if (p !== file && before.modules[p]?.code !== after.modules[p]?.code) return;
}
return modules.filter(m => isDep(m.id ?? m.url ?? ""));
},
compile(_source, { id, moduleId, root, solid, addWatchFile, hot }) {
const file = path.resolve(id);
const target = solid.generate === "ssr" ? "ssr" : solid.generate === "universal" ? "universal" : "dom";
const moduleName = solid.moduleName ?? "@solidjs/web";
// 08 CN-3d: a client-only build (no SSR, nothing hydrates) has nothing to show on a first load nothing holds
const spa = target === "dom" && solid.hydratable === false;
const dep = isDep(moduleId);
const { out } = dep ? containing(file, target, moduleName, spa, path.resolve(root ?? process.cwd())) : build(file, target, moduleName, spa);
const dep = isDep(moduleId) || restyling.delete(file);
const projectRoot = path.resolve(root ?? process.cwd());
const { out } = dep ? containing(file, target, moduleName, spa, projectRoot) : build(file, target, moduleName, spa);
if (out.diagnostics) throw new Error(report(out.diagnostics));
if (out.error) throw new Error(out.error);
const m = out.modules[file];
for (const p of Object.keys(out.modules)) if (p !== file) addWatchFile(p);
// CSS-4: each module links its own stylesheet, so a module several programs share links it once
return { code: tagDeps(m.code), map: m.map, css: m.css ?? "" };
return { code: dep && hot && m.hot && hotRuntime(projectRoot) ? hotFooter(tagDeps(m.code), m.hot) : tagDeps(m.code), map: m.map, css: m.css ?? "" };
},
};
}
Loading