@native-sdk/cli 0.7.1 → 0.8.0
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.
- package/build/app.zig +273 -65
- package/build/ts_run.mjs +6 -8
- package/build.zig +341 -361
- package/native-sdk.d.ts +6 -3
- package/package.json +13 -11
- package/packages/core/compile-surface/core.ts +559 -0
- package/packages/core/package-lock.json +375 -12
- package/packages/core/package.json +9 -6
- package/packages/core/scripts/compiler_typecheck.mjs +58 -0
- package/packages/core/scripts/gen_case_tables.mjs +130 -0
- package/packages/core/scripts/gen_declarations.mjs +97 -0
- package/packages/core/scripts/run_external_core_compiler.mjs +108 -0
- package/packages/core/scripts/stage_external_core.mjs +148 -0
- package/packages/core/sdk/core.d.ts +363 -0
- package/packages/core/sdk/events.d.ts +65 -0
- package/packages/core/sdk/text.d.ts +51 -0
- package/packages/core/src/checker.ts +3 -3
- package/packages/core/src/cli.ts +40 -38
- package/packages/core/src/contract.ts +749 -0
- package/packages/core/src/devhost.ts +4 -3
- package/packages/core/src/diagnostics.ts +5 -7
- package/packages/core/src/{transpile.ts → frontend.ts} +38 -50
- package/packages/core/src/infer.ts +1 -1
- package/packages/core/src/typed_ast.ts +16 -15
- package/packages/core/src/wyhash.ts +79 -0
- package/skill-data/native-ui/SKILL.md +4 -2
- package/skill-data/ts-core/SKILL.md +29 -29
- package/src/platform/macos/appkit_host.m +51 -3
- package/src/platform/types.zig +4 -0
- package/src/platform/windows/gpu_surface_renderer.cpp +2280 -0
- package/src/platform/windows/gpu_surface_renderer.h +86 -0
- package/src/platform/windows/root.zig +298 -20
- package/src/platform/windows/webview2_host.cpp +343 -33
- package/src/primitives/canvas/code.zig +50 -0
- package/src/primitives/canvas/code_tests.zig +174 -1
- package/src/primitives/canvas/frame.zig +45 -1
- package/src/primitives/canvas/gpu.zig +6 -0
- package/src/primitives/canvas/render_tests.zig +93 -0
- package/src/primitives/canvas/root.zig +2 -0
- package/src/primitives/canvas/serialization.zig +150 -21
- package/src/primitives/canvas/themes/geist.zig +51 -5
- package/src/primitives/canvas/tokens.zig +33 -4
- package/src/primitives/canvas/ui.zig +52 -7
- package/src/primitives/canvas/ui_markup.zig +38 -1
- package/src/primitives/canvas/ui_markup_compiled.zig +28 -0
- package/src/primitives/canvas/ui_markup_contract.zig +9 -0
- package/src/primitives/canvas/ui_markup_view.zig +28 -0
- package/src/primitives/canvas/ui_markup_view_tests.zig +10 -2
- package/src/primitives/canvas/ui_schema.zig +5 -0
- package/src/primitives/canvas/ui_schema_tests.zig +4 -3
- package/src/primitives/canvas/ui_tests.zig +14 -0
- package/src/primitives/canvas/widget_builtin_tests.zig +513 -13
- package/src/primitives/canvas/widget_invalidation.zig +11 -1
- package/src/primitives/canvas/widget_layout.zig +260 -21
- package/src/primitives/canvas/widget_metrics.zig +45 -9
- package/src/primitives/canvas/widget_render.zig +220 -70
- package/src/primitives/canvas/widget_render_controls.zig +79 -21
- package/src/primitives/canvas/widget_render_style.zig +52 -8
- package/src/primitives/canvas/widget_text_input.zig +2 -0
- package/src/primitives/canvas/widgets.zig +53 -2
- package/src/runtime/canvas_frame.zig +60 -7
- package/src/runtime/canvas_frame_invalidation_tests.zig +80 -0
- package/src/runtime/canvas_frame_packet_tests.zig +83 -9
- package/src/runtime/canvas_frame_patch_tests.zig +16 -0
- package/src/runtime/canvas_images.zig +8 -2
- package/src/runtime/canvas_widget_clipboard_tests.zig +1 -1
- package/src/runtime/canvas_widget_runtime.zig +11 -8
- package/src/runtime/effects.zig +6 -0
- package/src/runtime/effects_tests.zig +30 -0
- package/src/runtime/gpu_surface_events.zig +38 -7
- package/src/runtime/media_surface_tests.zig +1 -1
- package/src/runtime/runtime_event_tests.zig +74 -0
- package/src/runtime/ts_core_host.zig +38 -38
- package/src/runtime/ts_ui_app.zig +12 -12
- package/src/runtime/ui_app.zig +10 -8
- package/src/runtime/ui_app_tests.zig +67 -0
- package/src/runtime/view.zig +6 -0
- package/src/runtime/view_canvas.zig +15 -0
- package/src/runtime/view_widget_text.zig +6 -4
- package/src/runtime/window_view_runtime.zig +1 -0
- package/src/tooling/manifest.zig +32 -0
- package/src/tooling/raw_manifest.zig +4 -0
- package/src/tooling/templates.zig +34 -26
- package/src/tooling/ts_core.zig +55 -34
- package/src/tooling/verbs.zig +1 -1
- package/tools/corewire/core_abi.zig +169 -0
- package/tools/corewire/emit.zig +2418 -0
- package/tools/corewire/emit_facade.zig +3984 -0
- package/tools/corewire/emit_profile.zig +501 -0
- package/tools/corewire/main.zig +561 -0
- package/tools/corewire/shim_rt.zig +632 -0
- package/tools/corewire/sidecar.zig +2507 -0
- package/packages/core/rt/rt.zig +0 -1986
- package/packages/core/src/emitter.ts +0 -11898
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: ts-core
|
|
3
|
-
description: Authoring guide for TypeScript app cores - Model, Msg, update, and the pure functions they call, written in the closed app-core subset and compiled ahead-of-time to
|
|
3
|
+
description: Authoring guide for TypeScript app cores - Model, Msg, update, and the pure functions they call, written in the closed app-core subset, checked by the @native-sdk/core frontend, and compiled ahead-of-time to native code by the external core compiler. Use when writing or modifying a src/core.ts app core, fixing subset checker errors (NS1001-NS1060), or deciding how to express state, messages, text (bytes and the byte-text string methods), text input, continuous controls (sliders, scroll), effects (Cmd), subscriptions (Sub), the host-event wiring channels (frameMsg, keyMsg, appearanceMsg, chromeMsg, envMsgs, app.zon assets), derived values, the view_unbound lint opt-out, local mutation of owned arrays, or how to split a core into modules under src/ (relative imports, namespace imports, @native-sdk/core/text, @native-sdk/core/events).
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Author app cores in the TypeScript subset
|
|
7
7
|
|
|
8
|
-
An app core is the logic tier of a Native SDK app: `Model` (the app state), `Msg` (a discriminated union of everything that can happen), `update(model, msg)` (the one pure transition function), and the pure helpers they call. You write it as a TypeScript module rooted at `src/core.ts` - splitting into more modules under `src/` when it grows (see "Splitting a core into modules") - and the `@native-sdk/core`
|
|
8
|
+
An app core is the logic tier of a Native SDK app: `Model` (the app state), `Msg` (a discriminated union of everything that can happen), `update(model, msg)` (the one pure transition function), and the pure helpers they call. You write it as a TypeScript module rooted at `src/core.ts` - splitting into more modules under `src/` when it grows (see "Splitting a core into modules") - and the build checks the whole import graph with the `@native-sdk/core` frontend and compiles it to native code with the external core compiler. No JS engine ships in the binary — the program either passes the subset checker and compiles to native, or you get a teaching error naming the rule, the fix, and the reason. The same file is executable TypeScript: it typechecks with stock tsc and runs unmodified under node, so you can poke behavior with plain node scripts before the native build.
|
|
9
9
|
|
|
10
|
-
A whole TS app is three files of truth and zero Zig: `src/core.ts` (this guide; plus any modules it imports under `src/`), `src/app.native` (the markup view over the core's
|
|
10
|
+
A whole TS app is three files of truth and zero Zig: `src/core.ts` (this guide; plus any modules it imports under `src/`), `src/app.native` (the markup view over the core's model), and `app.zon` (windows, identity, permissions). `native init` scaffolds exactly that; the build detects `src/core.ts` in the tree (never a flag or config — a tree with both `src/core.ts` and `src/main.zig` is a teaching error) and generates the wiring outside the app. The loop:
|
|
11
11
|
|
|
12
12
|
```sh
|
|
13
13
|
native dev --core # the fastest loop: run the core under node's virtual host —
|
|
@@ -42,7 +42,7 @@ export function update(model: Model, msg: Msg): Model {
|
|
|
42
42
|
```
|
|
43
43
|
|
|
44
44
|
- `update` is pure and synchronous: next model out, plus optionally command data describing effects. When a dispatch needs an effect, declare the return type `Model | [Model, Cmd<Msg>]` and return `[nextModel, cmd]` — the runtime interprets the command after the model commits and dispatches any result back to you as a `Msg`. `initialModel` may return the same pair (`[Model, Cmd<Msg>]`) to run a boot effect once at install, and an app that needs recurring timers exports `subscriptions(model): Sub<Msg>`. See "Effects are Cmd data" below.
|
|
45
|
-
- Exported helper functions (`export function doneCount(model: Model): number`) compile to public
|
|
45
|
+
- Exported helper functions (`export function doneCount(model: Model): number`) compile to public native functions — and every exported helper taking exactly ONE Model parameter also becomes a Model declaration markup binds by the helper's own name (`{doneCount}`), so derived values need no model field. One binding name per member: a helper that collides with a field (or another helper) is a taught NS1031.
|
|
46
46
|
- Update-only state (fields, helpers, or Msg kinds nothing in markup binds or dispatches — host-fired timer arms, persistence bookkeeping) is declared once: `export const viewUnbound = ["nextId", "tick"] as const;`. It emits as the `view_unbound` opt-out `native check`'s unbound-state lint reads; a name outside the model surface is a taught NS1032. Entries are the TypeScript names exactly as declared (`"nextId"`) and Msg kinds as their `kind` tags — the same names markup binds, because there are no other names.
|
|
47
47
|
- Names: your names are your names — fields, helpers, and locals emit into Zig with their TS spellings (`doneToday` stays `doneToday`), and markup binds them verbatim. String-literal unions emit as native enums.
|
|
48
48
|
|
|
@@ -52,11 +52,11 @@ Everything `update` builds lives in a per-dispatch bump arena that is freed whol
|
|
|
52
52
|
|
|
53
53
|
That is why the immutable style is not a performance tax: `{ ...model, tasks: model.tasks.map(...) }` copies one small struct and one pointer array, never the world.
|
|
54
54
|
|
|
55
|
-
Both regions
|
|
55
|
+
Both regions are the compiled core's own: the frame arena bounds one dispatch's transients, the model heap holds the committed model between dispatches, and the compiler's determinism fences keep every dispatch allocation-shaped and replayable.
|
|
56
56
|
|
|
57
57
|
## What the subset means
|
|
58
58
|
|
|
59
|
-
The subset is TypeScript minus the ecosystem minus the purity violations — never minus basic syntax. Concretely: every basic statement, operator, and declaration form of the language compiles (every loop shape including `do...while`, labels with labeled `break`/`continue`, `switch` with `default`, the full assignment-operator family, `**` and the shifts, const record destructuring, namespace imports over your own modules). What does not compile falls into exactly two families, each with a named teaching rule: the ECOSYSTEM the binary cannot carry (npm packages, Node/DOM APIs, regex/JSON/Promise/generator machinery, `eval` — no JS engine ships), and the constructs that would break a core's guarantees (purity and determinism, fixed shapes, one text representation, functions as declarations not values, static types with no runtime tags). Classes and exceptions are NOT in either family: data classes and `throw`/`try`/`catch`/`finally` compile (see below) — only their guarantee-breaking tails (inheritance, unsafe finally, untagged thrown values) teach. A construct that fails with a generic error instead of a teaching rule is a
|
|
59
|
+
The subset is TypeScript minus the ecosystem minus the purity violations — never minus basic syntax. Concretely: every basic statement, operator, and declaration form of the language compiles (every loop shape including `do...while`, labels with labeled `break`/`continue`, `switch` with `default`, the full assignment-operator family, `**` and the shifts, const record destructuring, namespace imports over your own modules). What does not compile falls into exactly two families, each with a named teaching rule: the ECOSYSTEM the binary cannot carry (npm packages, Node/DOM APIs, regex/JSON/Promise/generator machinery, `eval` — no JS engine ships), and the constructs that would break a core's guarantees (purity and determinism, fixed shapes, one text representation, functions as declarations not values, static types with no runtime tags). Classes and exceptions are NOT in either family: data classes and `throw`/`try`/`catch`/`finally` compile (see below) — only their guarantee-breaking tails (inheritance, unsafe finally, untagged thrown values) teach. A construct that fails with a generic error instead of a teaching rule is a checker bug — the grammar matrix test (`grammar_matrix.test.ts`) pins every grammar production to its verdict so no silent gap can appear.
|
|
60
60
|
|
|
61
61
|
The banned families at a glance (each diagnostic names the fix and the reason at the site):
|
|
62
62
|
|
|
@@ -73,13 +73,13 @@ Model and message shapes:
|
|
|
73
73
|
|
|
74
74
|
- `interface` with `readonly` fields; nested interfaces; `T | null` for optional data.
|
|
75
75
|
- Model field types: `number`, `boolean`, string-literal unions (`"all" | "active" | "done"` → native enum), numeric-literal unions, `Uint8Array` (bytes), a nested interface, `readonly Interface[]` (arrays of object types), primitive arrays (`readonly number[]`, `readonly boolean[]`, arrays of literal-union tags), a tag-discriminated union (`{ kind: "list" } | { kind: "detail"; note: Note }` — arms may carry records, bytes, and primitive arrays), and `T | null` over any of these. Model unions compile to native tagged unions; switching arms in `update` retires the old arm's payload automatically at commit.
|
|
76
|
-
- `Msg`: a discriminated union on a `readonly kind` string tag, with primitive / bytes / interface payload fields. It must be a real union — give it at least two arms, or TypeScript collapses the alias to a plain object type and the
|
|
76
|
+
- `Msg`: a discriminated union on a `readonly kind` string tag, with primitive / bytes / interface payload fields. It must be a real union — give it at least two arms, or TypeScript collapses the alias to a plain object type and the checker rejects it.
|
|
77
77
|
|
|
78
78
|
Logic:
|
|
79
79
|
|
|
80
80
|
- `switch` on any union's `kind` tag — `msg.kind` (the Msg dispatch) and model-field unions (`switch (model.view.kind)`) alike — with member case labels, label stacking (`case "a": case "b": body`), `break`, and a trailing `default` covering the unnamed arms (without a `default` the switch must be exhaustive — NS1015; with every arm named the `default` is JS dead code and emits nothing) — and `switch` on a string-literal-union or numeric-literal-union *value* (`switch (model.filter)`) — an uncovered member skips the switch exactly like JS (a `default` anywhere but last is a taught stop in both forms) — and `switch` on a plain `number` or `string` value, lowered to an if/else chain with exact JS semantics: strict equality per case (NaN matches nothing, `-0` matches `0`, strings compare contents), cases tested in source order, `default` matching only after every case misses wherever it sits (an empty `default:` stacking onto the next body included); `if`/`else`; classic `for (let i = 0; ...)` including countdowns (`i--`, `i -= k`), multi-counter inits (`let lo = 0, hi = n`), and comma incrementors (`lo++, hi--` — the for-header is the one home for comma sequences); `do { ... } while (cond)` (the body runs before the first test; `continue` jumps to the test, exactly node); `for (const x of xs)` over arrays and `Uint8Array`, with `break`/`continue`, plus the indexed pair form `for (const [i, x] of xs.entries())` (exactly the `[index, element]` two-identifier binding — the index is the loop index, integer-classed; other tuple shapes stay taught); `while`; labeled statements on loops and blocks with labeled `break`/`continue` (`outer: for (...) { ... continue outer; }` — a labeled `continue` in a classic for still runs the incrementor, like JS); `let` locals with reassignment (and `let x: number;` declared-then-assigned); ternaries; `&&`/`||`/`!`; the empty statement `;`.
|
|
81
81
|
- `const { total, done: doneCount } = stats;` — record-field destructuring into const locals (a compile-time alias per field, renames included). Array patterns, parameter patterns, defaults, rest, and nesting are taught (NS1045 — positions can be silently absent in JS; fields cannot).
|
|
82
|
-
- `import * as util from "./util.ts"` — a namespace import over your own modules is pure dot-syntax: `util.helper(x)`, `util.CONST`, and `util.Cfg` in type positions all resolve to the target module's flat
|
|
82
|
+
- `import * as util from "./util.ts"` — a namespace import over your own modules is pure dot-syntax: `util.helper(x)`, `util.CONST`, and `util.Cfg` in type positions all resolve to the target module's flat names. The alias is not a value (storing or passing `util` itself is taught), and the intrinsic `@native-sdk/core` module is always imported by name (NS1039 — the purity rules recognize `Cmd`/`Sub`/`asciiBytes` by their imported names).
|
|
83
83
|
- Object spread `{ ...model, field: v }`, array spreads in any shape — append `[...xs, x]`, prepend `[x, ...xs]`, multi-spread `[...a, x, ...b]` (each compiles to one exact-size copy) — `.length`, indexing `xs[i]`.
|
|
84
84
|
- Array methods, lowered to inlined loops and exact-size arena copies: `.map` / `.filter` / `.find` / `.findIndex` / `.some` / `.every` / `.reduce` / `.toSorted` / `.slice` / `.concat` / `.indexOf` / `.includes`. `.map` is type-changing — `tasks.map((t) => t.id)` produces a number array, `t => t.title` a bytes array, and a callback that can return `null` produces an optional-element array. Callbacks on map/filter/find/findIndex/some/every may take the `(element, index)` pair — the index is the loop index, integer-classed (`.reduce` stays `(acc, x)`: its index parameter is not in v1, and no callback takes the third JS parameter, the array itself — reference the array by name). Array-method calls may sit directly in `if`/`else if` and ternary conditions (`if (xs.some((x) => x > 3))`) — the scan lowers to a loop just before the branch; a `while` condition cannot (it re-evaluates per iteration — hoist into the loop body or restructure). Callbacks are arrows (expression or block body), inline `function` expressions, or a BARE REFERENCE to a module-level function or const helper (`xs.map(encodeTurn)`, `xs.toSorted(byAscending)` — the referenced body inlines exactly like the arrow spelled at the site); in a block body every code path must end in an explicit `return` (falling off the end would be JS `undefined`, which has no mapping — a taught stop). JS semantics hold exactly: `.slice` resolves negative and out-of-range indices the JS way, `.indexOf` never matches `NaN` while `.includes` does, `.some`/`.every` keep their vacuous defaults on empty arrays, and `.reduce` needs its initial value (the no-initial form throws on an empty array in JS, so it is a taught NS1007 — pass the starting accumulator). `.indexOf`/`.includes` work on scalar elements (numbers, tags, booleans); on record arrays JS compares references, which has no native mapping — match a field with `.find`/`.findIndex` instead.
|
|
85
85
|
- **Local mutation — your own scratch is yours; shared data is immutable.** An array your function CREATES — an array literal (`const stack: number[] = []`, `const st = [1, 2, 3]`) or a fresh copy (`.slice()` / `.map()` / `.filter()` / `.concat()` / `.toSorted()`) — is locally owned, and the full mutating method set works on it with exact JS semantics: `push(...items)`, `pop()`, `shift()`, `unshift(...items)`, `splice(start, deleteCount?, ...items)` (negative/overshooting indices clamp the JS way; the value is the removed array, also yours), `reverse()`, `fill(v, start?, end?)`, in-place `sort(cmp)`, and indexed writes `xs[i] = v`. A parser stack, a work queue, a copy-then-sort — all legal, deterministic, and byte-identical to node. Ownership ends at the first ESCAPE: once the array is returned from a callback, stored into a record/array/model, aliased by a second binding (`const b = a`), or passed where the callee could keep or mutate it, mutating it afterwards is a taught NS1051 — finish mutating first, then let it escape (an early-exit `return` is fine: execution ends there, so mutations on the other path stay legal). Two loosenings keep real code flowing. BORROWING: passing an owned array into a `readonly T[]` parameter is NOT an escape when the callee only READS it (element/property access, iteration, spreads, further borrowing passes — no return of it, no store, no onward pass into a mutable position; recursion over borrowed slices included), so measure-mutate-measure loops work (`total(out); out.push(x); total(out)`). REASSIGNED-OWNING: a `let` binding whose EVERY assignment installs a fresh owning construction (a literal or a copy — `w = xs.filter(...)`, `acc = []`) stays owned through the reassignments; ONE mixed assignment (an alias, a parameter, a helper result) and the binding never owns (NS1001 names it). Never owned: parameters, model/msg data, module `const` tables, aliases, mixed reassigned bindings, and arrays produced by helper calls (copy with `.slice()` to own one). After the value escapes it is an ordinary immutable value; the commit walkers and sharing discipline are unaffected because ownership ended before the escape.
|
|
@@ -154,7 +154,7 @@ Three effect families deliver MANY results from one command — a keyed stream t
|
|
|
154
154
|
- `Cmd.audioPlay(key, { path?, url?, cachePath?, expectedBytes? }, { event })` — open the audio event stream. One player is the whole surface, so a new `audioPlay` always REPLACES the current playback (the one key-reuse exception besides `Cmd.request`). The source cascade is the engine's: the local `path` is tried first, a missing file falls through to `url` (streamed progressively, cached at `cachePath` when given, integrity-gated by `expectedBytes` — omitted/0 means unknown size). At least one of `path`/`url` is required (NS1029); each is bytes, at most 1 KiB (NS1030). Prefer OMITTING `cachePath` for URL sources: when the app wiring configures a caches directory (`TsUiApp`'s `audio_cache_dir`), the host derives the conventional content-addressed cache path from the URL itself — your update never builds filesystem paths, and replay re-derives the same path by construction. Pass `cachePath` only to override that convention.
|
|
155
155
|
- The `event` arm is the one SDK-fixed record shape, six fields matched by NAME: `state` (the `AudioState` string-literal union — import it from `@native-sdk/core/events`, or declare an alias with exactly the members `"loaded" | "position" | "completed" | "failed" | "rejected" | "spectrum"` in any order; the runtime matches members by name), `positionMs: number`, `durationMs: number` (milliseconds; the duration is the player's estimate), `playing: boolean`, `buffering: boolean` (true while a streamed url is stalled waiting for bytes), and `bands: Uint8Array` (the 32 spectrum band magnitudes, 0–255 each, all zeros outside `"spectrum"` events). Every playback event dispatches this arm — `"failed"` (unplayable source, decode/device failure) and `"rejected"` (an empty or over-long source) included, so failure is never silence — until `Cmd.audioStop` closes the stream. `"completed"` fires once at the natural end and does NOT close the stream: starting the next track from it is the idiom.
|
|
156
156
|
- `Cmd.audioPause(key)` / `Cmd.audioResume(key)` / `Cmd.audioStop(key)` / `Cmd.audioSeek(key, ms)` / `Cmd.audioSetVolume(key, volume)` — fire-and-forget control verbs: no result of their own; their consequences arrive on the event stream (`audioResume` on a dead player reports one `"failed"` event, never silence). A verb whose key names no open stream is a no-op. `audioStop` is the audio stream's close — no events for the key after it (`Cmd.cancel` does not apply to audio). Volume is clamped 0..1 and remembered across tracks; a literal outside 0..1 (or a negative seek literal) stops the build (NS1030).
|
|
157
|
-
- `Cmd.channelOpen(key, { event })` — open an EXTERNAL-SOURCE channel under the app's numeric key: the host stages a long-lived, thread-safe posting seam its NATIVE side feeds — embedders and platform-services extensions post bytes from their own threads (sockets, watchers, workers), and each accepted post dispatches the `event` arm as one `"data"` event. Posting is deliberately not a TS verb —
|
|
157
|
+
- `Cmd.channelOpen(key, { event })` — open an EXTERNAL-SOURCE channel under the app's numeric key: the host stages a long-lived, thread-safe posting seam its NATIVE side feeds — embedders and platform-services extensions post bytes from their own threads (sockets, watchers, workers), and each accepted post dispatches the `event` arm as one `"data"` event. Posting is deliberately not a TS verb — compiled cores are single-threaded, so the TS tier opens, closes, and receives while the posting handle lives on the native side (`Effects.channelHandle(key)`). `key` may be any number expression, a positive integer below 2^53 (a certain-to-be-refused literal stops the build, NS1030). The `event` arm is a five-field record matched by NAME: `key` (the channel key echoed verbatim, so concurrent channels sharing one arm stay distinguishable; a key the wire cannot carry exactly echoes 0), `state` (the `ChannelState` union — import it from `@native-sdk/core` or declare an alias with exactly the three members `"data" | "closed" | "rejected"` in any order; checked BOTH directions, since a narrower union would silently drop states the host emits), `bytes` (`Uint8Array` — the post's payload on `"data"` events, empty otherwise), and `droppedPending`/`droppedTotal` (numbers — the honest back-pressure counters: posts the native handle refused since the previous delivered event, and over the channel's whole life; refused posts count, never silence). One channel per key at a time — a duplicate live key dispatches `"rejected"` — and the key shares the engine's effect-key space (a same-key fetch is blocked while the channel lives). No timer polling anywhere: the source wakes the loop itself. Channel events journal at the effect boundary, so recorded sessions replay the whole stream from the journal — the native posting side is never needed at replay (a native producer that consults `ChannelHandle.live()` before launching keeps replay fully offline; one that launches unconditionally is stopped at its first post, which answers `.closed`).
|
|
158
158
|
- `Cmd.channelClose(key)` — close the open channel under the key, if any: staged posts flush, exactly one `"closed"` event (final drop totals aboard) dispatches the event arm, and the key frees. A key with no open channel no-ops.
|
|
159
159
|
- `Cmd.imageLoad(id, { path?, url?, cachePath?, expectedBytes? }, { event })` — load an image at runtime under the model-owned NUMERIC ImageId your markup binds (`<image image="{cover}"/>`, `<avatar image="{avatar}"/>`); `id` may be any number expression (ids are model data), a positive integer below 2^53 (a certain-to-be-refused literal like 0 stops the build, NS1030). The source cascade is `audioPlay`'s exactly: local `path` first, a missing file falls through to `url` (fetched whole, installed at the cache path and integrity-gated by `expectedBytes`); at least one of `path`/`url` (NS1029), and prefer OMITTING `cachePath` — the wiring's caches directory (`TsUiApp`'s `image_cache_dir`) derives the content-addressed path from the URL. Exactly ONE `event` arm dispatches per load — a five-field record matched by NAME: `id` (the requested ImageId echoed verbatim, so concurrent loads sharing one arm stay distinguishable; an id the wire cannot carry exactly echoes 0), `state` (the `ImageState` union — exactly the fifteen members `"loaded" | "rejected" | "not_found" | "io_failed" | "connect_failed" | "tls_failed" | "protocol_failed" | "timed_out" | "http_status" | "cancelled" | "too_large" | "unsupported" | "decode_failed" | "registry_full" | "alloc_failed"`, any order; `"alloc_failed"` is resource exhaustion at registration — the host refused the memory, the bytes may be fine, retry when memory frees), `width`/`height` (the decoded dimensions on `"loaded"`, 0 otherwise), and `status` (the HTTP status for url loads that performed an exchange; 0 when none occurred — local paths, cache hits — so a cached `"loaded"` is distinguishable from a network one). On `"loaded"` the pixels are already registered under the id — store the id in the model then (the store-on-success discipline keeps a fallback rendering until the load lands). One load per id at a time: a duplicate live id dispatches `"rejected"` (the spawn discipline — a load in flight is never replaced implicitly), and image loads are not the string-keyed `Cmd.cancel`'s to end — `Cmd.imageCancel(id)` is their cancel, LOUD like spawn's: the one terminal still arrives as the event arm's `"cancelled"`, and the id frees for a fresh load once it lands (an id with no live load no-ops; the same NS1030 literal gate as `imageLoad`). Decode limits are the registered-image limits (16 slots, 1 MiB decoded pixels — avatar/cover scale, not photo scale); the encoded source bound is 1.25 MiB, and over-bound sources fail whole with `"too_large"`, never cut. `Cmd.imageUnregister(id)` releases a loaded image's registry slot — the gallery eviction move when the 17th distinct image would answer `"registry_full"`: views bound to the id fall back, and the slot accepts the next load. Unregister is synchronous registry surgery, NOT an effect — no result Msg, an unregistered id no-ops (the same NS1030 literal gate) — and it frees only the CURRENT registration: a load in flight under the id still registers at its terminal, so cancel the load first (`Cmd.imageCancel`) to keep the slot free.
|
|
160
160
|
|
|
@@ -206,18 +206,18 @@ Sub values follow the Cmd purity rule with their own home (NS1025): built inline
|
|
|
206
206
|
|
|
207
207
|
Keep the Sub-vs-stream line straight: a Sub is DECLARATIVE — derived from the model, started and stopped by reconciliation, and the app never opens or closes one. The multi-result streams (`Cmd.spawn`'s lines, `Cmd.audioPlay`'s events) are Cmd-INITIATED — imperative opens with a keyed lifecycle the app drives (`Cmd.cancel` for spawn, `Cmd.audioStop` for audio). If the effect should exist exactly while some model state holds, it wants a Sub shape; if the app decides when it starts and ends, it is a stream.
|
|
208
208
|
|
|
209
|
-
One caveat for node-side pokes: the
|
|
209
|
+
One caveat for node-side pokes: the build resolves the `@native-sdk/core*` specifiers for you, but plain `node` does not know them, so quick behavioral checks under node work directly on cores with no SDK import, and on cores importing `Cmd`, `Sub`, `asciiBytes`, or the text engine only with a module mapping (or by copying the SDK module files next to the core and rewriting the specifiers). `native dev --core` already maps them.
|
|
210
210
|
|
|
211
211
|
## Splitting a core into modules
|
|
212
212
|
|
|
213
|
-
`src/core.ts` is the ENTRY module; a core that outgrows it splits into more `.ts` files under `src/` (subdirectories included). The whole import graph still
|
|
213
|
+
`src/core.ts` is the ENTRY module; a core that outgrows it splits into more `.ts` files under `src/` (subdirectories included). The whole import graph still compiles as ONE native module - one flat namespace - and runs unchanged under node.
|
|
214
214
|
|
|
215
215
|
- **Spell relative imports with the real filename**: `import { parsePs } from "./parsers.ts"` (node's loader resolves real files, not bare stems - a missing extension or a missing file is a taught NS1037).
|
|
216
216
|
- **`src/` is the boundary**: `../` escapes and absolute paths are taught (NS1034); bare npm specifiers are taught (NS1035 - vendor the code under `src/` or make the import `import type`). Only `@native-sdk/core` (the intrinsic Cmd/Sub/asciiBytes surface) and the SDK library modules below carry runtime meaning from outside.
|
|
217
|
-
- **Everything module-level is importable**: interfaces, literal-union aliases, discriminated unions, module `const` numbers and tables, and helper functions all cross files (renamed imports and `import * as ns` namespace aliases both work — the alias is dot-syntax over the same flat namespace, never a value of its own). Export lists and value re-exports work too: `export { helper, doneCount as remaining }` binds names over existing declarations, and `export { parsePs } from "./parsers.ts"` forwards another module's export by name (a renamed binding emits as a flat-namespace alias). Type names and EXPORTED value names must be unique across the core's files (NS1038 - declare once, import where used; renamed exports claim their new names in the same namespace); colliding PRIVATE helpers are fine (the
|
|
217
|
+
- **Everything module-level is importable**: interfaces, literal-union aliases, discriminated unions, module `const` numbers and tables, and helper functions all cross files (renamed imports and `import * as ns` namespace aliases both work — the alias is dot-syntax over the same flat namespace, never a value of its own). Export lists and value re-exports work too: `export { helper, doneCount as remaining }` binds names over existing declarations, and `export { parsePs } from "./parsers.ts"` forwards another module's export by name (a renamed binding emits as a flat-namespace alias). Type names and EXPORTED value names must be unique across the core's files (NS1038 - declare once, import where used; renamed exports claim their new names in the same namespace); colliding PRIVATE helpers are fine (the compile uniques them per module).
|
|
218
218
|
- **No runtime import cycles** (NS1036). `import type` back-edges are legal and idiomatic: a helper module type-imports `Model` from `./core.ts` while `core.ts` runtime-imports the helpers - that is the expected shape, not a smell.
|
|
219
219
|
- **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
|
|
220
|
-
- **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never
|
|
220
|
+
- **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
|
|
221
221
|
|
|
222
222
|
The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor-ts` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/ai-chat-ts` (core.ts + api.ts — the JSON-over-bytes wire-format reference: request encoding and a targeted parse walk that returns `null` on anything malformed) in the SDK repo.
|
|
223
223
|
|
|
@@ -225,7 +225,7 @@ The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player
|
|
|
225
225
|
|
|
226
226
|
`string` in a core is for literals, string-literal-union tags, and `===` comparisons — content equality, on tags and plain `string` values alike (`name === "app.add"` in a command mapper works and behaves identically under node and native). Dynamic, user-visible text lives in the Model as `Uint8Array` — indexing yields byte values, `.length` is byte length, `subarray` is a view and `slice` is a copy, and both resolve their bounds the JS way (negatives count from the end, out-of-range clamps, a crossed range is empty), identical under node and native. Observing a `string`'s code units (`.length`, `s[i]`, `.charCodeAt`) is banned (NS1004) because UTF-16 and UTF-8 would disagree, and `+` concatenation is banned (NS1018) because runtime string building needs a JS string heap the binary does not carry — build text with template literals into bytes instead.
|
|
227
227
|
|
|
228
|
-
Turn literals and templates into bytes with the `asciiBytes` intrinsic from the SDK. The
|
|
228
|
+
Turn literals and templates into bytes with the `asciiBytes` intrinsic from the SDK. The compiler recognizes the import by identity and folds every call at compile time — a literal argument becomes rodata, a template becomes per-dispatch arena bytes — and under node the same import runs as a plain function with the same result:
|
|
229
229
|
|
|
230
230
|
```ts
|
|
231
231
|
import { asciiBytes } from "@native-sdk/core";
|
|
@@ -239,7 +239,7 @@ Arguments must be string literals or templates (the fold happens at compile time
|
|
|
239
239
|
|
|
240
240
|
### The byte-text string methods
|
|
241
241
|
|
|
242
|
-
Bytes read like text: the everyday string methods work directly on `Uint8Array` values, with **byte-honest semantics** — every length, offset, and index is a BYTE length/offset (never a character count: `é` measures 2 and `padStart` pads by bytes), search is byte-wise, and case mapping is Unicode SIMPLE case mapping (code point → code point from the Unicode tables; locale-free, no special casing — `ß` stays `ß`, `σ` uppercases to `Σ`; bytes that are not well-formed UTF-8 pass through case mapping unchanged). Natively each call lowers onto
|
|
242
|
+
Bytes read like text: the everyday string methods work directly on `Uint8Array` values, with **byte-honest semantics** — every length, offset, and index is a BYTE length/offset (never a character count: `é` measures 2 and `padStart` pads by bytes), search is byte-wise, and case mapping is Unicode SIMPLE case mapping (code point → code point from the Unicode tables; locale-free, no special casing — `ß` stays `ß`, `σ` uppercases to `Σ`; bytes that are not well-formed UTF-8 pass through case mapping unchanged). Natively each call lowers onto the compiled core's runtime; under node the devhost installs the same methods from the same Unicode tables, so both runtimes produce identical bytes.
|
|
243
243
|
|
|
244
244
|
```ts
|
|
245
245
|
const query = model.query.trim().toLowerCase(); // JS whitespace set; simple case map
|
|
@@ -353,15 +353,15 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
|
|
|
353
353
|
- **NS1027 effect results route to Msg arms by name.** Routing (`{ key?, ok, err }`) and timer targets are string-literal arm names with the payload shape the effect produces — one `Uint8Array` field for host results/errors, one number field for timer and delay fires, no fields for `writeFile`'s ok, one number plus one `Uint8Array` field for `fetch`'s ok. Callbacks and computed names cannot work: the runtime builds the result Msg from the arm's declared shape at build time.
|
|
354
354
|
- **NS1028 Cmd.persist is not yet host-backed (warning).** The op compiles and stays on the wire, but no shipping host performs it — persist with `Cmd.writeFile` and boot-load with `Cmd.readFile` instead. The only non-fatal notice in the set.
|
|
355
355
|
- **NS1029 effect op arguments have a fixed shape.** Paths/URLs/bodies are bytes, `Cmd.fetch`'s spec is an inline object with a closed verb literal, a number-literal timeout, and an inline flat record of headers whose NAMES are compile-time ASCII and whose VALUES are string literals or runtime bytes (`Uint8Array`). The record's shape encodes at build time; a runtime header value rides its length-prefixed wire field at dispatch time exactly like `url`/`body` — but a smuggled string (a ternary of literals, a template) has no encoding: make it bytes.
|
|
356
|
-
- **NS1031 exported model helpers join the model's binding surface.** An exported single-Model-parameter helper
|
|
357
|
-
- **NS1032 viewUnbound names update-only model state.** `export const viewUnbound = [...] as const` entries must be string literals naming Model fields, exported model helpers, or Msg kinds — by their TypeScript spellings (`"nextId"
|
|
356
|
+
- **NS1031 exported model helpers join the model's binding surface.** An exported single-Model-parameter helper becomes a Model declaration markup binds (`doneCount` → `{doneCount}`); two members with one binding name would be ambiguous — rename one.
|
|
357
|
+
- **NS1032 viewUnbound names update-only model state.** `export const viewUnbound = [...] as const` entries must be string literals naming Model fields, exported model helpers, or Msg kinds — by their TypeScript spellings (`"nextId"`); anything else would silence nothing and hide a typo.
|
|
358
358
|
- **NS1030 effect arguments respect the engine's limits.** A compile-time-knowable value outside an engine bound (a path literal over 1024 bytes, a URL literal over 2 KiB, more than 8 headers, a header block over 1 KiB, a delay literal outside 1ms..one year) stops the build instead of shipping a guaranteed runtime rejection. Dynamic values stay the engine's to validate — they surface through the `err` arm.
|
|
359
359
|
- **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm. The generated wiring builds these host events structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
|
|
360
360
|
- **NS1034 core imports stay inside src/.** `../` escapes and absolute paths are rejected: the entry module's directory is the core's whole world - the build ships exactly that tree.
|
|
361
361
|
- **NS1035 npm packages do not run inside a core.** No JS engine ships in the binary; vendor the logic under `src/` or make the import type-only.
|
|
362
362
|
- **NS1036 core modules do not import in a cycle.** Runtime cycles only work through JS live-binding indirection; hoist shared declarations, or make the back-edge `import type` (which is exempt and idiomatic).
|
|
363
363
|
- **NS1037 an import names a real module file.** Spell relative specifiers with the `.ts` extension and point them at existing files; `@native-sdk/...` specifiers must name a shipped SDK module.
|
|
364
|
-
- **NS1038 module-scope names are unique across a core's files.** Type names and exported value names share the
|
|
364
|
+
- **NS1038 module-scope names are unique across a core's files.** Type names and exported value names share the compiled module's one namespace - declare the shared thing once and import it (private helper collisions are auto-prefixed instead). Same-file homonyms count too: a type and an exported value cannot share a name, and interfaces never merge.
|
|
365
365
|
- **NS1039 a namespace import is a compile-time alias.** `import * as ns from "./util.ts"` works as dot-syntax (`ns.helper(x)`, `ns.Cfg`); `ns` itself is not a value (never stored or passed), and the intrinsic `@native-sdk/core` module is imported by name so the purity rules can see `Cmd`/`Sub`/`asciiBytes`.
|
|
366
366
|
- **NS1040 no regular expressions.** A regex is a runtime engine the binary does not carry; scan bytes with loops or the SDK text helpers (`containsIgnoreCase`, `trimAsciiSpaces`).
|
|
367
367
|
- **NS1041 types are static: no runtime type or shape tests.** `typeof` values, `in`, `instanceof`, and the `Object`/`Reflect`/`JSON`/`Array` statics read runtime tags fixed native layouts do not have; model alternatives as a discriminated union and switch on its `kind`.
|
|
@@ -370,15 +370,15 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
|
|
|
370
370
|
- **NS1044 no BigInt or Symbol.** A core's numbers are IEEE f64 slots (integer-classed slots emit i64); model identities as number ids.
|
|
371
371
|
- **NS1045 destructuring binds record fields into const locals.** `const { total, done: doneCount } = stats;` is a compile-time alias; array positions, parameter patterns, defaults, rest, and nesting can be silently absent in JS and are taught toward explicit reads.
|
|
372
372
|
- **NS1046 functions live at module level.** Nested function declarations, non-const function values, and `?.()` treat functions as runtime values closing over the frame; move the function to module scope, bind it as a const local helper, or pass what it used (inline arrows as call arguments stay).
|
|
373
|
-
- **NS1047 modules export their declarations by name.** Named exports all compile: `export` on the declaration, export lists (`export { a, b as c }` — a rename binds a new flat-namespace name), and named value re-exports (`export { x } from "./m.ts"`). What stays out is the unnamed tail: `export default`, `export =`, `export * from`, plus bindings with no single
|
|
373
|
+
- **NS1047 modules export their declarations by name.** Named exports all compile: `export` on the declaration, export lists (`export { a, b as c }` — a rename binds a new flat-namespace name), and named value re-exports (`export { x } from "./m.ts"`). What stays out is the unnamed tail: `export default`, `export =`, `export * from`, plus bindings with no single compiled value (renamed generics/classes, wiring config, re-exports of the SDK surface).
|
|
374
374
|
- **NS1048 equality is strict.** `==`/`!=` apply JS's coercion table; use `===`/`!==`.
|
|
375
|
-
- **NS1049 locals declare with const and let.** `var` hoists to function scope and reads `undefined` before its line — behavior the
|
|
375
|
+
- **NS1049 locals declare with const and let.** `var` hoists to function scope and reads `undefined` before its line — behavior the compiled locals cannot have.
|
|
376
376
|
- **NS1050 generics live on module-level declarations.** Module-level generic functions/interfaces/aliases monomorphize per concrete use; entry points and function values stay concrete.
|
|
377
377
|
- **NS1051 a local array is yours until it escapes.** Mutating an owned array AFTER it was returned from a callback, stored into a structure, aliased, or passed where the callee could keep or mutate it is taught with the escape named (kind and line): JS would show the holder your later mutations through the shared reference, while the native value was shared structurally at the escape. Finish mutating first, pass the array after the last mutation, or mutate inside the callee — a pass into a `readonly T[]` reader parameter is a borrow, not an escape. An escape inside a loop gates the whole loop body (the second iteration would mutate after the first iteration's escape).
|
|
378
378
|
- **NS1052 spread array locals declare their array type.** `const turns = [...model.turns, next];` has no slice target to lower against — annotate the local: `const turns: readonly Turn[] = [...model.turns, next];`.
|
|
379
|
-
- **NS1053 generics instantiate per concrete call site.** A generic call whose resolved type argument has no concrete
|
|
379
|
+
- **NS1053 generics instantiate per concrete call site.** A generic call whose resolved type argument has no concrete compiled type (`never` from `pick([])`, `any`/`unknown`, an unnamed literal union) is taught — annotate the call site or name the alias.
|
|
380
380
|
- **NS1054 function values stay local helpers.** A const-bound, capture-free, fully-annotated function value hoists to a module-level fn; captures, missing annotations, reassignment, storing/returning the value, and record-field calls are taught toward the helper shape.
|
|
381
|
-
- **NS1055 classes hold data, not hierarchies.** No `extends`/`super`/`abstract`: compose (a field holding the other record or class), or model the variants as a `kind`-discriminated union and switch on it —
|
|
381
|
+
- **NS1055 classes hold data, not hierarchies.** No `extends`/`super`/`abstract`: compose (a field holding the other record or class), or model the variants as a `kind`-discriminated union and switch on it — compiled classes are flat structs with static dispatch.
|
|
382
382
|
- **NS1056 class members are annotated fields, one constructor, and plain methods.** `static` methods, `static readonly` consts, and erased `private`/`protected` compile; getters/setters, `#`-privates, `accessor`, unannotated or optional (`?`) instance fields, `this` escaping as a value (or used inside a static member — statics go by the class name), and class instances stored in the Model tree are each taught toward the data-class shape.
|
|
383
383
|
- **NS1057 thrown values are kind-tagged subset shapes.** Several distinct shapes may throw — the checker collects them into the core's thrown union, and `catch (e)` narrows it with kind tests (`if (e.kind === "parse")`), no `as` needed (single-shape cores may still narrow once with `const err = e as YourError;`; bare rethrow always works). What teaches: untagged thrown values in a heterogeneous set, two shapes sharing a `kind` with different payloads, asserting one member of a multi-shape core, the binding escaping untyped, and `throw new Error(...)`.
|
|
384
384
|
- **NS1058 finally never redirects control flow.** `return`/`throw`/`break`-out/`continue`-out inside `finally` would override the pending return or exception (JS's no-unsafe-finally); keep `finally` to cleanup statements.
|
|
@@ -463,10 +463,10 @@ export function update(model: Model, msg: Msg): Model {
|
|
|
463
463
|
|
|
464
464
|
A `native init` app needs NONE of this section: the build detects `src/core.ts` and stages the wiring itself (a core exporting `commandMsg(name: string): Msg | null` automatically receives menu/shortcut command events as Msgs). The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
|
|
465
465
|
|
|
466
|
-
The
|
|
466
|
+
The compiled core runs as a full desktop app through `native_sdk.TsUiApp(core)` — the committed TS model IS the app model, no shim, no glue:
|
|
467
467
|
|
|
468
468
|
```zig
|
|
469
|
-
const core = @import("core.zig"); // the
|
|
469
|
+
const core = @import("core.zig"); // the generated mirror over the compiled core
|
|
470
470
|
const Adapter = native_sdk.TsUiApp(core);
|
|
471
471
|
const App = Adapter.App; // a native_sdk.UiApp(core.Model, core.Msg)
|
|
472
472
|
|
|
@@ -482,9 +482,9 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
|
|
|
482
482
|
```
|
|
483
483
|
|
|
484
484
|
- `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically (a wiring that also sets one of those seams is a teaching panic). Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
|
|
485
|
-
- Markup binds your model's field names EXACTLY as you wrote them: `nextId` binds as `{nextId}` (the
|
|
485
|
+
- Markup binds your model's field names EXACTLY as you wrote them: `nextId` binds as `{nextId}` (the core's model keeps the TS spellings). Record arrays iterate with `<for each="tasks" as="t" key="id">` and items bind their fields (`{t.title}`); optional scalars gate with `<if test="{selected}">` (null is falsy); string-literal unions bind as their member name (`{filter}` renders `all` — compare against a quoted literal, `selected="{sortKey == 'cpu'}"`); exported single-model helpers bind as derived values (`{doneCount}`) and slice-returning ones drive `for each`. Markup `<chart>` series bind number arrays too — `<series kind="bar" values="{cpuSpark}" />` over a field or helper returning `readonly number[]` (f64, narrowed per sample into the chart pipeline); pad a filling window's leading gap with `NaN` samples, which draw nothing.
|
|
486
486
|
- `Options.sync` does not exist for TS apps (a committed model cannot be mutated in place): keep continuous controls model-driven — bind the widget's value and echo `on-change`/`on-scroll` Msgs back into the model.
|
|
487
|
-
- One live app per core module per process: two apps over the SAME
|
|
487
|
+
- One live app per core module per process: two apps over the SAME core would share one committed root — and a process carries ONE compiled core (the archive owns a fixed-prefix C ABI symbol set).
|
|
488
488
|
- Record/replay, the automation verbs, and screenshot fingerprints work unchanged — the adapter rides the standard UiApp dispatch path.
|
|
489
489
|
|
|
490
490
|
## Checking your work
|
|
@@ -493,11 +493,11 @@ Scaffolded apps carry an editor surface (`package.json`, `tsconfig.json`, and a
|
|
|
493
493
|
|
|
494
494
|
**Refresh the model contract after shape changes.** `native check`'s typed markup pass reads `zig-out/model-contract.zon`, an artifact of the LAST build/test — after changing Model fields or Msg kinds, run `native test` (or `zig build model-contract` in an app that owns its build.zig) before trusting `native check`. A stale contract reports phantom hard errors (`unknown message tag`, `binding does not name a model field`) that name your NEW state — the state is fine; the artifact is old. And never delete `src/app.native` in response to a note about nothing embedding it: on the TypeScript track the generated wiring embeds the view from outside the app tree, so that file is always wired.
|
|
495
495
|
|
|
496
|
-
The
|
|
496
|
+
The frontend is the checker: run it after every meaningful edit and read the diagnostics — they always name the rule, the idiomatic rewrite, and the reason. Inside an app, `native check` runs it for you (plus markup and app.zon validation); in a core-only workspace, invoke it directly:
|
|
497
497
|
|
|
498
498
|
```sh
|
|
499
499
|
native check # inside an app
|
|
500
|
-
node <sdk-repo>/packages/core/src/cli.ts src/core.ts
|
|
500
|
+
node <sdk-repo>/packages/core/src/cli.ts src/core.ts
|
|
501
501
|
```
|
|
502
502
|
|
|
503
|
-
Exit 0 means the module typechecked (real tsc semantics)
|
|
503
|
+
Exit 0 means the module typechecked (real tsc semantics) and passed every subset rule — the exact pass every build runs before the external core compiler takes the graph. Because the subset is erasable TypeScript, `node` can import your core directly for quick behavioral checks (`node --input-type=module -e "..."` or a small `node --test` file) — the native build has the same semantics. If the core imports `@native-sdk/core` (for `Cmd` or `asciiBytes`), map that one specifier for node first: copy the SDK module file next to the core and rewrite the import, or run through a loader that resolves it.
|
|
@@ -2958,7 +2958,7 @@ static NSRect NativeSdkPacketAlignRectToPixels(NSRect rect, CGFloat scale, NSUIn
|
|
|
2958
2958
|
}
|
|
2959
2959
|
|
|
2960
2960
|
/* ---------------------------------------------------------------------------
|
|
2961
|
-
* Compact binary gpu-surface packet decoding (wire format
|
|
2961
|
+
* Compact binary gpu-surface packet decoding (wire format v5).
|
|
2962
2962
|
*
|
|
2963
2963
|
* Little-endian, length-prefixed, mirror of the engine's binary packet
|
|
2964
2964
|
* encoder (serialization.zig, `writeCanvasGpuPacketBinary` and the patch
|
|
@@ -2973,7 +2973,8 @@ static NSRect NativeSdkPacketAlignRectToPixels(NSRect rect, CGFloat scale, NSUIn
|
|
|
2973
2973
|
* keyed upserts + the full draw-order vector) against the view's retained
|
|
2974
2974
|
* command dictionary; v3 added the flag-gated dirty rect list after the
|
|
2975
2975
|
* scissor; v4 added the per-command stroke end-cap code after
|
|
2976
|
-
* stroke_width
|
|
2976
|
+
* stroke_width; v5 added compact positioned glyph runs after text UTF-8.
|
|
2977
|
+
* The version this comment names and the encoder's spec
|
|
2977
2978
|
* comment must agree with `binary_packet_version` (serialization.zig);
|
|
2978
2979
|
* the `test-wire-format-version-prose` build check pins all three.
|
|
2979
2980
|
*/
|
|
@@ -3005,6 +3006,14 @@ static uint8_t NativeSdkBinaryReadU8(NativeSdkBinaryPacketReader *reader) {
|
|
|
3005
3006
|
return reader->bytes[reader->offset++];
|
|
3006
3007
|
}
|
|
3007
3008
|
|
|
3009
|
+
static uint16_t NativeSdkBinaryReadU16(NativeSdkBinaryPacketReader *reader) {
|
|
3010
|
+
if (!NativeSdkBinaryHasBytes(reader, 2)) return 0;
|
|
3011
|
+
uint16_t value = 0;
|
|
3012
|
+
memcpy(&value, reader->bytes + reader->offset, 2);
|
|
3013
|
+
reader->offset += 2;
|
|
3014
|
+
return CFSwapInt16LittleToHost(value);
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3008
3017
|
static uint32_t NativeSdkBinaryReadU32(NativeSdkBinaryPacketReader *reader) {
|
|
3009
3018
|
if (!NativeSdkBinaryHasBytes(reader, 4)) return 0;
|
|
3010
3019
|
uint32_t value = 0;
|
|
@@ -3209,6 +3218,45 @@ static NSDictionary *NativeSdkBinaryReadText(NativeSdkBinaryPacketReader *reader
|
|
|
3209
3218
|
@"color" : color,
|
|
3210
3219
|
@"text" : text,
|
|
3211
3220
|
}];
|
|
3221
|
+
uint8_t hasPositionedGlyphs = NativeSdkBinaryReadU8(reader);
|
|
3222
|
+
if (reader->failed) return nil;
|
|
3223
|
+
if (hasPositionedGlyphs) {
|
|
3224
|
+
uint32_t glyphCount = NativeSdkBinaryReadU32(reader);
|
|
3225
|
+
if (reader->failed || glyphCount > 65536 || glyphCount > (reader->length - reader->offset) / 15) {
|
|
3226
|
+
reader->failed = YES;
|
|
3227
|
+
return nil;
|
|
3228
|
+
}
|
|
3229
|
+
NSMutableArray *glyphs = [NSMutableArray arrayWithCapacity:glyphCount];
|
|
3230
|
+
for (uint32_t index = 0; index < glyphCount; index++) {
|
|
3231
|
+
uint16_t glyphId = NativeSdkBinaryReadU16(reader);
|
|
3232
|
+
uint8_t flags = NativeSdkBinaryReadU8(reader);
|
|
3233
|
+
if (flags > 1) {
|
|
3234
|
+
reader->failed = YES;
|
|
3235
|
+
return nil;
|
|
3236
|
+
}
|
|
3237
|
+
uint64_t glyphFontId = (flags & 1) != 0 ? NativeSdkBinaryReadU64(reader) : fontId;
|
|
3238
|
+
NSNumber *x = NativeSdkBinaryReadF32Number(reader);
|
|
3239
|
+
NSNumber *baseline = NativeSdkBinaryReadF32Number(reader);
|
|
3240
|
+
NSNumber *advance = NativeSdkBinaryReadF32Number(reader);
|
|
3241
|
+
if (reader->failed) return nil;
|
|
3242
|
+
[glyphs addObject:@{ @"id" : @(glyphId), @"font" : @(glyphFontId), @"x" : x, @"baseline" : baseline, @"advance" : advance }];
|
|
3243
|
+
}
|
|
3244
|
+
uint32_t fragmentCount = NativeSdkBinaryReadU32(reader);
|
|
3245
|
+
if (reader->failed || fragmentCount > 64 || fragmentCount > (reader->length - reader->offset) / 12) {
|
|
3246
|
+
reader->failed = YES;
|
|
3247
|
+
return nil;
|
|
3248
|
+
}
|
|
3249
|
+
NSMutableArray *fragments = [NSMutableArray arrayWithCapacity:fragmentCount];
|
|
3250
|
+
for (uint32_t index = 0; index < fragmentCount; index++) {
|
|
3251
|
+
NSNumber *x = NativeSdkBinaryReadF32Number(reader);
|
|
3252
|
+
NSNumber *baseline = NativeSdkBinaryReadF32Number(reader);
|
|
3253
|
+
NSString *fragmentText = NativeSdkBinaryReadString(reader);
|
|
3254
|
+
if (reader->failed || !fragmentText) return nil;
|
|
3255
|
+
[fragments addObject:@{ @"x" : x, @"baseline" : baseline, @"text" : fragmentText }];
|
|
3256
|
+
}
|
|
3257
|
+
result[@"positionedGlyphs"] = glyphs;
|
|
3258
|
+
result[@"positionedFragments"] = fragments;
|
|
3259
|
+
}
|
|
3212
3260
|
uint8_t hasLayout = NativeSdkBinaryReadU8(reader);
|
|
3213
3261
|
if (reader->failed) return nil;
|
|
3214
3262
|
if (!hasLayout) return result;
|
|
@@ -3358,7 +3406,7 @@ static NSDictionary *NativeSdkPacketDictionaryFromBinary(const uint8_t *bytes, N
|
|
|
3358
3406
|
if (memcmp(bytes, "NSGP", 4) != 0) return nil;
|
|
3359
3407
|
reader.offset = 4;
|
|
3360
3408
|
uint8_t version = NativeSdkBinaryReadU8(&reader);
|
|
3361
|
-
if (version !=
|
|
3409
|
+
if (version != 5) return nil;
|
|
3362
3410
|
uint8_t loadActionCode = NativeSdkBinaryReadU8(&reader);
|
|
3363
3411
|
uint8_t packetFlags = NativeSdkBinaryReadU8(&reader);
|
|
3364
3412
|
(void)NativeSdkBinaryReadU8(&reader); /* reserved */
|
package/src/platform/types.zig
CHANGED
|
@@ -766,6 +766,10 @@ pub const ViewKind = enum {
|
|
|
766
766
|
pub const GpuSurfaceBackend = enum {
|
|
767
767
|
none,
|
|
768
768
|
metal,
|
|
769
|
+
/// Direct2D retained rendering on Windows. The application-facing
|
|
770
|
+
/// backend request remains portable; frame events report the concrete
|
|
771
|
+
/// renderer that actually completed the present.
|
|
772
|
+
direct2d,
|
|
769
773
|
/// CPU rasterization (reference renderer) presented through the
|
|
770
774
|
/// platform's pixel blit path. Platforms without a GPU packet renderer
|
|
771
775
|
/// (Linux/GTK) report this backend in their frame events; manifests
|