aktion-runtime 0.5.2 → 0.5.3

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 (35) hide show
  1. package/README.md +654 -376
  2. package/dist/aktion.iife.js +798 -790
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +10046 -8011
  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/system_prompt.txt +595 -829
  9. package/dist/system_prompt_chat.txt +98 -263
  10. package/dist/types/element.d.ts +46 -26
  11. package/dist/types/language/grammar.d.ts +25 -9
  12. package/dist/types/language/index.d.ts +8 -6
  13. package/dist/types/library/components/content.d.ts +0 -1
  14. package/dist/types/library/components/escape-hatch.d.ts +3 -0
  15. package/dist/types/library/components/layout.d.ts +3 -0
  16. package/dist/types/library/components/wrappers.d.ts +12 -0
  17. package/dist/types/library/utils.d.ts +42 -0
  18. package/dist/types/parser/frontier.d.ts +3 -3
  19. package/dist/types/parser/lexer.d.ts +7 -17
  20. package/dist/types/parser/types.d.ts +239 -113
  21. package/dist/types/prompt/generator.d.ts +0 -11
  22. package/dist/types/renderer/renderer.d.ts +53 -4
  23. package/dist/types/runtime/builtins.d.ts +10 -6
  24. package/dist/types/runtime/effects.d.ts +3 -28
  25. package/dist/types/runtime/evaluator.d.ts +333 -24
  26. package/dist/types/runtime/http.d.ts +35 -30
  27. package/dist/types/runtime/i18n.d.ts +23 -32
  28. package/dist/types/runtime/router.d.ts +5 -6
  29. package/dist/types/runtime/state.d.ts +77 -33
  30. package/dist/types/runtime/util.d.ts +88 -0
  31. package/dist/types/theme/styles.d.ts +1 -1
  32. package/dist/types/tooling/delta.d.ts +1 -1
  33. package/dist/types/tooling/inspector.d.ts +1 -1
  34. package/package.json +2 -2
  35. package/dist/types/language/builtins.d.ts +0 -33
@@ -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;
@@ -6,6 +6,8 @@ export interface HttpRequest {
6
6
  headers: Record<string, string>;
7
7
  body?: unknown;
8
8
  signal?: AbortSignal;
9
+ /** Extra `fetch`-compatible options passed through verbatim. */
10
+ init?: Record<string, unknown>;
9
11
  }
10
12
  export interface HttpResponse {
11
13
  status: number;
@@ -17,20 +19,10 @@ export interface HttpInterceptors {
17
19
  onResponse?: (response: HttpResponse, retry: () => Promise<HttpResponse>) => HttpResponse | Promise<HttpResponse>;
18
20
  onError?: (error: unknown, request: HttpRequest) => void;
19
21
  }
20
- export interface HttpDefaults {
21
- baseUrl?: string;
22
- headers?: Record<string, string>;
23
- timeoutMs?: number;
24
- retry?: {
25
- count: number;
26
- backoff?: "linear" | "exponential";
27
- };
28
- credentials?: RequestCredentials;
29
- }
30
- /** Reactive lifecycle of an `http({...})` resource. */
22
+ /** Reactive lifecycle of an `Http({...})` resource. */
31
23
  export type ResourceState = "idle" | "loading" | "data" | "error" | "stale";
32
24
  /**
33
- * Reactive bag returned by `http({...})`. Fields update in place as
25
+ * Reactive bag returned by `Http({...})`. Fields update in place as
34
26
  * the request progresses; the runtime calls `notify()` so the next
35
27
  * render observes the new values.
36
28
  */
@@ -44,28 +36,36 @@ export interface EndpointResource {
44
36
  lastUpdated?: number;
45
37
  refetch: () => Promise<void>;
46
38
  cancel: () => void;
39
+ /**
40
+ * Optional completion callback. Fires once each time a request settles
41
+ * (success *or* error) — the initial load and every `refetch()`. It does
42
+ * NOT fire when a request is superseded or `cancel()`led. Authors assign
43
+ * it after creation:
44
+ *
45
+ * $patch = Http({ url, method: "PATCH", body })
46
+ * $patch.onDone = () => { $todos.refetch() }
47
+ *
48
+ * The resource bag itself is passed as the sole argument so the callback
49
+ * can branch on `res.error` / `res.data` without closing over `$patch`.
50
+ */
51
+ onDone?: (resource: EndpointResource) => void;
47
52
  }
48
- /** Compatibility shim — subscription transports were removed in this version. */
49
- export interface SubscriptionTransport {
50
- open(url: string, opts: {
51
- protocol?: string;
52
- headers?: Record<string, string>;
53
- }): {
54
- onMessage(cb: (raw: unknown) => void): void;
55
- onError(cb: (err: unknown) => void): void;
56
- onClose(cb: () => void): void;
57
- onOpen(cb: () => void): void;
58
- send(payload: unknown): void;
59
- close(): void;
60
- };
61
- }
53
+ /** `true` when `value` is a live `Http({...})` resource bag. Used by the
54
+ * evaluator to mutate property writes in place rather than cloning, which
55
+ * would detach the running request's async continuations from the value
56
+ * the program reads.
57
+ */
58
+ export declare function isEndpointResource(value: unknown): value is EndpointResource;
62
59
  export declare class HttpRuntime {
63
60
  private interceptors;
64
- private defaults;
65
- setDefaults(defaults: HttpDefaults): void;
66
61
  /** Merge new interceptors on top of any previously-registered ones. */
67
62
  registerInterceptors(interceptors: HttpInterceptors): void;
68
- /** Resolve a relative URL against the configured `baseUrl`. */
63
+ /**
64
+ * Resolve a URL. Currently a pass-through — every `Http({ url })` call
65
+ * is expected to supply an absolute URL. Kept as a hook so request
66
+ * interceptors can rely on a stable shape if URL rewriting is added
67
+ * later.
68
+ */
69
69
  resolveUrl(url: string): string;
70
70
  /**
71
71
  * Issue a single HTTP request. Runs through `onRequest`/`onResponse`
@@ -75,11 +75,16 @@ export declare class HttpRuntime {
75
75
  request(input: HttpRequest): Promise<HttpResponse>;
76
76
  }
77
77
  /**
78
- * Run a single `http({...})` call and return the reactive resource bag.
78
+ * Run a single `Http({...})` call and return the reactive resource bag.
79
79
  *
80
80
  * The bag mutates in place: `data`, `error`, `status`, `loading`,
81
81
  * `headers`, `lastUpdated` update during the request lifecycle. The
82
82
  * `refetch()` callback re-issues the original request; `cancel()`
83
83
  * aborts the in-flight request (no-op when idle).
84
+ *
85
+ * A monotonic `generation` token guards every async continuation so a
86
+ * superseded request (because `refetch()` or `cancel()` ran while it
87
+ * was in flight) can never clobber the resource with stale data. This
88
+ * is what makes back-to-back refetches and cancels deterministic.
84
89
  */
85
90
  export declare function createHttpResource(config: unknown, ctx: EvaluationContext): EndpointResource;