# Aster 1.2.3
When writing Aster components, NEVER use React hooks. Keep local state in a generator, receive fresh props with for (props of ctx), and delegate interactive steps with yield*. DOM event handlers schedule a refresh. External subscriptions can call ctx.refresh() and use ctx.onCleanup() to unsubscribe.
Aster is a browser-native UI framework. Write a function for a view derived from props, a synchronous generator for interactive local state, and a finite async generator for loading and resolved views. Use JSX with the Aster Vite plugin or tagged HTML in JavaScript.
This handbook contains the complete application guides followed by the API reference. For design history, see the [architecture decisions](https://github.com/fierstdev/aster/blob/v1.2.3/docs/README.md).
# 01. Getting Started with Aster (Vite+)
Aster pairs a browser-native generator runtime with Vite+ for development, testing, type checking and production builds. Use Node 20.19 or later for the package. The repository uses the version listed in `.node-version`.
---
## 1. Install Vite+ (`vp`)
If you don't already have Vite+ installed globally:
```bash
# macOS / Linux
curl -fsSL https://vite.plus | bash
# Windows (PowerShell)
irm https://vite.plus/ps1 | iex
```
---
## 2. Scaffold a New App in 30 Seconds
```bash
vp dlx @fierst/aster my-app
cd my-app
vp install
vp dev
```
_(From inside the Aster repo itself, you can also run `node bin/create.mjs my-app`.)_
The CLI names are `aster` and `create-aster`. The default target is `my-aster-app`. Use an empty directory. The optional `--force` flag overwrites matching starter files in an existing directory. Scaffolding copies files and leaves dependency installation to you.
Open the URL printed by `vp dev`. Edit `src/main.tsx`, then click the button from `src/counter.tsx` to see local state persist. To add an optional AsterUI button, run `npm run ui -- add button`, install the dependencies printed by the CLI and import `Button` from `./ui/button`. Run `vp build` to create the static client site in `dist/` and `vp preview` to try it locally. Configure your static host to serve `index.html` for client routes.
---
## 3. Run the Framework Playground & Tests
From the `aster` repository root:
```bash
vp install # Install repository dependencies
vp dev # Launches the interactive playground at http://localhost:5173/
vp dlx playwright install chromium # One-time setup for Browser Mode tests
vp test # Runs both Node unit tests and real-Chromium Browser Mode tests
vp check # Runs Oxfmt + Oxlint + TypeScript 7 type checking in one pass
vp pack # Builds publishable ESM + .d.ts bundles into dist/
```
---
## 4. Use Aster in Any Vite+ App
Install `@fierst/aster` in the app (for example, `npm install @fierst/aster`). Add `aster()` from `@fierst/aster/vite` to your `vite.config.ts`:
```ts
import { defineConfig } from 'vite-plus';
import aster from '@fierst/aster/vite';
export default defineConfig({
plugins: [aster()],
});
```
Set `"jsx": "react-jsx"` and `"jsxImportSource": "@fierst/aster"` in `tsconfig.json`, and write standard `.tsx` components:
```tsx
import { render } from '@fierst/aster';
export function* Counter() {
let count = 0;
for (;;) {
yield ;
}
}
render(, document.getElementById('app')!);
```
The Vite plugin parses JSX and TSX with **Oxc** before Vite strips TypeScript. Aster lowers JSX into hoisted template slots, maps expressions back to their original positions, and stamps exported generator components for lazy revival. The Astro integration uses the same compiler.
---
## 5. Universal Edge SSR (`workerd` or Any Fetch Server)
Use a TSX server entry in a Fetch-based host. Build and serve the client assets first, then import that build's manifest in your server bundle.
```tsx
import manifest from '../dist/aster-manifest.json' with { type: 'json' };
import { htmlResponse } from '@fierst/aster/ssr';
import { App } from './app.tsx';
export default {
fetch(req: Request) {
const url = new URL(req.url);
return htmlResponse(, {
title: 'My App',
revive: true,
manifest,
});
},
};
```
For a split client/server build, keep browser-safe components in shared modules. Import the island modules from the client entry (a side-effect import such as `import './Counter.tsx'` lets the plugin discover its exports). Run `vp build` for the client, then `vp build --ssr src/server.tsx --outDir dist-server` for a server entry at that path. Resolve the manifest import relative to the entry file, for example `../dist/aster-manifest.json` from `src/server.tsx`. Serve the contents of `dist/` at the configured public base. Route document requests to your Fetch handler and asset requests to the client files. The handler above is a Fetch-host module, so a Node HTTP server needs its own Request/Response adapter.
# 02. Components, Local State, and Signals
Aster has a two-sentence state rule:
> **Use plain `let` inside `function*` for local component state. Use `signal()` only when sharing state across components.**
---
## 1. Stateless Components (`function`)
If a component only transforms props into markup, write an ordinary JavaScript function. It allocates zero generator frames and compiles straight to a static `` slot patch:
```tsx
export function Badge({ text, tone = 'neutral' }: { text: string; tone?: string }) {
return {text};
}
```
---
## 2. Stateful Components (`function*`)
Add `*` to turn any function into a stateful component. Everything **before** `for (props of ctx)` runs once; everything **inside** runs on each update:
```tsx
import { type Ctx } from '@fierst/aster';
export function* Counter(
props: { start?: number; label?: string },
ctx: Ctx<{ start?: number; label?: string }>,
) {
// Setup (runs once)
let count = props.start ?? 0;
try {
// Render loop (runs on every event, prop change, or shared signal update)
for (props of ctx) {
const doubled = count * 2; // Always fresh — no computed() needed!
if (count < 0) {
yield
Count went negative!
;
continue;
}
yield (
);
}
} finally {
// Teardown (runs automatically when unmounted via gen.return())
console.log('Counter unmounted');
}
}
```
### Why There Is No Stale-Closure or Thunk Tax
- **No `()` or `.value`:** `count` is a native `number`.
- **No `() =>` thunks:** `disabled={!draft.trim()}` is evaluated directly on each yield, and the slot runtime diffs only the flat array of dynamic values.
- **No `` or ``:** Plain `if / else` and `items.map((item) => )` work natively.
- **No manual `ctx.refresh()` for child callbacks:** Any `on*` function prop passed to a child component is automatically wrapped with the parent's microtask scheduler.
---
## 3. Two-Way Form Bindings (`bind:*`)
`@fierst/aster/vite` (`src/compiler.ts`) lowers `bind:value={draft}`, `bind:checked={task.done}`, and `bind:open={isOpen}` into getter/setter tuples automatically:
```tsx
export function* SearchBox() {
let query = '';
for (;;) {
yield (
);
}
}
```
---
Use a mutable local, a writable property, a signal held in a `const` or import, or an explicit `[get, set]` pair. For example, `const query = signal('')` works with `bind:value={query}`. Calling `query()` there supplies only its current value. Both compilers flag a known scalar at its JSX source location. A factory returning a binding is checked during server rendering or when the control mounts.
DOM handlers and custom binding setters can throw or return a rejecting promise. Aster forwards that failure to the nearest error boundary around the component that rendered the listener, or logs the event or binding name when there is no boundary. Return or await asynchronous callbacks to keep their errors in the event chain.
Use `on:keydown={event => event.key === 'Escape' && event.currentTarget.blur()}` for a native keyboard event. TypeScript infers both the event and the element. For application-defined events, augment the DOM interface `GlobalEventHandlersEventMap` with the event name and its `CustomEvent` type to infer `event.detail` in JSX.
## 4. Shared Cross-Component State (`signal()`)
When multiple components (including Web Components) need to stay in sync, create a `signal()` in a shared module. Reading `step()` inside any `function*` automatically subscribes that generator:
```tsx
import { signal } from '@fierst/aster';
export const step = signal(1);
export function* StepDisplay() {
for (;;) {
// Automatically wakes up whenever step.set(...) is called anywhere
yield Current step: +{step()};
}
}
```
---
## 5. Async Components (`async function*`)
Use `async function*` to express loading states and sequential fetches as straight-line code. Every component receives `ctx.signal` (`AbortSignal`), which aborts immediately on unmount:
```tsx
export async function* UserProfile(props: { id: string }, ctx: Ctx) {
yield
Loading user #{props.id}…
;
const res = await fetch(`/api/users/${props.id}`, { signal: ctx.signal });
const user = await res.json();
yield (
{user.name}
{user.bio}
);
}
```
---
## 6. Spread Props, Style Objects, and JSX Comments
Standard JSX ergonomics work identically on components and intrinsic HTML elements:
```tsx
export function ActionButton({ label, ...rest }: { label: string; [key: string]: any }) {
return (
);
}
```
---
## 7. Tree-Scoped Context (`createContext`, `provide`, `useContext`, ``)
Use module-level `signal()` for client-wide state, and **tree-scoped Context** when passing data down a subtree or rendering concurrently on the server (so SSR requests never leak state across users):
```tsx
import { createContext, provide, useContext, Provider } from '@fierst/aster';
export const UserCtx = createContext<{ name: string } | null>(null);
export function Greeting() {
const user = useContext(UserCtx);
return
Hello, {user ? user.name : 'Guest'}
;
}
export function App({ user }: { user: { name: string } }) {
// Option A: imperative inside a parent component
provide(UserCtx, user);
return ;
// Option B: declarative wrapper
// return ;
}
```
### Automatic `async function*` Prop Restarts
Aster compares each prop with `Object.is`. Changing `id` in `` aborts the previous execution and starts a new one. Pass `ctx.signal` to the pending operation so it can settle and let the old generator reach its `finally` block.
Function props participate in this comparison. If a parent passes `load={loadProfile}`, replacing the loader restarts the child. Declare callbacks before the parent generator's render loop when they should keep the same identity across updates. An inline arrow inside the loop creates a fresh function on every render.
In lesson 7 on `/learn`, change a request while it is waiting, then leave a delegated confirmation. The execution trace shows the abort and the order of the two `finally` blocks.
# 03. Composable UI Flows with `yield*`
In traditional frameworks, interactive sub-flows—confirmation dialogs, multi-step onboarding wizards, inline editors, or step-up authentication—force you to scatter boolean flags (`isConfirmOpen`, `pendingId`, `stepIndex`) and callback props across your component.
Because Aster components are native JavaScript generators, **`yield*` lets a sub-generator temporarily take over rendering and return a strongly typed value directly to its caller**—with 0 bytes of extra framework code.
---
## Example 1: Confirmation Dialog Returning `boolean`
```tsx
function* confirmDelete(title: string) {
let choice: boolean | null = null;
while (choice === null) {
yield (
Delete {title}?
);
}
return choice;
}
export function* TaskRow(
props: { task: Task; onDelete: (id: string) => void },
ctx: Ctx,
) {
let asking = false;
for (props of ctx) {
if (asking) {
// Hands UI control to confirmDelete(); resumes right here with true or false!
const confirmed = yield* confirmDelete(props.task.title);
asking = false;
if (confirmed) {
props.onDelete(props.task.id);
return;
}
}
yield (
;
}
```
### Automatic Teardown Propagation
If `CheckoutFlow` unmounts while the user is halfway through `PaymentStep`, Aster calls `gen.return()` on the outer generator. JavaScript automatically propagates that termination into `PaymentStep`'s `finally` block so timers, listeners, or locks are cleaned up cleanly.
## Choosing who advances a workflow
A synchronous component advances once per scheduled update. While `yield*` is active, the delegated generator receives the value passed to `.next()`. A prop update can advance the current step. Arguments captured when the step began retain their values. Key the workflow by record ID when switching records should discard an outstanding confirmation.
An async generator advances again as soon as its previous yield resolves. Use it for finite sequences such as loading, awaiting a request, and displaying a result. Keep click-driven loops in synchronous generators. In an async generator a loop that repeatedly yields while waiting for a click can prevent the browser from dispatching that click.
Exceptions thrown inside a delegated step propagate to the caller's `try/catch`. Unmount calls `.return()` on the outer generator and runs active nested `finally` blocks from the inside out. Use `ctx.signal` for work that supports cancellation and `ctx.refresh()` to request a render after other asynchronous work finishes.
The [profile editor](https://github.com/fierstdev/aster/blob/main/playground/profile-editor.tsx) in the playground showcase demonstrates editing, confirmation with a native dialog, Escape, focus restoration, and retry after a failed save. Its confirmation returns a boolean inferred by TypeScript.
### Moving focus after a yield
Pass the component context into a delegated step to open a dialog once its controls and listeners are ready.
```tsx
function* confirm(ctx: Ctx) {
let accepted: boolean | undefined;
while (accepted === undefined) {
yield (
);
}
return accepted;
}
```
`ctx.afterRender(callback)` runs once, in registration order, immediately after **this component's** next successful DOM patch. This includes mounting, updates, async yields, and claiming server HTML. Refs point to their elements and synchronous children have mounted by then. The container can be detached, and browser paint and pending async children have their own timing.
Registration alone does not schedule a render. A callback registered inside another callback waits for the next patch. Unmount, replacement of the generator execution, or a failed render discards pending work. Server rendering skips these callbacks. A thrown error or a returned promise rejection goes to the component's error boundary while the execution is active.
# 04. Unified Web Components & Native Styling
Aster eliminates the split between "framework component" and "Web Component." You write **one** `function*` component and register it with `defineElement()` whenever you want to expose it as a standard HTML Custom Element.
---
## 1. Write Once, Mount Anywhere
```tsx
import { defineElement, css, type Ctx } from '@fierst/aster';
export function* Counter(
props: { start?: number; label?: string },
ctx: Ctx<{ start?: number; label?: string }>,
) {
let count = props.start ?? 0;
for (props of ctx) {
yield (
);
}
}
defineElement('aster-counter', Counter, {
props: { start: 'number', label: 'string' },
shadow: true,
styles: css`
button {
padding: 0.5rem 1rem;
border-radius: 999px;
background: #0071e3;
color: white;
border: none;
cursor: pointer;
}
`,
});
```
### What `defineElement()` Handles Automatically
- **Typed Attribute Coercion:** Declaring `{ start: 'number', open: 'boolean', config: 'json' }` parses HTML string attributes before passing them into `Counter`—your component never writes `Number(props.start)`.
- **JS Property Sync:** Setting `el.label = 'Score'` in JavaScript or `el.setAttribute('label', 'Score')` in HTML both push fresh props into `for (props of ctx)`.
- **Automatic Cleanup:** `disconnectedCallback()` calls `gen.return()` and aborts `ctx.signal`, executing your component's `try / finally` block cleanly.
- **Shared Signals Work Across Shadow Boundaries:** If `Counter` reads a shared `signal()`, updating that signal wakes up both `` and `` simultaneously.
---
## 2. Styling: `@scope` vs. Shadow DOM
- **Light DOM (`scope`):** Ideal for app-level UI where global typography and CSS custom properties (`--surface`, `--text`) should cascade naturally while preventing component classes from leaking out.
```tsx
import { scope } from '@fierst/aster';
const cardClass = scope`
:scope { padding: 1.25rem; border-radius: 14px; border: 1px solid var(--border); }
h3 { margin: 0 0 0.5rem; }
`;
export function Card({ title, children }: any) {
return (
{title}
{children}
);
}
```
- **Shadow DOM (`css` or CSS Module Scripts):** Ideal for portable Web Components (`defineElement(..., { shadow: true, styles })`) where strict style encapsulation is desired.
# 05. Routing, Automatic Lazy Revival, and Error Boundaries
## 1. Browser-Native Routing (Zero `` Wrapper)
`src/router.ts` uses the native **Navigation API** (`window.navigation`), **`URLPattern`**, and **`document.startViewTransition()`**—automatically falling back to the History API in browsers that don't yet support Navigation API.
Just write standard HTML `` tags:
```tsx
import { Router, useParams, type RouteDef } from '@fierst/aster/router';
function Home() {
return