aktion-runtime 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +773 -376
  2. package/dist/aktion.iife.js +798 -790
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +10238 -8024
  5. package/dist/aktion.js.map +1 -1
  6. package/dist/aktion.umd.cjs +798 -790
  7. package/dist/aktion.umd.cjs.map +1 -1
  8. package/dist/node/compile-BUw0GAvN.cjs +491 -0
  9. package/dist/node/compile-BUw0GAvN.cjs.map +1 -0
  10. package/dist/node/compile-DxttTzo8.js +492 -0
  11. package/dist/node/compile-DxttTzo8.js.map +1 -0
  12. package/dist/node/compiler.cjs +11 -0
  13. package/dist/node/compiler.cjs.map +1 -0
  14. package/dist/node/compiler.js +11 -0
  15. package/dist/node/compiler.js.map +1 -0
  16. package/dist/node/index-8OvnOYPI.js +14070 -0
  17. package/dist/node/index-8OvnOYPI.js.map +1 -0
  18. package/dist/node/index-DBgA3bHQ.cjs +14069 -0
  19. package/dist/node/index-DBgA3bHQ.cjs.map +1 -0
  20. package/dist/node/language.cjs +1244 -0
  21. package/dist/node/language.cjs.map +1 -0
  22. package/dist/node/language.js +1244 -0
  23. package/dist/node/language.js.map +1 -0
  24. package/dist/node/vite.cjs +65 -0
  25. package/dist/node/vite.cjs.map +1 -0
  26. package/dist/node/vite.js +65 -0
  27. package/dist/node/vite.js.map +1 -0
  28. package/dist/system_prompt.txt +595 -829
  29. package/dist/system_prompt_chat.txt +98 -263
  30. package/dist/types/aktion-modules.d.ts +22 -0
  31. package/dist/types/compiler/compile.d.ts +54 -0
  32. package/dist/types/compiler/emit.d.ts +15 -0
  33. package/dist/types/compiler/index.d.ts +14 -0
  34. package/dist/types/compiler/linker.d.ts +27 -0
  35. package/dist/types/compiler/runtime.d.ts +63 -0
  36. package/dist/types/compiler/sourcemap.d.ts +40 -0
  37. package/dist/types/element.d.ts +82 -26
  38. package/dist/types/index.d.ts +1 -0
  39. package/dist/types/language/grammar.d.ts +25 -9
  40. package/dist/types/language/index.d.ts +8 -6
  41. package/dist/types/language-api.d.ts +15 -0
  42. package/dist/types/library/components/content.d.ts +0 -1
  43. package/dist/types/library/components/escape-hatch.d.ts +3 -0
  44. package/dist/types/library/components/layout.d.ts +3 -0
  45. package/dist/types/library/components/wrappers.d.ts +12 -0
  46. package/dist/types/library/utils.d.ts +42 -0
  47. package/dist/types/parser/frontier.d.ts +3 -3
  48. package/dist/types/parser/lexer.d.ts +7 -17
  49. package/dist/types/parser/types.d.ts +276 -113
  50. package/dist/types/plugin/index.d.ts +10 -0
  51. package/dist/types/plugin/vite.d.ts +21 -0
  52. package/dist/types/prompt/generator.d.ts +0 -11
  53. package/dist/types/renderer/renderer.d.ts +53 -4
  54. package/dist/types/runtime/builtins.d.ts +10 -6
  55. package/dist/types/runtime/effects.d.ts +3 -28
  56. package/dist/types/runtime/evaluator.d.ts +333 -24
  57. package/dist/types/runtime/http.d.ts +35 -30
  58. package/dist/types/runtime/i18n.d.ts +23 -32
  59. package/dist/types/runtime/router.d.ts +5 -6
  60. package/dist/types/runtime/state.d.ts +77 -33
  61. package/dist/types/runtime/util.d.ts +88 -0
  62. package/dist/types/theme/styles.d.ts +1 -1
  63. package/dist/types/tooling/delta.d.ts +1 -1
  64. package/dist/types/tooling/inspector.d.ts +1 -1
  65. package/package.json +37 -6
  66. package/dist/types/language/builtins.d.ts +0 -33
@@ -19,7 +19,7 @@ export interface RenderOptions {
19
19
  */
20
20
  evaluationContext?: () => EvaluationContext;
21
21
  /**
22
- * Mount `effect [ ...deps ] { … }` declarations discovered inside a
22
+ * Mount `effect(() => { … }, [deps])` declarations discovered inside a
23
23
  * `component { … }` body. Called by the renderer after every render of
24
24
  * the instance; the implementation is expected to be idempotent so
25
25
  * re-renders are no-ops once the effects are mounted. The host wires
@@ -37,6 +37,14 @@ export interface RenderOptions {
37
37
  * (between two `beginRender`/`endRender` passes).
38
38
  */
39
39
  unmountInstanceEffects?: (instanceKey: string) => void;
40
+ /**
41
+ * Drop the per-instance hook cells (`$state` / `$memo`) held under
42
+ * `instanceKey`. Invoked when a component that used hooks disappears from
43
+ * the render tree, giving React-like reset-on-unmount: a future remount
44
+ * starts its `$state` from the initial value again. The host wires this to
45
+ * `clearInstanceHooks(ctx, key)`.
46
+ */
47
+ unmountInstanceHooks?: (instanceKey: string) => void;
40
48
  }
41
49
  export declare class Renderer {
42
50
  private options;
@@ -62,6 +70,30 @@ export declare class Renderer {
62
70
  * GC even when an instance never registered `useInstanceState`.
63
71
  */
64
72
  private readonly instancesWithEffects;
73
+ /**
74
+ * User-declared component instances that currently hold per-instance hook
75
+ * cells (`$state` / `$memo`). Tracked so the renderer can fire
76
+ * `unmountInstanceHooks` when the instance leaves the tree.
77
+ */
78
+ private readonly instancesWithHooks;
79
+ /**
80
+ * Per-instance render memo (React.memo / Solid-style granularity). Keyed by
81
+ * instance path; holds the args + the `$state` paths the body read + the
82
+ * body's last return value. On a re-render where the change paths are fully
83
+ * known, an instance whose args are unchanged AND whose read-paths don't
84
+ * overlap the change set reuses its cached value — its body (and its
85
+ * `console.log`s / work) is skipped. Reusing the *value* (not the DOM) means
86
+ * children are still visited and re-checked against their own memo, so a
87
+ * descendant that reads a changed path still re-renders. GC'd in `endRender`.
88
+ */
89
+ private readonly memoCache;
90
+ /**
91
+ * Paths changed since the last render (set by the host before `render`).
92
+ * Drives memoization. `null`/empty + `memoEnabled=false` ⇒ full re-render.
93
+ */
94
+ private changedPaths;
95
+ /** Whether memoization may apply this render (false on mount / replan / notify). */
96
+ private memoEnabled;
65
97
  constructor(options: RenderOptions);
66
98
  /**
67
99
  * Swap the component library backing this renderer. Used when the host
@@ -75,18 +107,35 @@ export declare class Renderer {
75
107
  * is `clear()`ed so a fresh program starts with a clean slate.
76
108
  */
77
109
  reset(): void;
78
- /** Begin a fresh render pass; tracks which instances are still alive. */
79
- beginRender(): void;
110
+ /**
111
+ * Begin a fresh render pass; tracks which instances are still alive.
112
+ *
113
+ * `changedPaths` is the set of `$state` paths that changed since the last
114
+ * render and `memoize` says whether per-component memoization may apply
115
+ * (false on first paint, replan, or a `notify()`-driven render where the
116
+ * change set isn't fully known — those re-render everything).
117
+ */
118
+ beginRender(opts?: {
119
+ changedPaths?: ReadonlySet<string>;
120
+ memoize?: boolean;
121
+ }): void;
80
122
  /**
81
123
  * End the current render pass. Drops instance state for components that
82
124
  * disappeared from the tree so the map doesn't grow unbounded.
83
125
  */
84
126
  endRender(): void;
85
127
  private safeDispose;
128
+ /**
129
+ * Apply a state write addressed by either a plain atom name
130
+ * (`$count` → `"count"`) or a dotted path (`$form.email` →
131
+ * `"form.email"`). Dotted writes go through `state.setPath` so the
132
+ * root object is reconstructed immutably and subscribers wake up.
133
+ */
134
+ private writeState;
86
135
  render(value: unknown): Node;
87
136
  private renderAt;
88
137
  /**
89
- * Expand a user-declared `component Foo(p) { ... }` invocation. Each
138
+ * Expand a user-declared `function Foo(p) { return ... }` invocation. Each
90
139
  * instance gets a stable instance key derived from its render path (or
91
140
  * the caller's explicit `key:` override); the evaluator then evaluates
92
141
  * the component's body with a fresh per-instance state-alias scope so
@@ -1,13 +1,17 @@
1
1
  /**
2
- * Built-in `@Name(...)` functions for Aktion.
2
+ * Theme marker for the runtime.
3
3
  *
4
- * These are pure data transformations. The legacy action-step builtins
5
- * (`@Run`, `@Set`, `@Reset`, `@ToAssistant`, `@OpenUrl`, `@Navigate`,
6
- * `@Js`) and the `@Const` memo helper were removed. Use `action <Name>() {
7
- * … }` declarations + lambda handlers (`onClick: save`) instead, and just
8
- * `$name = expression` for plain reactive bindings.
4
+ * The former `@`-builtin catalog (`@Count`, `@Filter`, `@Format`, …)
5
+ * has been removed. Programs now reach for equivalent native
6
+ * JavaScript or the `Util` namespace (see `./util.ts`).
9
7
  */
10
8
  export type BuiltinFn = (args: unknown[]) => unknown;
9
+ /**
10
+ * Empty registry kept as a structural placeholder so the parser's
11
+ * synthetic `BuiltinCall` nodes (`__rui_assign__`, `__rui_postfix__`,
12
+ * `__rui_prefix__`, `__rui_await__`) flow through the evaluator without
13
+ * a surprise lookup.
14
+ */
11
15
  export declare const dataBuiltins: Record<string, BuiltinFn>;
12
16
  /**
13
17
  * Marker emitted by the `Theme({...})` construct. Carries an arbitrary token
@@ -5,17 +5,8 @@ export interface EffectRunnerOptions {
5
5
  state: StateStore;
6
6
  /** Called whenever an effect mutates state or completes — schedules render. */
7
7
  notify: () => void;
8
- /** Called when the action body emits a CustomEvent via `emit`. */
8
+ /** Called when the effect/action body emits a CustomEvent via `emit()`. */
9
9
  onEmit?: (eventName: string, detail: unknown) => void;
10
- /** Host element — exposed to `js{}` block bodies as `ctx.host`. */
11
- host?: HTMLElement;
12
- /**
13
- * Optional pluggable async tool registry — exposed to `js{}` blocks as
14
- * `ctx.tools.<name>(...)`. Each entry is invoked with whatever args the
15
- * JS body passes; the return value is awaited. Hosts can register fetch
16
- * shims, persistence helpers, etc.
17
- */
18
- tools?: Record<string, (...args: unknown[]) => unknown>;
19
10
  }
20
11
  export declare class EffectRunner {
21
12
  private readonly options;
@@ -30,12 +21,12 @@ export declare class EffectRunner {
30
21
  * alone, those that vanish from the new program are torn down.
31
22
  *
32
23
  * Only touches global (top-level) effects. Per-instance effects mounted
33
- * inside `component { … }` bodies are managed via `syncInstanceEffects`
24
+ * inside function bodies are managed via `syncInstanceEffects`
34
25
  * / `unmountInstance` and are not affected by this call.
35
26
  */
36
27
  syncEffects(decls: ReadonlyArray<EffectDeclaration>, getCtx: () => EvaluationContext): void;
37
28
  /**
38
- * Mount per-instance effects discovered inside a `component { … }` body.
29
+ * Mount per-instance effects discovered inside a function body.
39
30
  * Idempotent: re-rendering the same instance with the same effect set is
40
31
  * a no-op; effects that vanished from the body since the last render are
41
32
  * torn down. Effects belonging to other instances are untouched.
@@ -53,26 +44,11 @@ export declare class EffectRunner {
53
44
  private mount;
54
45
  private unmount;
55
46
  }
56
- interface JsBlockExecOptions {
57
- state: StateStore;
58
- host?: HTMLElement;
59
- tools?: Record<string, (...args: unknown[]) => unknown>;
60
- }
61
- /**
62
- * Build a standalone `js{ … }` runner closure for the renderer / inline
63
- * lambdas to invoke. Identical sandbox surface as the effect/action
64
- * runners (host, tools, state get/set, optional cleanup hook).
65
- */
66
- export declare function createInlineJsExecutor(options: JsBlockExecOptions): (body: string, args?: Record<string, unknown>) => unknown;
67
47
  export interface ActionRunnerOptions {
68
48
  state: StateStore;
69
49
  notify: () => void;
70
50
  onEmit?: (eventName: string, detail: unknown) => void;
71
51
  onAssistantMessage?: (message: string) => void;
72
- /** Host element exposed to `js{}` blocks as `ctx.host`. */
73
- host?: HTMLElement;
74
- /** Pluggable tool registry exposed to `js{}` blocks as `ctx.tools.<name>`. */
75
- tools?: Record<string, (...args: unknown[]) => unknown>;
76
52
  }
77
53
  /**
78
54
  * Run an `action` declaration. When the declaration is `optimistic` we
@@ -85,4 +61,3 @@ export declare class ActionDeclRunner {
85
61
  run(decl: ActionDeclaration, callArgs: unknown[], ctx: EvaluationContext): Promise<unknown>;
86
62
  private runStatement;
87
63
  }
88
- export {};
@@ -1,12 +1,93 @@
1
- import { Expression, Program, ComponentDeclaration, EffectDeclaration, ActionDeclaration } from '../parser/types.js';
1
+ import { Expression, Program, Statement, ComponentDeclaration, EffectDeclaration, ActionDeclaration, HookDeclaration, DestructuringPattern } from '../parser/types.js';
2
2
  import { StateStore } from './state.js';
3
3
  import { HttpRuntime } from './http.js';
4
- import { I18nRuntime } from './i18n.js';
5
4
  import { ActionDeclRunner } from './effects.js';
6
5
  import { Router } from './router.js';
7
6
  import { ComponentLibrary } from '../library/types.js';
7
+ /**
8
+ * Runtime safety budget — bounds the work a single render can perform
9
+ * so a partial / accidentally-recursive program (e.g. while the user is
10
+ * still typing in the playground) cannot freeze the browser or exhaust
11
+ * the heap.
12
+ *
13
+ * Three independent dimensions are tracked:
14
+ *
15
+ * - `componentDepth` — current user-component invocation depth.
16
+ * `function Foo() { return Foo() }` would otherwise recurse until the JS
17
+ * stack overflows; capping this at ~150 catches the typo in <1ms
18
+ * and surfaces a friendly error instead of a frozen tab.
19
+ * - `iterations` — cumulative count of loop body evaluations across
20
+ * every `for` loop in the current render. Bounded across the
21
+ * whole render (not per-loop) so a thousand tiny loops still get
22
+ * caught before they pile up into seconds of work.
23
+ * - `arrayLengthLimit` — pre-flight cap on `@Range` / `@Repeat`
24
+ * allocations. A bare `Util.range(0, 1e9)` would otherwise call
25
+ * `Array.push` a billion times and OOM the renderer process.
26
+ *
27
+ * Limits are deliberately generous (anything a real app needs fits
28
+ * easily) but tight enough to abort runaway evaluations in
29
+ * milliseconds. The host element resets the budget at the start of
30
+ * every render so each pass starts fresh.
31
+ */
32
+ export interface RuntimeBudget {
33
+ /** Max simultaneous depth of user-component invocations. */
34
+ componentDepthLimit: number;
35
+ /** Max total iterations executed across every loop in a single render. */
36
+ iterationLimit: number;
37
+ /** Max length of any array materialised by `@Range` / `@Repeat`. */
38
+ arrayLengthLimit: number;
39
+ /** Current depth — managed by enter/leave in `evaluateUserComponent`. */
40
+ componentDepth: number;
41
+ /** Iterations consumed so far in the current render. */
42
+ iterations: number;
43
+ }
44
+ /** Default limits — comfortable for real apps, fatal for runaway typos. */
45
+ export declare const DEFAULT_RUNTIME_BUDGET: Readonly<Omit<RuntimeBudget, "componentDepth" | "iterations">>;
46
+ /** Why the runtime aborted. Used by the host to render a friendly banner. */
47
+ export type RuntimeBudgetKind = "component-depth" | "iterations" | "array-length";
48
+ /**
49
+ * Thrown when the evaluator hits a runtime safety limit. Carries enough
50
+ * detail for the host to surface a parse-error-style message that
51
+ * points the user at the offending construct.
52
+ */
53
+ export declare class RuntimeBudgetError extends Error {
54
+ readonly kind: RuntimeBudgetKind;
55
+ readonly limit: number;
56
+ readonly source: string;
57
+ constructor(kind: RuntimeBudgetKind, limit: number, source: string);
58
+ }
59
+ /** Create a fresh budget with default (or overridden) limits. */
60
+ export declare function createRuntimeBudget(overrides?: Partial<Omit<RuntimeBudget, "componentDepth" | "iterations">>): RuntimeBudget;
61
+ /**
62
+ * Reset the per-render counters on an existing budget. Limits are
63
+ * preserved; only the running totals (`iterations`, `componentDepth`)
64
+ * are cleared. Called by the host between renders.
65
+ */
66
+ export declare function resetRuntimeBudget(budget: RuntimeBudget): void;
67
+ /**
68
+ * Open a user-component frame against the budget. The caller MUST pair
69
+ * every successful return with a `leaveUserComponent(ctx)` call (use
70
+ * `try { … } finally { leaveUserComponent(ctx) }`).
71
+ *
72
+ * Lives here rather than inside `evaluateUserComponent` because the
73
+ * renderer drives the recursive expansion of nested user components
74
+ * via `renderAt(value, …) → renderUserComponent(…) → evaluateUserComponent`.
75
+ * The depth bracket has to span that whole chain — including the
76
+ * `renderAt` call that recurses — so it can't sit inside
77
+ * `evaluateUserComponent`'s own try/finally (that frame is popped
78
+ * before the recursive call starts).
79
+ */
80
+ export declare function enterUserComponent(ctx: EvaluationContext, name: string): void;
81
+ /** Close a user-component frame previously opened by `enterUserComponent`. */
82
+ export declare function leaveUserComponent(ctx: EvaluationContext): void;
8
83
  export interface ArgMeta {
9
- /** Name of the `$variable` if this argument is a direct state reference. */
84
+ /**
85
+ * Name of the `$variable` (or dotted path inside one) carried by this
86
+ * argument. Direct refs (`value: $name`) store the bare atom name;
87
+ * member-access refs (`value: $form.email`, `value: $cart.items[0]`)
88
+ * store a dotted path (`"form.email"`, `"cart.items.0"`) so renderers
89
+ * can wire two-way binding into the right nested slot.
90
+ */
10
91
  stateRef?: string;
11
92
  }
12
93
  export interface ComponentNode {
@@ -32,7 +113,7 @@ export interface ComponentNode {
32
113
  }
33
114
  export declare const isComponentNode: (value: unknown) => value is ComponentNode;
34
115
  /**
35
- * Lazy node produced when a user-declared `component Foo(p) { ... }` is
116
+ * Lazy node produced when a user-declared `function Foo(p) { return ... }` is
36
117
  * called. The renderer expands these per-instance: each instance gets its
37
118
  * own state-alias scope so two `Counter()` calls hold independent `$state`
38
119
  * atoms (§7 — per-instance reactivity).
@@ -56,7 +137,27 @@ export interface UserComponentNode {
56
137
  }
57
138
  export declare const isUserComponentNode: (value: unknown) => value is UserComponentNode;
58
139
  /**
59
- * An `effect [ … ] { … }` declaration discovered inside a `component { … }`
140
+ * A global store created by `Store({ …state, …methods })` (§ Global state).
141
+ *
142
+ * State (the non-function entries of the config) lives in a single reactive
143
+ * atom named `__atom`, so reads through the handle (`store.field`) get the
144
+ * same fine-grained path tracking as a `$state` read, and writes
145
+ * (`s.field = …` inside a method) route through `setPath`. Methods (the
146
+ * function entries) are pre-bound so calling `store.method(args)` invokes the
147
+ * author's function with the handle injected as the first argument
148
+ * (`(s, ...args)`); the bound functions are reference-stable across renders,
149
+ * which keeps memoization tight when an action is passed as a prop.
150
+ */
151
+ export interface StoreHandle {
152
+ __kind: "Store";
153
+ /** Backing reactive atom name holding the store's state object. */
154
+ __atom: string;
155
+ /** Pre-bound methods: `(...args) => rawMethod(handle, ...args)`. */
156
+ __methods: Record<string, (...args: unknown[]) => unknown>;
157
+ }
158
+ export declare const isStoreHandle: (value: unknown) => value is StoreHandle;
159
+ /**
160
+ * An `effect(() => { … }, [deps])` declaration discovered inside a `function` component
60
161
  * body, paired with the per-instance state-alias stack captured at the
61
162
  * moment the body was walked. The runner restores those aliases before
62
163
  * running the body so `$count = …` lands on the same instance slot the
@@ -70,6 +171,56 @@ export interface ScopedEffectDecl {
70
171
  * declared at the program top level, where no per-instance frame applies.
71
172
  */
72
173
  capturedAliases: ReadonlyArray<ReadonlyMap<string, string>>;
174
+ /**
175
+ * Snapshot of `ctx.loopVars` at the moment the declaration was
176
+ * collected (component parameters, slots, and any outer `for`-loop
177
+ * variables in scope). Restored onto `ctx.loopVars` before the effect
178
+ * body runs so an effect declared inside
179
+ * `function Item(todo) { effect(() => { use(todo) }, [$x]) }` keeps seeing
180
+ * its `todo` parameter even after the body has returned and the
181
+ * runtime cleared the loop var. Without it `todo` resolves to
182
+ * `undefined` because the param binding only lives for the duration
183
+ * of `evaluateUserComponent`.
184
+ *
185
+ * Refreshed on every re-render via `EffectRunner.syncInstanceEffects`
186
+ * so the effect always observes the latest prop values rather than
187
+ * the ones captured at first mount.
188
+ */
189
+ capturedLoopVars: ReadonlyMap<string, unknown>;
190
+ }
191
+ /**
192
+ * One hook slot held by a component instance (§ Hooks). Slots are matched
193
+ * by call order across renders — the React "rules of hooks" model.
194
+ *
195
+ * - `state` cells back a `$state(initial)` call. The `value` is the live
196
+ * current state; the setter returned by the hook mutates it in place and
197
+ * calls `ctx.notify()` to schedule a re-render. The cell object identity
198
+ * is stable across renders, so a setter captured in an event handler from
199
+ * an earlier render still writes the slot the next render reads.
200
+ * - `memo` cells back a `$memo(fn, deps)` call. `value` is the last
201
+ * computed result; `deps` is the dependency array it was computed with
202
+ * (shallow-compared via `Object.is` to decide whether to recompute).
203
+ */
204
+ export type HookCell = {
205
+ kind: "state";
206
+ value: unknown;
207
+ } | {
208
+ kind: "memo";
209
+ deps: ReadonlyArray<unknown> | undefined;
210
+ value: unknown;
211
+ };
212
+ /**
213
+ * Active hook scope — the component instance currently rendering, plus a
214
+ * monotonically increasing slot cursor. Set by `evaluateUserComponent`
215
+ * around the body walk and shared by any `$hook()` calls (built-in or
216
+ * user-declared) encountered while walking, so a custom hook's internal
217
+ * `$state` / `$memo` allocate slots on the calling component (React's
218
+ * custom-hook model). `null` when no component is rendering.
219
+ */
220
+ export interface HookScope {
221
+ instanceKey: string;
222
+ /** Next slot index to hand out — advanced once per hook call. */
223
+ cursor: number;
73
224
  }
74
225
  export interface EvaluationContext {
75
226
  state: StateStore;
@@ -84,6 +235,18 @@ export interface EvaluationContext {
84
235
  * bindings, lambda parameters, and component declaration parameters.
85
236
  */
86
237
  loopVars: Map<string, unknown>;
238
+ /**
239
+ * Per-render slot store for top-level non-`$state` bindings
240
+ * (`let badges = []`, `i = 10`, …). Reads memoise their declared
241
+ * initialiser here on first access and writes (`badges = …`,
242
+ * `badges.push(…)` against the cached reference) land here too — so a
243
+ * single render observes ONE stable value/reference for each top-level
244
+ * variable instead of re-evaluating the initialiser on every read
245
+ * (which previously made `.push` mutations vanish and `[...x, y]`
246
+ * reassignments accumulate across renders). Reset at the start of
247
+ * every render pass via `resetMutableBindings`.
248
+ */
249
+ mutableBindings: Map<string, unknown>;
87
250
  /**
88
251
  * Per-instance state alias scope (§7). When a user-declared component
89
252
  * body declares `$state n = 0`, the renderer pushes an alias frame so
@@ -93,13 +256,13 @@ export interface EvaluationContext {
93
256
  * not overridden.
94
257
  */
95
258
  stateAliases: Array<Map<string, string>>;
96
- /** Optional router — exposed to the runtime for `_route_.path` / `params`. */
259
+ /** Optional router — exposed to the runtime for `route.path` / `params`. */
97
260
  router?: Router;
98
261
  /** Component library used to resolve trailing named-arg object literals. */
99
262
  library?: ComponentLibrary;
100
- /** Component declarations from the program (`component Foo() { ... }`). */
263
+ /** Component declarations (`function Foo() { return ... }` — PascalCase). */
101
264
  componentDecls: Map<string, ComponentDeclaration>;
102
- /** Effect declarations (`effect [ ...deps ] { ... }`), keyed by auto-generated name. */
265
+ /** Effect declarations (`effect(() => { ... }, [deps])`), keyed by auto-generated name. */
103
266
  effectDecls: Map<string, EffectDeclaration>;
104
267
  /**
105
268
  * Stack of per-component-invocation effect collection frames.
@@ -117,43 +280,118 @@ export interface EvaluationContext {
117
280
  * component body has returned and the alias frame has been popped.
118
281
  */
119
282
  componentEffectStack: ScopedEffectDecl[][];
120
- /** Action declarations (`action Foo() { ... }`). */
283
+ /** Action declarations (`function foo() { ... }` — camelCase). */
121
284
  actionDecls: Map<string, ActionDeclaration>;
122
- /** HTTP runtime (`http({...})` calls + interceptor configuration). */
285
+ /**
286
+ * Hook declarations (`function $useFoo() { ... }`), keyed by name WITHOUT
287
+ * the `$` sigil. Invoked as `$useFoo(...)`; the body runs inline in the
288
+ * caller's hook scope so its `$state` / `$memo` calls allocate slots on
289
+ * the rendering component instance.
290
+ */
291
+ hookDecls: Map<string, HookDeclaration>;
292
+ /**
293
+ * Active hook scope, or `null` when no user component is rendering. Set by
294
+ * `evaluateUserComponent` around the body walk and consumed by the
295
+ * `$state` / `$memo` built-ins (and any user `$hook()` they reach).
296
+ */
297
+ hookScope: HookScope | null;
298
+ /**
299
+ * Per-instance hook cells, keyed by the same `instanceKey` the renderer
300
+ * derives for per-instance `$state` / effects. Each entry is the ordered
301
+ * slot array for one component instance. Persists across renders so hook
302
+ * state survives a re-render; the renderer prunes an instance's entry when
303
+ * it leaves the tree (`clearInstanceHooks`), giving React-like reset-on-
304
+ * unmount semantics.
305
+ */
306
+ hookStore: Map<string, HookCell[]>;
307
+ /**
308
+ * Global stores created by `Store({...})`, keyed by source location so the
309
+ * same call site yields one singleton handle across renders (the store is
310
+ * app-global, not per-instance). Lives as long as the program; rebuilt on
311
+ * replan with a fresh context.
312
+ */
313
+ stores: Map<string, StoreHandle>;
314
+ /** HTTP runtime (`Http({...})` calls + interceptor configuration). */
123
315
  http?: HttpRuntime;
124
- /** Aktion 0.5 i18n runtime (`$i18n = i18n({...})` declaration + `t()` builtin). */
125
- i18n?: I18nRuntime;
126
- /** Aktion 0.5 action runner (`action Foo() optimistic { … }` invocations). */
316
+ /** Action runner for function declarations. */
127
317
  actionRunner?: ActionDeclRunner;
128
318
  /** Notify the host that something changed and a re-render is needed. */
129
319
  notify?: () => void;
320
+ /** Dispatch a custom event from an `emit("name", detail)` call. */
321
+ onEmit?: (eventName: string, detail: unknown) => void;
322
+ /**
323
+ * Cleanup callbacks attached to this context. Populated during
324
+ * `planProgram` for resources that outlive a single evaluation pass —
325
+ * notably the state-store subscription that re-derives computed
326
+ * `$state = expr` atoms when their dependencies change. The host
327
+ * (`element.replan()`) drains this array via `disposeContext` before
328
+ * creating a fresh context so subscribers don't leak across replans.
329
+ */
330
+ disposers: Array<() => void>;
331
+ /**
332
+ * Pending timer handles created by the language-level `setTimeout` /
333
+ * `setInterval` builtins. Tracked per context so every timer is cleared
334
+ * when the context is disposed (`disposeContext`), which the host runs
335
+ * before each replan and on disconnect — otherwise a `setInterval` from a
336
+ * previous program would keep firing against a stale scope forever.
337
+ * `clearTimeout` / `clearInterval` remove handles from these sets.
338
+ */
339
+ timers: {
340
+ timeouts: Set<ReturnType<typeof setTimeout>>;
341
+ intervals: Set<ReturnType<typeof setInterval>>;
342
+ };
130
343
  /**
131
- * Optional executor for raw `js{ … }` blocks encountered inside an
132
- * inline lambda. When set, evaluating a lambda whose body resolves to
133
- * a `JsBlock` payload will invoke this with the captured body so
134
- * `Button("Hi", action: () => { js{ alert("Hi") } })` actually runs
135
- * the script instead of returning the deferred payload.
344
+ * Runtime safety budget — bounds component recursion depth, loop
345
+ * iterations, and array allocations so a partial/recursive program
346
+ * (typed live in the playground, mid-stream LLM token, …) cannot
347
+ * freeze the browser. The host resets it between renders; tests
348
+ * inherit the defaults and never bother because realistic test
349
+ * programs are orders of magnitude under the limits. Set to
350
+ * `undefined` (via `createContext({ budget: null })`) to disable
351
+ * enforcement entirely — only do this in trusted offline pipelines.
136
352
  */
137
- jsBlockExecutor?: (body: string, args?: Record<string, unknown>) => unknown;
353
+ budget?: RuntimeBudget;
138
354
  }
139
355
  /**
140
356
  * Optional injectables for `createContext` — the host element passes its
141
- * runtime singletons (HTTP, i18n, action runner) so endpoint use sites and
357
+ * runtime singletons (HTTP, action runner) so endpoint use sites and
142
358
  * action calls can resolve against them.
143
359
  */
144
360
  export interface CreateContextOptions {
145
361
  router?: Router;
146
362
  library?: ComponentLibrary;
147
363
  http?: HttpRuntime;
148
- i18n?: I18nRuntime;
149
364
  actionRunner?: ActionDeclRunner;
150
365
  notify?: () => void;
151
- jsBlockExecutor?: (body: string, args?: Record<string, unknown>) => unknown;
366
+ onEmit?: (eventName: string, detail: unknown) => void;
367
+ /**
368
+ * Runtime safety budget for this context.
369
+ * - omitted (default): a fresh budget with `DEFAULT_RUNTIME_BUDGET` limits.
370
+ * - explicit `RuntimeBudget`: caller-supplied limits (e.g. higher caps for
371
+ * server-side batch renders that don't need browser-tab safety).
372
+ * - `null`: disable enforcement entirely.
373
+ */
374
+ budget?: RuntimeBudget | null;
152
375
  }
153
376
  /**
154
377
  * Build a top-level evaluation context for a freshly parsed program.
155
378
  */
156
379
  export declare function createContext(state: StateStore, options?: CreateContextOptions): EvaluationContext;
380
+ /**
381
+ * Drain every cleanup callback attached to `ctx.disposers`. Safe to call
382
+ * multiple times — each callback is invoked at most once even if it
383
+ * throws (the array is cleared up-front so a faulty disposer can't
384
+ * prevent siblings from running).
385
+ */
386
+ export declare function disposeContext(ctx: EvaluationContext): void;
387
+ /**
388
+ * Clear the per-render mutable-binding cache. Called by the host at the
389
+ * start of every render pass so top-level `let`/`var`/plain bindings are
390
+ * re-seeded from their initialisers each render (keeping derived values
391
+ * reactive) while remaining stable WITHIN a single render (so `.push`
392
+ * and `[...x, y]` mutations behave like ordinary JS module variables).
393
+ */
394
+ export declare function resetMutableBindings(ctx: EvaluationContext): void;
157
395
  /**
158
396
  * Resolve a `$name` reference through the active per-instance alias
159
397
  * stack. Returns the topmost binding or `name` itself when no alias is
@@ -161,17 +399,75 @@ export declare function createContext(state: StateStore, options?: CreateContext
161
399
  * the same way the evaluator resolves reads.
162
400
  */
163
401
  export declare function resolveStateAlias(ctx: EvaluationContext, name: string): string;
402
+ /**
403
+ * Walk a chain of `Member` expressions rooted at a `StateRef` and return
404
+ * the alias-resolved root atom name plus the trailing dotted path. Used
405
+ * by two-way-binding extraction (`value: $form.email`) and by the
406
+ * synthetic-assign runner (`() => $form.email = …`).
407
+ *
408
+ * Returns `null` for any expression whose root is not a `$variable`
409
+ * (e.g. `loopVar.field`, `someBinding.x`). Bracket-access segments are
410
+ * supported when the key is a literal — `$cart.items[0]` resolves to
411
+ * path `["items", "0"]`. Optional chaining (`?.`) is treated as a
412
+ * regular member step for binding purposes; the renderer's getter still
413
+ * short-circuits at runtime if the chain is null.
414
+ */
415
+ export declare function extractStatePath(expr: Expression, ctx: EvaluationContext): {
416
+ name: string;
417
+ path: string[];
418
+ } | null;
164
419
  /**
165
420
  * Plan a program: declare state variables, register HTTP endpoints, and
166
421
  * build lazy bindings for every assignment so forward references resolve.
167
422
  */
168
423
  export declare function planProgram(program: Program, ctx: EvaluationContext): void;
169
424
  export declare function evaluate(expr: Expression, ctx: EvaluationContext): unknown;
425
+ /**
426
+ * Control-flow signals threaded through `runStatement` / `evaluateBlock`
427
+ * so `break`, `continue`, and `return` in nested `for` / `while` /
428
+ * `if` bodies propagate up to the enclosing loop / function body.
429
+ *
430
+ * Thrown as a class so the existing try/finally restores still execute
431
+ * along the way; the loop / function runners catch the matching
432
+ * signal and either resume or exit.
433
+ */
434
+ export declare class BreakSignal {
435
+ readonly kind: "break";
436
+ }
437
+ export declare class ContinueSignal {
438
+ readonly kind: "continue";
439
+ }
440
+ export declare class ReturnSignal {
441
+ readonly value: unknown;
442
+ readonly kind: "return";
443
+ constructor(value: unknown);
444
+ }
445
+ /**
446
+ * Resolve a destructuring pattern (`{ a, b: c = 1, ...rest }` /
447
+ * `[x, , y, ...rest]`) against a source value into a flat list of
448
+ * `name → value` pairs. Shared by `let`-destructuring statements and
449
+ * destructured function / lambda parameters so both honour defaults,
450
+ * renames, holes, and rest the same way. Does NOT touch `loopVars` —
451
+ * the caller decides how to bind + restore.
452
+ */
453
+ export declare function resolvePatternBindings(pattern: DestructuringPattern, source: unknown, ctx: EvaluationContext): Array<{
454
+ name: string;
455
+ value: unknown;
456
+ }>;
457
+ /**
458
+ * Public entry point for the effect / action runners — they delegate
459
+ * control-flow statements (`if`, `for`, `while`, `switch`, `try`,
460
+ * `break`, `continue`, `throw`) to this helper so the same semantics
461
+ * apply everywhere. Returns nothing; `BreakSignal`, `ContinueSignal`,
462
+ * and `ReturnSignal` are thrown for the caller's loop / function frame
463
+ * to catch.
464
+ */
465
+ export declare function runControlFlowStatement(stmt: Statement, ctx: EvaluationContext): void;
170
466
  /**
171
467
  * Result of `evaluateUserComponent`. `value` is the body's last
172
468
  * expression value (a `ComponentNode`, another `UserComponentNode`, or a
173
469
  * primitive) that the renderer will materialise. `effects` is the list of
174
- * `effect [ ...deps ] { … }` declarations discovered inside the body
470
+ * `effect(() => { … }, [deps])` declarations discovered inside the body
175
471
  * (paired with the per-instance alias stack captured at walk time) —
176
472
  * the renderer hands them to the host's `EffectRunner` so they mount on
177
473
  * a per-instance scope and tear down when the instance unmounts.
@@ -179,6 +475,13 @@ export declare function evaluate(expr: Expression, ctx: EvaluationContext): unkn
179
475
  export interface EvaluatedUserComponent {
180
476
  value: unknown;
181
477
  effects: ReadonlyArray<ScopedEffectDecl>;
478
+ /**
479
+ * Number of hook slots (`$state` / `$memo` / user `$hook`) this instance
480
+ * consumed during the body walk. `0` when the component uses no hooks.
481
+ * The renderer uses a non-zero count to track the instance for hook
482
+ * teardown when it later leaves the tree (reset-on-unmount).
483
+ */
484
+ hooks: number;
182
485
  }
183
486
  /**
184
487
  * Evaluate a user-declared component body in a fresh per-instance scope.
@@ -191,7 +494,13 @@ export interface EvaluatedUserComponent {
191
494
  *
192
495
  * Returns the body's last-expression value (typically a `ComponentNode`
193
496
  * the renderer can hand to the library, or another `UserComponentNode`
194
- * to expand recursively) plus any `effect [ ...deps ] { … }` declarations
497
+ * to expand recursively) plus any `effect(() => { … }, [deps])` declarations
195
498
  * discovered inside the body that the renderer must mount per-instance.
196
499
  */
197
500
  export declare function evaluateUserComponent(node: UserComponentNode, ctx: EvaluationContext, instanceKey: string): EvaluatedUserComponent;
501
+ /**
502
+ * Drop every hook cell owned by `instanceKey`. Called by the renderer when a
503
+ * component instance leaves the tree so its `$state` resets to the initial
504
+ * value on a future remount (React-like reset-on-unmount).
505
+ */
506
+ export declare function clearInstanceHooks(ctx: EvaluationContext, instanceKey: string): void;