aktion-runtime 0.5.1 → 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 -373
  2. package/dist/aktion.iife.js +798 -790
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +10059 -7997
  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 +60 -7
  23. package/dist/types/runtime/builtins.d.ts +10 -6
  24. package/dist/types/runtime/effects.d.ts +5 -30
  25. package/dist/types/runtime/evaluator.d.ts +356 -25
  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
@@ -1,40 +1,31 @@
1
1
  /**
2
- * Aktion 0.5 i18n runtime — `$i18n` declaration + `t()` global builtin (§23).
2
+ * Aktion i18n factory — `i18n({...})` returns a `{ t, setCurrentLanguage,
3
+ * getCurrentLanguage }` bundle with language state held in closure.
3
4
  *
4
- * The runtime is intentionally tiny:
5
- * - Holds the active locale, fallback locale, and message map.
6
- * - `t(key, vars?)` looks up `key` (dot-paths supported, e.g. `"orders.title"`),
7
- * falls back to the fallback locale's bundle, then to the bare key.
8
- * - `vars?` are interpolated using `${name}` placeholders.
5
+ * const { t, setCurrentLanguage, getCurrentLanguage } = i18n({
6
+ * defaultLanguage: "en",
7
+ * currentLanguage: "fr",
8
+ * translations: {
9
+ * greeting: { en: "Hello, {name}!", fr: "Bonjour, {name}!" },
10
+ * items_count: { en: "{count} items", fr: "{count} objets" },
11
+ * },
12
+ * })
9
13
  *
10
- * Locale-aware formatting (`Money`, `Date`, `Number`, `Percent`,
11
- * `RelativeTime`) is wired through `getLocale()` so library components
12
- * can read the live value without each declaring it as a prop.
14
+ * t("greeting", { name: "Ada" }) // "Bonjour, Ada!"
15
+ * setCurrentLanguage("en")
16
+ * t("greeting", { name: "Ada" }) // "Hello, Ada!"
17
+ *
18
+ * Placeholders use `{name}` syntax. Lookup falls back to
19
+ * `defaultLanguage`, then to the bare key.
13
20
  */
14
21
  export interface I18nConfig {
15
- locale: string;
16
- messages: Record<string, unknown>;
17
- fallback?: string;
18
- /** Optional secondary message map for the fallback locale. */
19
- fallbackMessages?: Record<string, unknown>;
22
+ defaultLanguage?: string;
23
+ currentLanguage?: string;
24
+ translations?: Record<string, Record<string, string>>;
20
25
  }
21
- export declare class I18nRuntime {
22
- private locale;
23
- private fallback;
24
- private messages;
25
- private fallbackMessages;
26
- configure(config: I18nConfig): void;
27
- /** Current active locale tag (e.g. `"en-US"`, `"de"`). */
28
- getLocale(): string;
29
- /** Snapshot of the configured fallback locale. */
30
- getFallback(): string;
31
- /**
32
- * Translate a dot-pathed key, optionally interpolating `${name}` vars.
33
- *
34
- * Resolution order:
35
- * 1. The active locale's message map.
36
- * 2. The fallback locale's message map (if provided separately).
37
- * 3. The bare key as a literal string.
38
- */
26
+ export interface I18nInstance {
39
27
  t(key: string, vars?: Record<string, unknown>): string;
28
+ setCurrentLanguage(lang: string): void;
29
+ getCurrentLanguage(): string;
40
30
  }
31
+ export declare function createI18n(config?: I18nConfig): I18nInstance;
@@ -2,11 +2,10 @@
2
2
  * Hash-based router for `<aktion-app>`.
3
3
  *
4
4
  * The router is owned by the host element and exposed to:
5
- * - The evaluator (which special-cases `Routes(...)` to pick the matching
6
- * `Route(path, content)` and inject path params as the loop variable
7
- * `params`).
5
+ * - The evaluator (which special-cases `Router({...})` to pick the matching
6
+ * route arm and inject path params as the `params` scope).
8
7
  * - The renderer's helpers (so `NavLink(...)` can wire click handlers).
9
- * - The action runner (`@Navigate("/path")` step).
8
+ * - Action functions (via `route.navigate("/path")`).
10
9
  *
11
10
  * The wire format is hash-based — `#/page-name`. The router strips the leading
12
11
  * `#` and any trailing `?…` query string before exposing the path. Navigating
@@ -85,10 +84,10 @@ export declare class Router {
85
84
  stop(): void;
86
85
  getPath(): string;
87
86
  getParams(): RouteParams;
88
- /** Path pattern of the most recently matched `Route` (or null). */
87
+ /** Path pattern of the most recently matched route arm (or null). */
89
88
  getActivePattern(): string | null;
90
89
  /**
91
- * Called by `Routes(...)` after each render so we have the canonical
90
+ * Called by `Router({...})` after each render so we have the canonical
92
91
  * pattern + params for the active page (used by `NavLink` to highlight the
93
92
  * active link). The state store is NOT touched here.
94
93
  */
@@ -7,41 +7,97 @@
7
7
  * which keeps the surface small and predictable.
8
8
  */
9
9
  export type StateValue = unknown;
10
- export type Subscriber = (changedNames: ReadonlySet<string>) => void;
11
10
  /**
12
- * Pluggable persistent storage adapter for `$$variable` declarations.
11
+ * Subscribers receive the set of **changed paths** since the last flush, not
12
+ * just atom names. A whole-atom write (`set("user", …)`) reports the root
13
+ * path `"user"`; a nested write (`setPath("user", ["name"], …)`) reports the
14
+ * precise path `"user.name"`. Consumers decide whether a change is relevant
15
+ * to them with `pathAffects` / `anyPathAffects` (the prefix-overlap rule),
16
+ * which is what gives Aktion fine-grained reactivity: a dependency on
17
+ * `user.name` ignores a `user.role` write but still wakes for a `user`
18
+ * (ancestor) replacement.
19
+ */
20
+ export type Subscriber = (changedPaths: ReadonlySet<string>) => void;
21
+ /**
22
+ * Join an atom name and a nested path into the canonical dotted dependency
23
+ * key (`"user"`, `"user.name"`, `"cart.items.0.qty"`).
24
+ */
25
+ export declare function joinStatePath(rootName: string, path: ReadonlyArray<string>): string;
26
+ /**
27
+ * The core fine-grained-reactivity predicate: does a change to path
28
+ * `changed` affect a dependency on path `dep`?
13
29
  *
14
- * The default implementation reads/writes JSON-encoded values to the host
15
- * page's `localStorage`. Hosts (or tests) can swap it out via
16
- * `StateStore.setPersistenceAdapter(...)` — useful for SSR shims or to
17
- * scope storage per-element via a custom key prefix.
30
+ * True when the two paths lie on the same root-to-leaf line — i.e. they are
31
+ * equal, `changed` is an ancestor of `dep` (the whole subtree the dep lives
32
+ * in was replaced), or `dep` is an ancestor of `changed` (a field inside the
33
+ * value the dep reads changed). Sibling paths (`user.name` vs `user.role`)
34
+ * never affect each other. Boundaries are matched at dot separators so
35
+ * `user` does not spuriously match `username`.
18
36
  */
19
- export interface PersistenceAdapter {
20
- load(name: string): StateValue | undefined;
21
- save(name: string, value: StateValue): void;
22
- remove(name: string): void;
23
- }
37
+ export declare function pathAffects(changed: string, dep: string): boolean;
38
+ /** True when any path in `changed` affects the single dependency `dep`. */
39
+ export declare function anyPathAffects(changed: ReadonlySet<string>, dep: string): boolean;
40
+ /** True when any path in `changed` affects any dependency in `deps`. */
41
+ export declare function pathsOverlap(changed: ReadonlySet<string>, deps: Iterable<string>): boolean;
24
42
  export declare class StateStore {
25
43
  private values;
26
44
  private defaults;
27
- /** Persistent variable names — written to the adapter on every change. */
28
- private persistent;
29
- private persistenceAdapter;
30
45
  private subscribers;
31
46
  private pendingChanges;
32
47
  private flushScheduled;
33
- setPersistenceAdapter(adapter: PersistenceAdapter | null): void;
34
- declare(name: string, defaultValue: StateValue): void;
35
48
  /**
36
- * Declare a persistent `$$variable`. The adapter is queried for an
37
- * existing value; if one is found, it replaces the default. Otherwise
38
- * the default is written back so the next mount reads the seeded value.
49
+ * True while the host is evaluating a render. Writes that land in this
50
+ * window still update the value, but are NOT broadcast as changes — so a
51
+ * `$x = …` assignment running in render position can't schedule a re-render
52
+ * that re-runs the same write and loops forever. Writing reactive state
53
+ * during render is an anti-pattern (React/Vue/Solid all guard against it);
54
+ * we degrade gracefully instead of freezing the tab.
39
55
  */
40
- declarePersistent(name: string, defaultValue: StateValue): void;
41
- isPersistent(name: string): boolean;
56
+ private rendering;
57
+ /** Set when a write was suppressed during the render pass (for diagnostics). */
58
+ private renderWriteOccurred;
59
+ declare(name: string, defaultValue: StateValue): void;
42
60
  has(name: string): boolean;
43
61
  get(name: string): StateValue;
44
62
  set(name: string, value: StateValue): void;
63
+ /**
64
+ * Record a changed path and schedule a flush — unless a render is in
65
+ * progress, in which case the value is kept but no notification fires.
66
+ * This is the loop-breaker for state writes during render.
67
+ */
68
+ private enqueueChange;
69
+ /**
70
+ * Open a render guard. Writes between this and `endRenderPass` update
71
+ * values without scheduling re-renders. Returns nothing; pair with
72
+ * `endRenderPass` in a `finally`.
73
+ */
74
+ beginRenderPass(): void;
75
+ /**
76
+ * Whether a render is currently in progress. Used by the evaluator to give
77
+ * a function body's top-level `$x = expr` *set-once* (declaration)
78
+ * semantics while rendering — so a function used to build the UI seeds its
79
+ * state once and preserves later mutations, regardless of name case.
80
+ */
81
+ isRendering(): boolean;
82
+ /**
83
+ * Close the render guard. Returns `true` when at least one write was
84
+ * suppressed during the pass, so the host can surface a one-time warning
85
+ * pointing at the "state write during render" anti-pattern.
86
+ */
87
+ endRenderPass(): boolean;
88
+ /**
89
+ * Write `value` to a nested path inside the atom named `rootName`,
90
+ * producing a *new* root object so the standard identity-based change
91
+ * detection fires. Used by deep-binding sites such as
92
+ * `Checkbox(value: $form.done)` and lambda assignments like
93
+ * `() => $form.done = true`. Empty paths fall back to `set`.
94
+ *
95
+ * Objects along the path are reconstructed immutably (`{...prev, key: …}`)
96
+ * — sibling keys are preserved and downstream subscribers always see a
97
+ * fresh top-level reference. Numeric segments target array indices and
98
+ * preserve the surrounding array shape.
99
+ */
100
+ setPath(rootName: string, path: ReadonlyArray<string>, value: StateValue): void;
45
101
  /** Iterate over every (name, value) pair. Order is insertion order. */
46
102
  entries(): IterableIterator<[string, StateValue]>;
47
103
  /** Snapshot every (name, value) pair into a plain object. */
@@ -53,10 +109,6 @@ export declare class StateStore {
53
109
  * URL-backed deep links, conversational continuity). Atoms that have
54
110
  * not yet been `declare`d are still written so they show up the
55
111
  * moment the program declares them.
56
- *
57
- * The persistence adapter is *not* consulted — hydration is
58
- * authoritative. If the caller wants persisted reads to win, they
59
- * should call `hydrate(snapshot)` before `declare(name, …)`.
60
112
  */
61
113
  hydrate(snapshot: Readonly<Record<string, StateValue>>): void;
62
114
  reset(...names: string[]): void;
@@ -74,11 +126,3 @@ export declare class StateStore {
74
126
  private scheduleFlush;
75
127
  private flush;
76
128
  }
77
- /**
78
- * Build a `PersistenceAdapter` backed by `window.localStorage` (or
79
- * `sessionStorage`). The returned adapter namespaces each key by
80
- * `keyPrefix` so two elements on the same page don't clobber one
81
- * another's `$$variable` values. Returns `null` when no storage is
82
- * available (SSR, sandboxed iframes, private mode in some browsers).
83
- */
84
- export declare function createLocalStorageAdapter(keyPrefix: string, storage: Storage | null): PersistenceAdapter | null;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * `Util` — global helper namespace exposed to Aktion programs.
3
+ *
4
+ * These are pure data transformations available everywhere as
5
+ * `Util.<method>(...)`. They replace the former `@-builtin` catalog
6
+ * (`@Count`, `@Filter`, `@Format`, …) which was removed.
7
+ *
8
+ * The namespace is intentionally open: add methods here and they
9
+ * become available to authors without any other wiring. Pair with
10
+ * documentation in `src/prompt/generator.ts` so the LLM-facing prompt
11
+ * teaches the new entry.
12
+ */
13
+ /**
14
+ * Pure helpers exposed to programs as the `Util` namespace.
15
+ *
16
+ * All methods are side-effect-free and safe inside reactive expressions.
17
+ * Authors typically reach for one of two styles:
18
+ *
19
+ * total = Util.sum($cart.price)
20
+ * text = Util.plural(items.length, "item")
21
+ *
22
+ * Comparators for `filter` / `find` accept the operator strings
23
+ * `"=="`, `"!="`, `">"`, `"<"`, `">="`, `"<="`, `"contains"`.
24
+ */
25
+ export declare const Util: {
26
+ readonly count: (arr: unknown) => number;
27
+ readonly sum: (arr: unknown) => number;
28
+ readonly avg: (arr: unknown) => number;
29
+ readonly min: (arr: unknown) => number;
30
+ readonly max: (arr: unknown) => number;
31
+ readonly first: (arr: unknown) => unknown;
32
+ readonly last: (arr: unknown) => unknown;
33
+ readonly filter: (arr: unknown, field?: string, op?: string, value?: unknown) => unknown[];
34
+ readonly find: (arr: unknown, field?: string, op?: string, value?: unknown) => unknown;
35
+ readonly sort: (arr: unknown, field?: string, direction?: "asc" | "desc") => unknown[];
36
+ readonly groupBy: (arr: unknown, field?: string) => Record<string, unknown[]>;
37
+ readonly slice: (arr: unknown, start?: number, end?: number) => unknown[];
38
+ readonly unique: (arr: unknown, field?: string) => unknown[];
39
+ readonly reverse: (arr: unknown) => unknown[];
40
+ readonly range: (start: number, end: number, step?: number) => number[];
41
+ readonly repeat: <T>(value: T, n: number) => T[];
42
+ readonly pick: (obj: unknown, keys: unknown) => Record<string, unknown>;
43
+ /**
44
+ * Locale-aware number formatter. Modes: `"number"` (default),
45
+ * `"currency"`, `"percent"`, `"compact"`. Options object:
46
+ * `{ currency?, locale?, decimals? }`. Legacy positional form
47
+ * `Util.format(v, "currency", "USD", "en-US")` is also accepted.
48
+ */
49
+ readonly format: (value: unknown, mode?: string, options?: unknown, fourth?: unknown) => string;
50
+ /**
51
+ * Format a date. Second argument is either a moment-like pattern
52
+ * (`"MMM D"`, `"YYYY-MM-DD"`) or one of: `"relative"`, `"date"`,
53
+ * `"time"`, `"datetime"`, `"iso"`.
54
+ */
55
+ readonly formatDate: (value: unknown, format?: string) => string;
56
+ readonly plural: (count: unknown, singular: unknown, plural?: unknown) => string;
57
+ readonly capitalize: (text: unknown) => string;
58
+ readonly lowercase: (text: unknown) => string;
59
+ readonly uppercase: (text: unknown) => string;
60
+ readonly titlecase: (text: unknown) => string;
61
+ readonly case: (text: unknown, kind?: "camel" | "snake" | "kebab" | "pascal") => string;
62
+ readonly now: () => number;
63
+ readonly today: () => string;
64
+ readonly addDays: (date: unknown, days: unknown) => string;
65
+ readonly addHours: (date: unknown, hours: unknown) => string;
66
+ readonly diffDays: (start: unknown, end: unknown) => number;
67
+ readonly startOfWeek: (date: unknown) => string;
68
+ readonly endOfMonth: (date: unknown) => string;
69
+ readonly join: (arr: unknown, sep?: string) => string;
70
+ readonly split: (text: unknown, sep?: string) => string[];
71
+ readonly trim: (text: unknown) => string;
72
+ readonly replace: (text: unknown, search: unknown, replacement?: unknown) => string;
73
+ readonly substring: (text: unknown, start: unknown, end?: unknown) => string;
74
+ readonly startsWith: (text: unknown, prefix: unknown) => boolean;
75
+ readonly endsWith: (text: unknown, suffix: unknown) => boolean;
76
+ readonly contains: (text: unknown, needle: unknown) => boolean;
77
+ readonly match: (text: unknown, pattern: unknown) => boolean;
78
+ readonly round: (value: unknown, decimals?: number) => number;
79
+ readonly floor: (value: unknown) => number;
80
+ readonly ceil: (value: unknown) => number;
81
+ readonly abs: (value: unknown) => number;
82
+ readonly clamp: (value: unknown, min: unknown, max: unknown) => number;
83
+ readonly pow: (base: unknown, exp: unknown) => number;
84
+ readonly sqrt: (value: unknown) => number;
85
+ readonly random: () => number;
86
+ readonly log: (value: unknown) => number;
87
+ };
88
+ export type UtilNamespace = typeof Util;