@ape-egg/vibe
v3.0.4
Published
Runtime-first reactivity for plain HTML — no build step, no virtual DOM, no new syntax to learn
Maintainers
Readme
Vibe
Version 3.0.4 — Runtime-first reactivity for plain HTML. Drop a script tag into any page and get reactive bindings, control flow, and URL-loaded components — no build step required. Compile later if you want; the compiler is a separate, optional package (@ape-egg/vibe-compiler).
Security model & CSP
Vibe escapes by default: @[expr] renders as text, never markup. The one deliberate exception is @[$.unsafe(trustedHtml)], which sets innerHTML and is for trusted input only.
What you must know before adopting: Vibe's engine evaluates binding expressions with new Function and uses inline on* attributes as its event model. A site running Vibe therefore needs a Content-Security-Policy that allows 'unsafe-eval' and inline event handlers — i.e. it cannot deploy a strict CSP. Vibe itself is not an XSS vector, but strict CSP is a browser-level safety net against other injection bugs anywhere on a page, and Vibe requires that net loosened.
If you ship to an environment that mandates strict CSP (banks, healthcare, government, security-reviewed enterprise), Vibe is currently the wrong tool. For everything else — personal sites, games, dashboards, internal tools, most product work — this is the same posture as running Vue's in-browser template compiler or Alpine.js, and it is a documented trade-off, not an accident.
No virtual DOM. No build step required. Just modern JavaScript. When you need production optimizations, add the optional Rust-based compiler.
npm install @ape-egg/vibeStatus: Functional and ready to use, but expect bugs and breaking changes daily until stable. Use in production at your own risk.
Vibe Runtime
The core reactive runtime. Works directly in the browser without any build tools.
Quick Start
<html>
<head>
<link rel="stylesheet" href="./node_modules/@ape-egg/vibe/vibe.css" />
<script type="module">
import vibe from './node_modules/@ape-egg/vibe/index.js';
window.$ = vibe({ name: 'World', count: 0 });
</script>
</head>
<body vibe-fouc>
<h1>Hello, @[name]!</h1>
<button onclick="$.count++">Clicked @[count] times</button>
</body>
</html>The vibe() Signature
window.$ = vibe(state, config?, targetSelector?);state(object, required) — initial reactive state. Becomeswindow.$. Mutate freely ($.count++,$.user.name = 'Alice'); deep mutations trigger updates automatically. Methods on the object are preserved.config(object, optional) — runtime configuration. Currently supported keys:debug(boolean, defaultfalse) — colored console logs for every lifecycle phase (parse, hydrate, iterate, mutate, …). Useful for debugging reactivity issues.noCache(boolean, defaultfalse) — disable the component template cache (see Component Template Caching below). When set, every<component src>mount refetches its template.
targetSelector(string, optional) — CSS selector for the root element vibe attaches to. Defaults todocument.body. Vibe parses, hydrates, and observes mutations only inside this root — anything outside (e.g.<head>, sibling<aside>elements) is ignored. If the selector matches nothing, vibe silently falls back todocument.body. Pass'html'to include<head>(e.g. for binding<title>@[pageTitle]</title>).
window.$ = vibe({ count: 0 }, { debug: true }, '#app');Prevent FOUC
To prevent a flash of unstyled content while Vibe hydrates:
- Include
vibe.cssin your HTML - Add the
vibe-foucattribute (orclass="vibe-fouc") to an element — typically<body>
vibe.css hides [vibe-fouc] and .vibe-fouc until hydration completes; Vibe removes the attribute/class once it's done.
Reactive Bindings
Vibe supports bindings in three positions:
Text content — Inside element tags:
<div>@[firstName] @[lastName]</div>
<h1>Hello, @[name]!</h1>Attribute values — In attribute value position:
<input value="@[username]" />
<div class="@[theme]" style="color: @[color]"></div>
<a href="@[url]">Link</a>Attribute names — In attribute name position (useful for dynamic attributes):
<icon @[iconName]></icon>
<button @[state]>Click me</button>CSS — Bindings also work in style tags:
<style>
.box {
background: @[themeColor];
}
</style>Iteration
<!-- each items as item, index -->
<li>@[index]: @[item]</li>
<!-- /each -->The "array" position accepts any JS expression evaluated in scope, not just a state path:
<!-- each items.filter(i => i.active) as item -->...<!-- /each -->
<!-- each Array.from({ length: count }) as n, index -->...<!-- /each -->Keyed iteration — give each row a stable identity with (keyExpr) so survivors keep their DOM (and listeners / animation state) when the list reorders or items are removed. The key comes before the optional index. Without a key, Vibe falls back to an index-coupled hash and bulk-re-renders the tail on reorder.
<!-- each rows as row (row.id) -->
<li>@[row.label]</li>
<!-- /each -->
<!-- key + index -->
<!-- each rows as row (row.id), index -->
<li>@[index]: @[row.label]</li>
<!-- /each -->Nested iteration with dot paths:
<!-- each categories as category -->
<!-- each category.items as item -->
<span>@[item.name]</span>
<!-- /each -->
<!-- /each -->Conditionals
<!-- if user.isAdmin -->
<admin-badge>Admin</admin-badge>
<!-- else -->
<span>User</span>
<!-- /if -->Components
Runtime component loading with props and slots. Slot content (between the tags) replaces <slot></slot> inside the component template:
<!-- /components/card.html -->
<div class="card">
<h3>@[title]</h3>
<slot></slot>
</div>
<!-- usage -->
<component src="/components/card.html" title="@[pageTitle]" theme="dark">
<p>Content passed as slot</p>
</component><div class="component" src="..."> is an equivalent alternative to <component src="..."> for cases where standard HTML elements are required (validation, accessibility tooling).
Props can be reactive bindings (title="@[pageTitle]"), static literals (theme="dark"), or live objects/arrays passed through iteration scope (<component src="/card.html" card="@[card]"> inside <!-- each cards as card -->). Non-primitive props are stashed in an internal registry so the child template can dot/iterate into them (@[card.name], <!-- each card.abilities as a -->).
Component-Local State
For state scoped to a single component, import component from @ape-egg/vibe/component and call it from a <script type="module"> inside the component file:
<!-- /components/Counter.html -->
<script type="module">
import component from '@ape-egg/vibe/component';
component({
count: 0,
increment() { this.count++; }
});
</script>
<button onclick="this.increment()">Clicked @[this.count] times</button>How it works:
component({...})generates a unique id (e.g._c0,_c1) and registers the state at$[id]- The
<script>and every following sibling is tagged withdata-vibe-component-id="<id>" - Inside that subtree,
@[this.X.Y]is rewritten to@[_c0.X.Y]and event handlers likeonclick="this.method()"oroninput="$.this.value = ..."are rewritten to address$[id] - When the component leaves the DOM, its state entry is freed automatically
Multi-segment paths (@[this.user.profile.name]), conditionals (<!-- if this.editing -->), and iterations (<!-- each this.items as item -->) all resolve against the component's bucket. Global $ and component this.X coexist freely.
Drop-In Components (no vibe() needed)
component() auto-boots the runtime. You can drop a self-contained reactive block into any HTML page — no top-level vibe(...) call, no global state setup, no build step. Import directly from a CDN and the runtime wires itself up:
<component>
<script type="module">
import component from 'https://esm.sh/@ape-egg/vibe/component.js';
component({ count: 0 });
</script>
<button onclick="this.count--">-</button>
<span>Count: <strong>@[this.count]</strong></span>
<button onclick="this.count++">+</button>
</component>How it works:
component({...})claims the nearest unprocessed<component>(or<div class="component">) wrapper, registers state at$[id], and tags the wrapper withdata-vibe-component-id- Internally it triggers the boot pipeline, which initializes
window.$, parses the DOM, hydrates bindings, and starts the MutationObserver — exactly once, even if multiple<component>blocks callcomponent() - From there,
@[this.X],onclick="this.fn()", and<!-- if this.X -->work as documented
Multiple drop-in blocks on the same page each get their own state bucket. They can read each other's state via global $['_c0'].count if they need to coordinate, but in most drop-in cases they're independent.
Component Template Caching
Vibe loads a <component src="..."> by fetching its HTML template. A page often mounts the same component many times (a list of cards, a row of stat bars), and an SPA re-mounts components on every navigation. By default Vibe caches each fetched template by src, so:
- Concurrent mounts coalesce. Twenty
<component src="/components/Bar.html">in the same render share one in-flight request instead of stampeding the network with twenty. - Repeat mounts are free. Later mounts — including after an SPA navigation away and back — resolve the template from memory with no network request at all. This is the one win a browser HTTP cache can't give you: it revalidates per request and never coalesces concurrent ones.
The cache is session-lived and content-busted, never time-based. In production a component template is immutable for the life of the page (it only changes on redeploy, which is a new session), so there is nothing to invalidate and no staleness window. Per-instance props, slots, and component-local state are unaffected — only the fetched template text is shared; each instance still hydrates independently.
Turn it off with vibe(state, { noCache: true }) — useful if you serve component HTML that genuinely changes within a session.
Manual invalidation (rarely needed):
$.clearComponentCache('/components/Card.html'); // drop one template (query string ignored)
$.clearComponentCache(); // drop all cached templatesDev note:
@ape-egg/vite-plugin-vibecalls$.clearComponentCache(path)on hot update, so editing a component file is reflected immediately for both live and freshly-mounted instances — the runtime itself stays free of any dev-server coupling.
Lifecycle Hooks
$.on('ready', () => {}); // once, after initial parse + first hydrate + all components mounted
$.on('afterUpdate', (cur, prev) => {}); // every state change (batched per microtask)
$.on('afterDomMutation', () => {}); // after every MutationObserver batch$.ready is also exposed as a Promise (await $.ready), useful for code that captured window.$ before boot.
$.on('unmount', () => {}); // scope-resolved teardown: component scripts → that component
// unmounts; page level → pagehideSPA Router (@ape-egg/vibe/spa)
A standalone client-side router built on one contract: $.page = { path, route, params, src, name }. Point a reactive component src at it and the outlet is your route view:
<script type="module">
import vibe from '@ape-egg/vibe';
import { setupSpa, resolve } from '@ape-egg/vibe/spa';
const routes = [
{ route: '/brawlers/:index', src: '/components/brawler.html', title: 'Brawler' },
{ route: '/docs/:rest*', src: '/components/docs.html' },
{ route: '/', src: '/components/home.html', title: 'Home' },
{ route: '*', src: '/components/lost.html' },
];
window.$ = vibe({ page: resolve(location, routes) ?? {} });
setupSpa({ routes });
</script>
<component src="@[page.src]" key="@[page.path]"></component>Route grammar (shared with the compiler's route table): literal segments, :param captures one segment, a trailing :name* captures zero or more (/docs matches with rest: ''), and '*' is the declared no-match fallback. Tables are pre-sorted most-specific-first; resolve returns the first match. resolve(location, routes) is pure — it accepts anything with a .pathname (or a bare path string) and returns { path, route, params, src, name, title? } or null.
Route names: name is the route slug — segments joined with dashes, params flattened to their bare name: '/' → 'home', '/pve/:id' → 'pve-id', '/docs/:rest*' → 'docs-rest', the '*' fallback keeps its literal '*'. Stable across param values, so markup hangs page-scoped attributes and active checks on it: <page @[page.name]>, page.name.startsWith('pve').
Keyed outlet: key on a fetched <component> declares its identity — when the resolved key changes, the component remounts even if src is unchanged. With key="@[page.path]", param→param navigation on the same route (/brawlers/0 → /brawlers/1 — same fragment src) mounts fresh, exactly like an MPA reload on the new URL. src and key are the wrapper's own contract and are never passed to the component as props.
Link claiming: one document-level click listener claims same-origin, unmodified, untargeted clicks whose pathname matches a real route — pushState + a fresh $.page assignment + document.title swap when the route carries one, scroll to top. Everything else navigates natively: other origins, modified clicks, target/download links, same-page hash anchors, and unrouted paths — which is what makes mixed MPA/SPA output work. '*' never claims a click; it only resolves deep-link entries and popstate. popstate re-resolves (including '*') without scrolling — the browser restores position.
No match, no '*': $.page.src stays unset and the outlet mounts nothing. There is no built-in 404.
setupSpa({ routes, onNavigate? }) returns { navigate, dispose }. navigate(path) claims like a link click (unrouted paths get a native load); dispose() removes the listeners. Pass a custom onNavigate(resolved) and the module is a pure router — parse/claim/history only, no Vibe in sight.
App-Lifetime State Defaults (built into vibe())
vibe() called once the app is booted applies defaults semantics: only keys that do not yet exist on $ are set.
import vibe from '@ape-egg/vibe';
vibe({ ...globalState, notifications: [] }); // first mount seeds, re-mounts never clobberPre-boot, state accumulates and boot is queued as always — on a fresh document load nothing changes, MPA behavior is byte-identical. Once booted, "initial state, declared again" seeds missing keys only: under SPA a re-mounted page fragment's vibe({...}) call re-runs on every visit, and live state (notifications, session, timers) is never reset to initial values. No separate entry, no compiler rewrite — the same import does the right thing in both lifetimes. The pure applyDefaults(target, state) is exported for reuse.
The rule: vibe() state is app-lifetime; component() state is mount-lifetime (resets per visit). Per-page-reset state belongs in a component — that's the Timer pattern.
Subtree Reconciliation (advanced)
$.reconcile(el, html) and $.renderComponent(rawHtml, props, slot, opts) are public-but-advanced APIs used by the vite plugin's HMR path. Their shape may evolve; treat them as plumbing rather than application code for now.
Dehydrate
Skip reactive processing for an element:
<code vibe-dehydrate>@[this] displays literally</code>Raw HTML ($.unsafe)
@[expr] escapes its output (textContent) — safe by default. To render trusted markup instead, wrap the value in $.unsafe(...); the binding sets innerHTML. This is Vibe's equivalent of Svelte {@html} / Vue v-html / React dangerouslySetInnerHTML.
<p>@[$.unsafe(description)]</p>- The binding must be the sole content of its element (innerHTML semantics). Mixed into surrounding text, it falls back to escaped literal text.
- Injected markup is inert —
@[...]/<!-- if -->/<!-- each -->inside it are not processed (matches Svelte{@html}); the subtree is opaque to the MutationObserver. - Fully reactive — re-renders on value change; works in iterations, conditionals, and components. Compiled mode paints the markup at stamp time and re-hydrates at runtime.
- Trusted input only — no sanitizing. Don't pass user-supplied strings.
Internal Names (don't collide)
These are used by the runtime — don't repurpose them in your code:
window.__vibeManifest,window.__vibeCompiling,window.__vibeComponents,window.__vibeIterProps— internal registriesdata-vibe-component-id,data-vibe-iter-prop— element-level bookkeeping attributes (set automatically)
Deep Reactivity
Vibe uses recursive proxies to detect changes at any nesting level:
// All of these trigger reactive updates:
$.user.name = 'Alice';
$.todos[2].completed = true;
$.config.theme.colors.primary = '#007bff';No need for immutable update patterns or spread operators. Just mutate and Vibe handles the rest.
How It Works
- Proxy-based state —
window.$intercepts property changes - Deep reactivity — Nested mutations trigger updates automatically (
$.obj.nested.prop = x) - DOM parsing — Finds all
@[...]bindings on load - Auto-tracked subscriptions — Every binding, conditional, and iteration records which state keys its expression read during evaluation; a write dispatches exactly its subscribers — O(what changed), no tree walk, no virtual DOM
- MutationObserver — Tracks dynamically added elements
One contract follows from #4: an expression that should react must read reactive state. @[items.map(format)] re-renders when $.items changes because items was read from $ — but if format is a window global that you later reassign, nothing re-renders, because assigning a global is not a state write. Values that change over time belong in $. (Helpers defined by component scripts are safe: mounts re-settle their directives once their scripts have run.)
Vibe Compiler
Optional build step for production optimization. The compiler provides component inlining, iteration optimization, watch mode, and hydration manifests while preserving directory structure.
Installation
The compiler requires Rust for non-macOS ARM64 platforms:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shNote: A prebuilt binary for macOS ARM64 is included. Other platforms will compile from source automatically.
Usage
# Initialize config in package.json
bunx vibe compile --init
# Basic compilation
bunx vibe compile
# or shorthand
bunx vibe c
# Watch mode (incremental compilation)
bunx vibe compile --watch
# Production build
bunx vibe compile --minify --source-maps
# With options
bunx vibe compile --verbose # Step-by-step logging
bunx vibe compile --minify # Minify output
bunx vibe compile --elements-as-is # Keep custom elements as-is
bunx vibe compile --source-maps # Generate source maps
bunx vibe compile --node-modules-as-is # Copy node_modules as-is
bunx vibe compile --components-as-is # Skip component inlining
bunx vibe compile --runtime-as-is # Skip manifest generation
bunx vibe compile --iterations-as-is # Skip iteration optimization
bunx vibe compile --spa # Compile the pages tree to SPA outputOr via npm scripts:
{
"scripts": {
"compile": "vibe compile",
"compile:watch": "vibe compile --watch",
"compile:prod": "vibe compile --minify --source-maps"
}
}Then run with npm run compile or bun compile.
Configuration
Add to your package.json:
{
"vibe-compiler": {
"source": "./",
"output": "./compiled",
"components": "components",
"pages": "pages",
"assets": "assets",
"minify": false,
"elementsAsIs": false,
"reservedElements": [],
"sourceMaps": false,
"nodeModulesAsIs": false,
"componentsAsIs": false,
"runtimeAsIs": false,
"iterationsAsIs": false,
"spa": false
}
}Key Options:
elementsAsIs: false— Transform custom elements to divs (default)reservedElements: []— Additional element names to reserve (appends to built-in HTML5 elements + "component")componentsAsIs: false— Inline components (default) or keep separate for runtimeiterationsAsIs: false— Optimize iterations (default) or use runtime renderingruntimeAsIs: false— Generate manifest (default) or skip for runtime-onlyspa: false— Compile the pages tree to SPA output: fragments + route table + shell (see SPA Mode)
Defaults (when no config):
source:./output:./compiledcomponents:<source>/componentspages:<source>/pagesassets:<source>/assets
Asset Handling
The compiler uses a whitelist approach. These file types are automatically copied:
Fonts: .ttf, .otf, .woff, .woff2, .eot
Images: .png, .jpg, .jpeg, .gif, .svg, .webp, .avif, .ico
Media: .mp4, .webm, .ogg, .mp3, .wav, .flac, .aac
Documents: .pdf
Data: .json, .xml, .csv
HTML, CSS, and JavaScript files are processed by the compiler.
Node Modules (Self-Contained Output)
By default, the compiler creates deployable output by installing production dependencies directly into the output directory:
- Copies
package.jsonand lockfile to output - Runs
<package-manager> install --productionin output directory - Removes
package.jsonand lockfile from output (cleanup)
This ensures:
- Compiled output only includes runtime dependencies (from
dependencies, notdevDependencies) - Local
node_modulesis never modified - Faster than copying (no intermediate copy step)
Package Manager Detection:
Auto-detects based on lockfiles: bun.lockb, pnpm-lock.yaml, yarn.lock, package-lock.json
Opt-out:
Set nodeModulesAsIs: true in config or use --node-modules-as-is flag to copy node_modules as-is.
Watch Mode
Watch mode enables incremental compilation with intelligent dependency tracking:
bunx vibe compile --watchFeatures:
- Incremental builds — Only recompiles changed files (~100ms)
- Dependency tracking — Changes to components trigger recompilation of pages using them
- Debounced — 300ms debounce prevents excessive compilation during rapid changes
- Delta output — First compile shows full output, subsequent compiles show only changes
SPA Mode
"spa": true (or --spa) compiles the same MPA pages/ tree into a single-page app — authors change nothing about how pages are written:
{ "vibe-compiler": { "spa": true } }The pages tree becomes three things:
- Page fragments at
/components/vibe-spa/<pages-relative-path>— each page's body content, with its head<style>tags prepended and its<script type="module">carried along byte-identical. No rewrites:vibe()itself applies defaults semantics once booted (see App-Lifetime State Defaults above), so page state gets app-lifetime behavior with the page's own import. - A generated route table —
pages/brawlers/$index.html→{ route: '/brawlers/:index', src: '/components/vibe-spa/brawlers/$index.html', title: <harvested from the page's <title>> }.$param→:param, terminal$$name→:name*, terminalindexserves its directory path. Sorted most-specific-first. - A composed shell at the output root
/index.html— plain runtime-Vibe code: the deduped union of every page's head resources (<meta>keeps only the set common to all pages; page-specific meta is dropped with a verbose note), the/route's title, the union of page body attributes minusvibe-fouc, one generated boot script (resolveseeds$.page,setupSpawires navigation — imports reuse the pages' own import style), and the keyed route outlet:<component src="@[page.src]" key="@[page.path]"></component>(a path change remounts the fragment even when the route — and so the src — is unchanged: param→param navigation mounts fresh, like the MPA reload it replaces).
What SPA mode skips: per-page stamped HTML, per-page manifests, and the pages/ output directory. Fragments are runtime-parsed on mount (per-route lazy loading falls out of the reactive src for free); the shell itself gets a manifest but is deliberately left unstamped — it is served at every route path, so its first paint is location-dependent by nature. The shell ships without vibe-fouc: its absence is the compiled-mode marker (it gates hyperspeed manifest loading), and there is nothing to flash — the outlet is empty and fragments hydrate off-DOM before insertion.
Deployment: one rewrite — every route serves /index.html; /components/**, /vibe-hyperspeed/**, and assets serve as files. The vercel.json shape:
{
"rewrites": [
{ "source": "/((?!components/|vibe-hyperspeed/|nodemodules/|.*\\..*).*)", "destination": "/index.html" }
]
}Dev-server equivalents: any "history API fallback" option (http-server can't rewrite; vite preview, serve -s, and Caddy try_files all can).
Watch mode: --spa --watch re-runs the SPA pass on any pages-tree change — edited pages re-transform, added/removed pages resync the route table and prune orphan fragments, title/head edits recompose the shell, and the shell's manifest refreshes.
Current scope: spa: true converts the entire pages tree (per-page selection is planned as a config-object form — parsing already tolerates it). Fragments ship as separate fetched files either way; componentsAsIs decides their children: false (the default) inlines child components into each fragment, making every route one self-contained fetch, while true keeps children as runtime <component src> fetches deduped across routes by the component cache. Compiling every fragment into the shell itself behind route conditionals (single document, zero per-route fetches) is specified but lands only once compiled branch-scripts stop double-running. Pages that wrap themselves in a Layout component remount it per navigation — exactly like an MPA reload; persistent chrome is out of scope for now. components/vibe-spa/ in your source is reserved.
MPA → SPA Compliance Contract
SPA mode assumes; this contract defines. Pages that follow it compile to MPA today and SPA tomorrow with no edits:
- Side effects register teardown. Anything a page script starts —
setInterval,addEventListener, sockets — must be released in$.on('unmount', …). Under MPA that callback fires onpagehide; under SPA it fires when the page fragment unmounts on navigation. The compiler emits a warning for page scripts that start side effects and never reference$.on('unmount'. vibe()state is app-lifetime;component()state is mount-lifetime. Under SPA, a page'svibe({...})seeds missing keys only (defaults semantics) — it never resets live state. State that must reset on every visit belongs in acomponent().- Head resources are shell-safe. Stylesheets and scripts linked from a page's
<head>end up in the shared shell head (deduped union) — they must be safe to load once for the whole app. Page-specific styling goes in<style>tags (which travel with the fragment) or components, not head links. Page-specific<meta>is dropped. - No full-document assumptions. Pages don't rely on
window.onload-era patterns or being the entire document — a page's body becomes a fragment inside a live shell. Use absolute URLs for assets and component srcs (the fragment is served from a different path than the page was authored at).
Component System
Components are automatically inlined during compilation with full support for props and slots:
<!-- Source: components/card.html -->
<div class="card">
<h2>@[title]</h2>
<p>@[description]</p>
<slot></slot>
</div>
<!-- Usage in page -->
<component src="/components/card.html" title="My Card" description="Card description">
<p>Slot content</p>
</component>
<!-- Compiled output -->
<component>
<div class="card">
<h2>My Card</h2>
<p>Card description</p>
<p>Slot content</p>
</div>
</component>Custom element syntax: Components can also use custom element syntax (e.g., <card> → auto-converts to <component src="/components/card.html">).
Opt-out: Set componentsAsIs: true to keep components as separate files for runtime loading.
Iteration Optimization
The compiler generates optimized batch functions for <!-- each --> loops, providing 2-3x faster rendering:
<!-- Source -->
<!-- each items as item, index -->
<li>@[index]: @[item]</li>
<!-- /each -->
<!-- Compiled to optimized batch function -->Opt-out: Set iterationsAsIs: true to use runtime rendering for all iterations.
Pre-rendered Global State (write state the way the compiler expects)
To eliminate the flash of raw @[...] markers, the compiler bakes any global $
value it can prove is constant straight into the pre-rendered HTML. BETA v@[version]
ships as BETA v0.1.5. Everything else stays a live binding the runtime fills on
hydration.
A global key is baked only when both hold:
- It's a primitive —
string/number/boolean/null. Objects and arrays are never baked (their contents can be mutated through a reference the compiler can't follow), so an@[config.theme]binding always stays live. - It's never reassigned anywhere the compiler scans (every
.jsmodule, inline<script>, andon*handler undersource, minusskipFiles). Any$.key = …,$.key += …,$.key++,delete $.key, or$['key'] = …marks it dynamic.
This is why how you write a mutation matters — write global state through a
direct member assignment on $:
$.coins = gameState.coins; // ✅ seen → `coins` stays a live bindingIf you mutate global state by a path static analysis can't follow, the compiler won't see the write and may bake a stale initial value:
const s = $; s.coins = 5; // ⚠️ aliasing $ — disables baking for ALL keys (safe, but loses the optimization)
applyState($, patch); // ⚠️ if applyState does `arg.coins = …`, that write is INVISIBLE → `coins` may wrongly bakePassing $ as a read-only argument (derive($, opts)) is fine; only writing through
the alias is the problem. Reach for $.key = … and the classifier stays correct.
The baked value comes from your vibe({ ... }) initial state, resolved statically
(including default imports, e.g. version: VERSION → version.js's export default).
If the initial value is a runtime call (settings: loadLocalStorage(...)), it simply
isn't baked — the binding stays live, which is harmless.
Iterations follow the same rule. An <!-- each --> over a global/dynamic array is
rendered empty in the compiled HTML (the raw @[item.x] template body is dropped,
not painted), and the runtime restores it from the manifest once the array has data.
Don't rely on a loop's template body existing in the DOM before hydration.
Still use vibe-fouc. Baking removes raw markers for constant values, but
session/runtime state (auth, server data, anything you reassign) can't be pre-rendered
— keep the vibe-fouc guard so that state doesn't flash either.
Output Structure
Mirrors source structure:
src/ compiled/
├── pages/ ├── pages/
│ └── index.html │ └── index.html
├── components/ │ (components inlined)
│ └── counter.html
├── assets/ ├── assets/
│ └── image.png │ └── image.png
└── node_modules/ └── node_modules/
└── @ape-egg/ └── @ape-egg/
└── vibe/ └── vibe/Element Transformation
By default (elementsAsIs: false), custom HTML elements are transformed to divs with classes for better HTML validity:
<!-- input -->
<counter-header>Count</counter-header>
<!-- output -->
<div class="counter-header">Count</div>Set elementsAsIs: true or use --elements-as-is flag to keep custom elements unchanged.
Note: The <component> element is a framework element and is never transformed.
Reserved Element Names
The compiler validates component filenames against reserved element names (all HTML5 elements + "component" + your custom list). This prevents confusing bugs where components share names with HTML elements.
{
"vibe-compiler": {
"reservedElements": ["my-custom-element", "another-reserved-name"]
}
}Case-sensitive validation: nav.html conflicts with <nav> and will error, but Nav.html is allowed.
Building Native Binaries
For distribution without Rust:
cd node_modules/@ape-egg/vibe/compiler/src
# Build for current platform
cargo build --release
# Copy binary to native directory
cp target/release/vibe-compiler ../native/vibe-compiler-darwin-arm64Supported platforms:
vibe-compiler-darwin-arm64(macOS Apple Silicon) ✅ Includedvibe-compiler-darwin-x64(macOS Intel)vibe-compiler-linux-x64vibe-compiler-linux-arm64vibe-compiler-win32-x64.exe
The CLI wrapper automatically falls back to cargo run when native binaries aren't present.
Browser Support
Modern browsers with Proxy and MutationObserver support.
License
ISC
Future improvements to refactor
Dependency tracking uses string matching, not AST
affected() determines which bindings to re-hydrate by string-matching expression text against state key names. When matching fails, a safety fallback marks the binding as affected on every state change.
runtime/affected.js:15—matchesKeydoes exact/prefix match, then word-boundary searchruntime/affected.js:~122—shouldAffect = noMatch || ...fallback for unmatched expressionsruntime/affected.js:~248— same fallback for name bindings
As of 3.0.0 this is solved — not by static extraction (which lies for helper calls) but by the subscription engine: every binding records the state keys it actually reads during evaluation, live at the proxy's get trap, so a write notifies exactly its subscribers. Update cost is O(change), and it costs zero authoring syntax.
HTML lowercases attribute names — breaks name binding matching
The browser lowercases all attribute names during HTML parsing. <page @[pageName]> becomes @[pagename] in the DOM. Every value hydrated into an attribute NAME position loses its case. @[myCoolPage] → DOM stores @[mycoolpage], causing comparison mismatches against camelCase state keys.
Handled today by case-insensitive fallbacks in three places:
runtime/hydrate.js:~32— case-insensitive state key lookup when evaluating name bindings (clone path)runtime/affected.js:~235— case-insensitivematchesKeywrapper for name bindingsruntime/iterate.js— case-insensitive lookup againststateKeysinsidecompileBatchFn's name-binding emission (batch path)
All three are workarounds for HTML's behavior. A cleaner architecture would centralize the case-insensitive state key resolution into one helper, or normalize the name binding expression to canonical state-key case at first evaluation and cache it on the tree node.
Related: value hydration into attribute values is case-preserving
Only attribute NAMES are lowercased by HTML, not values. So title="@[pageName]" and @[pageName] in text content preserve case and work without fallbacks — the issue is specific to name bindings.
