@native-sdk/cli 0.4.4 → 0.5.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.
Files changed (83) hide show
  1. package/build/app.zig +187 -6
  2. package/build/ts_run.mjs +63 -0
  3. package/build.zig +213 -1
  4. package/build.zig.zon +1 -0
  5. package/package.json +15 -10
  6. package/packages/core/package-lock.json +43 -0
  7. package/packages/core/package.json +37 -0
  8. package/packages/core/rt/rt.zig +1579 -0
  9. package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
  10. package/packages/core/sdk/core.ts +694 -0
  11. package/packages/core/sdk/events.ts +137 -0
  12. package/packages/core/sdk/text.ts +519 -0
  13. package/packages/core/src/checker.ts +1869 -0
  14. package/packages/core/src/cli.ts +68 -0
  15. package/packages/core/src/devhost.ts +291 -0
  16. package/packages/core/src/devhost_resolver.mjs +22 -0
  17. package/packages/core/src/diagnostics.ts +417 -0
  18. package/packages/core/src/emitter.ts +8815 -0
  19. package/packages/core/src/infer.ts +1515 -0
  20. package/packages/core/src/modules.ts +173 -0
  21. package/packages/core/src/ownership.ts +740 -0
  22. package/packages/core/src/text_polyfill.ts +337 -0
  23. package/packages/core/src/text_tables.ts +408 -0
  24. package/packages/core/src/transpile.ts +146 -0
  25. package/packages/core/src/typed_ast.ts +536 -0
  26. package/packages/core/src/types.ts +815 -0
  27. package/skill-data/native-ui/SKILL.md +14 -0
  28. package/skill-data/ts-core/SKILL.md +493 -0
  29. package/skill-data/zig/SKILL.md +10 -0
  30. package/src/app_runner/root.zig +24 -0
  31. package/src/app_runner/ts_core_main.zig +231 -0
  32. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  33. package/src/primitives/app_manifest/root.zig +5 -0
  34. package/src/primitives/canvas/commands.zig +14 -7
  35. package/src/primitives/canvas/lazy_tls.zig +73 -0
  36. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  37. package/src/primitives/canvas/root.zig +6 -0
  38. package/src/primitives/canvas/tests.zig +1 -0
  39. package/src/primitives/canvas/text_atlas.zig +40 -32
  40. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  41. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  42. package/src/primitives/canvas/text_spans.zig +39 -26
  43. package/src/primitives/canvas/tokens.zig +54 -0
  44. package/src/primitives/canvas/ui.zig +125 -0
  45. package/src/primitives/canvas/ui_markup.zig +22 -3
  46. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  47. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  48. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  49. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  50. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  51. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  52. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  53. package/src/primitives/canvas/ui_schema.zig +8 -0
  54. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  55. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  56. package/src/primitives/canvas/widget_render.zig +25 -15
  57. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  58. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  59. package/src/root.zig +7 -0
  60. package/src/runtime/canvas_frame.zig +57 -36
  61. package/src/runtime/canvas_images.zig +9 -3
  62. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  63. package/src/runtime/canvas_widget_runtime.zig +7 -4
  64. package/src/runtime/effects.zig +490 -2
  65. package/src/runtime/effects_host_tests.zig +594 -0
  66. package/src/runtime/root.zig +18 -0
  67. package/src/runtime/session_replay.zig +7 -1
  68. package/src/runtime/tests.zig +2 -0
  69. package/src/runtime/ts_core_host.zig +1505 -0
  70. package/src/runtime/ts_core_host_tests.zig +1408 -0
  71. package/src/runtime/ts_ui_app.zig +469 -0
  72. package/src/runtime/ui_app.zig +58 -0
  73. package/src/runtime/view_canvas.zig +24 -17
  74. package/src/runtime/view_widget_tree.zig +2 -2
  75. package/src/tooling/codesign.zig +212 -105
  76. package/src/tooling/doctor.zig +78 -0
  77. package/src/tooling/manifest.zig +47 -0
  78. package/src/tooling/package.zig +124 -12
  79. package/src/tooling/raw_manifest.zig +15 -0
  80. package/src/tooling/root.zig +1 -0
  81. package/src/tooling/templates.zig +683 -28
  82. package/src/tooling/ts_core.zig +486 -0
  83. package/src/tooling/verbs.zig +17 -0
@@ -0,0 +1,815 @@
1
+ // The module type table: every named type in an app core, classified into
2
+ // the Zig type model the mapping rules emit against.
3
+ //
4
+ // string-literal union -> enum(u8), declaration order (R5)
5
+ // number-literal union -> integer alias (R5; see report: v1 emits the
6
+ // integer repr instead of a synthesized enum —
7
+ // member names cannot be derived mechanically)
8
+ // discriminated union -> union(enum), payloads inlined per arm (R6)
9
+ // interface -> struct; by-value when promoted (R4), else a
10
+ // frame/heap node behind *const T (R14)
11
+ // readonly T[] -> []const E; []const *const T for node types (R16)
12
+ // T | null/undefined -> ?T (R7)
13
+ // Uint8Array -> []const u8 (R3)
14
+
15
+ import { ts, TypedAst, hasExportModifier, exportListBindings, type PropInfo } from "./typed_ast.ts";
16
+ import { mutatingMethodNames } from "./ownership.ts";
17
+
18
+ export type ZType =
19
+ | { readonly k: "number" } // resolved to i64/f64 per slot by integer inference (R2)
20
+ | { readonly k: "i64" }
21
+ | { readonly k: "f64" }
22
+ | { readonly k: "bool" }
23
+ | { readonly k: "void" }
24
+ | { readonly k: "bytes" }
25
+ | { readonly k: "string" } // rodata literals only; storage is []const u8
26
+ | { readonly k: "numAlias"; readonly name: string; readonly repr: "u8" | "i64"; readonly values: readonly number[] }
27
+ | { readonly k: "enum"; readonly name: string; readonly members: readonly string[] }
28
+ | { readonly k: "struct"; readonly name: string }
29
+ | { readonly k: "union"; readonly name: string }
30
+ | { readonly k: "slice"; readonly elem: ZType }
31
+ | { readonly k: "optional"; readonly inner: ZType };
32
+
33
+ export interface ZField {
34
+ readonly tsName: string;
35
+ readonly zigName: string;
36
+ readonly type: ZType;
37
+ readonly decl: ts.Declaration;
38
+ }
39
+
40
+ export interface StructInfo {
41
+ readonly name: string;
42
+ readonly decl: ts.InterfaceDeclaration | ts.ClassDeclaration;
43
+ /// Filled in the second collection pass (field types may reference types
44
+ /// declared in any of the core's files, in any order).
45
+ fields: readonly ZField[];
46
+ /// Mutable: an un-renamed export list (`export { Task }`) exports a class
47
+ /// declared without the modifier.
48
+ exported: boolean;
49
+ promoted: boolean;
50
+ }
51
+
52
+ export interface UnionArm {
53
+ readonly tag: string;
54
+ /// Empty -> void arm; one field -> bare payload; several -> anonymous struct.
55
+ readonly fields: readonly ZField[];
56
+ }
57
+
58
+ export interface UnionInfo {
59
+ readonly name: string;
60
+ readonly decl: ts.TypeAliasDeclaration;
61
+ /// Filled in the second collection pass, like StructInfo.fields.
62
+ arms: readonly UnionArm[];
63
+ readonly exported: boolean;
64
+ }
65
+
66
+ export interface EnumInfo {
67
+ readonly name: string;
68
+ readonly decl: ts.TypeAliasDeclaration;
69
+ readonly members: readonly string[];
70
+ readonly exported: boolean;
71
+ }
72
+
73
+ export interface NumAliasInfo {
74
+ readonly name: string;
75
+ readonly decl: ts.TypeAliasDeclaration;
76
+ readonly repr: "u8" | "i64";
77
+ readonly values: readonly number[];
78
+ readonly exported: boolean;
79
+ }
80
+
81
+ /// A data class: the struct (registered in `structs` under the same name)
82
+ /// plus its behavior surface — the constructor `new` calls and the methods
83
+ /// that emit as module-level functions.
84
+ export interface ClassInfo {
85
+ readonly name: string;
86
+ readonly decl: ts.ClassDeclaration;
87
+ readonly ctor: ts.ConstructorDeclaration | null;
88
+ /// Instance methods (static methods are module-level functions, below).
89
+ readonly methods: readonly ts.MethodDeclaration[];
90
+ /// `static` methods: module-level functions under the class's mangled
91
+ /// names (`Task__fromRow`), no receiver.
92
+ readonly staticMethods: readonly ts.MethodDeclaration[];
93
+ /// `static readonly` fields with initializers: module consts under the
94
+ /// class's mangled names (`Task__LIMIT`). Mutable statics are taught
95
+ /// (module state, NS1010).
96
+ readonly staticConsts: readonly ts.PropertyDeclaration[];
97
+ /// Methods whose bodies (transitively) write `this` — pointer receivers;
98
+ /// call sites require a locally-owned instance.
99
+ readonly mutating: ReadonlySet<string>;
100
+ }
101
+
102
+ /// Whether a class member carries the `static` modifier.
103
+ export function isStaticMember(m: ts.ClassElement): boolean {
104
+ return ts.canHaveModifiers(m) && (ts.getModifiers(m) ?? []).some((x) => x.kind === ts.SyntaxKind.StaticKeyword);
105
+ }
106
+
107
+ export class TypeTable {
108
+ readonly structs = new Map<string, StructInfo>();
109
+ readonly classes = new Map<string, ClassInfo>();
110
+ readonly unions = new Map<string, UnionInfo>();
111
+ readonly enums = new Map<string, EnumInfo>();
112
+ readonly numAliases = new Map<string, NumAliasInfo>();
113
+ /// Aliases that resolve to bytes (e.g. `type Bytes = Uint8Array`).
114
+ readonly bytesAliases = new Set<string>();
115
+ /// Alias name -> aliased named type (plain `type A = B`).
116
+ readonly plainAliases = new Map<string, string>();
117
+ /// Aliases that resolve STRUCTURALLY through their type node under the
118
+ /// active type-parameter scope (`type Limit = typeof LIMIT` today).
119
+ readonly structuralAliases = new Map<string, ts.TypeNode>();
120
+ /// Generic templates: declared once, instantiated per concrete argument
121
+ /// list (`Box<Task>` -> the emitted struct `Box__Task`).
122
+ readonly genericStructTemplates = new Map<string, ts.InterfaceDeclaration>();
123
+ readonly genericAliasTemplates = new Map<string, ts.TypeAliasDeclaration>();
124
+ /// Instantiations created on demand, in creation order — the emitter
125
+ /// appends these as a generated-types section (Zig scope is order-free).
126
+ readonly instantiationOrder: string[] = [];
127
+ readonly declOrder: string[] = [];
128
+
129
+ /// The active type-parameter substitution (monomorphization): resolved
130
+ /// concrete type per TypeParameterDeclaration, keyed by declaration
131
+ /// identity. One scope at a time — instantiations emit serially.
132
+ private typeParamScope: ReadonlyMap<ts.Declaration, ZType> | null = null;
133
+
134
+ withTypeParams<T>(scope: ReadonlyMap<ts.Declaration, ZType> | null, run: () => T): T {
135
+ const prev = this.typeParamScope;
136
+ this.typeParamScope = scope;
137
+ try {
138
+ return run();
139
+ } finally {
140
+ this.typeParamScope = prev;
141
+ }
142
+ }
143
+
144
+ activeTypeParams(): ReadonlyMap<ts.Declaration, ZType> | null {
145
+ return this.typeParamScope;
146
+ }
147
+
148
+ private readonly tast: TypedAst;
149
+ /// The core's modules in canonical order (entry first) — one flat type
150
+ /// namespace across all of them (cross-file name collisions are the
151
+ /// checker's NS1038).
152
+ private readonly files: readonly ts.SourceFile[];
153
+
154
+ constructor(tast: TypedAst, files: readonly ts.SourceFile[] | ts.SourceFile) {
155
+ this.tast = tast;
156
+ this.files = Array.isArray(files) ? files : [files as ts.SourceFile];
157
+ // Two passes: names classify first (across every file), fields resolve
158
+ // second — a field's type may reference a type declared in a LATER
159
+ // file (`core.ts` holding a `readonly Item[]` of `tables.ts`'s Item),
160
+ // so resolution must see the whole namespace.
161
+ for (const file of this.files) this.classify(file);
162
+ for (const file of this.files) this.fill(file);
163
+ // An un-renamed export list over a class exports it exactly like the
164
+ // modifier would (renamed class exports are checker-taught NS1047).
165
+ for (const file of this.files) {
166
+ for (const b of exportListBindings(this.tast, file)) {
167
+ if (b.target && ts.isClassDeclaration(b.target) && !b.renamed && b.target.name) {
168
+ const info = this.structs.get(b.target.name.text);
169
+ if (info && info.decl === b.target) info.exported = true;
170
+ }
171
+ }
172
+ }
173
+ this.markPromotions();
174
+ }
175
+
176
+ private classify(file: ts.SourceFile): void {
177
+ for (const stmt of file.statements) {
178
+ if (ts.isClassDeclaration(stmt) && stmt.name) {
179
+ // A data class is a struct (its fields) plus module-level functions
180
+ // (constructor and methods). Ill-shaped classes (heritage, generics)
181
+ // are checker-taught; they stay out of the table so nothing emits
182
+ // against a shape the mapping does not carry.
183
+ if ((stmt.typeParameters && stmt.typeParameters.length > 0) || (stmt.heritageClauses && stmt.heritageClauses.length > 0)) {
184
+ continue;
185
+ }
186
+ const name = stmt.name.text;
187
+ this.structs.set(name, {
188
+ name,
189
+ decl: stmt,
190
+ fields: [],
191
+ exported: hasExportModifier(stmt),
192
+ promoted: true, // refined by markPromotions
193
+ });
194
+ const methods = stmt.members.filter(
195
+ (m): m is ts.MethodDeclaration => ts.isMethodDeclaration(m) && ts.isIdentifier(m.name) && !isStaticMember(m),
196
+ );
197
+ const staticMethods = stmt.members.filter(
198
+ (m): m is ts.MethodDeclaration => ts.isMethodDeclaration(m) && ts.isIdentifier(m.name) && isStaticMember(m),
199
+ );
200
+ const staticConsts = stmt.members.filter(
201
+ (m): m is ts.PropertyDeclaration =>
202
+ ts.isPropertyDeclaration(m) &&
203
+ ts.isIdentifier(m.name) &&
204
+ isStaticMember(m) &&
205
+ m.initializer !== undefined &&
206
+ (ts.getModifiers(m) ?? []).some((x) => x.kind === ts.SyntaxKind.ReadonlyKeyword),
207
+ );
208
+ const ctor =
209
+ stmt.members.find((m): m is ts.ConstructorDeclaration => ts.isConstructorDeclaration(m) && m.body !== undefined) ??
210
+ null;
211
+ this.classes.set(name, { name, decl: stmt, ctor, methods, staticMethods, staticConsts, mutating: mutatingMethodNames(stmt) });
212
+ this.declOrder.push(name);
213
+ continue;
214
+ }
215
+ if (ts.isInterfaceDeclaration(stmt)) {
216
+ const name = stmt.name.text;
217
+ if (stmt.typeParameters && stmt.typeParameters.length > 0) {
218
+ // A generic interface is a TEMPLATE: it emits nothing itself and
219
+ // instantiates per concrete argument list (`Box<Task>`).
220
+ this.genericStructTemplates.set(name, stmt);
221
+ continue;
222
+ }
223
+ this.structs.set(name, {
224
+ name,
225
+ decl: stmt,
226
+ fields: [],
227
+ exported: hasExportModifier(stmt),
228
+ promoted: true, // refined by markPromotions
229
+ });
230
+ this.declOrder.push(name);
231
+ } else if (ts.isTypeAliasDeclaration(stmt)) {
232
+ const name = stmt.name.text;
233
+ const exported = hasExportModifier(stmt);
234
+ if (stmt.typeParameters && stmt.typeParameters.length > 0) {
235
+ // A generic alias resolves structurally per instantiation:
236
+ // discriminated-union bodies become named instantiations, other
237
+ // bodies resolve straight through under the argument scope.
238
+ this.genericAliasTemplates.set(name, stmt);
239
+ continue;
240
+ }
241
+ if (ts.isTypeQueryNode(stmt.type)) {
242
+ // `type Limit = typeof LIMIT` — the alias resolves structurally
243
+ // through the checker's own type query (type-level only; the
244
+ // emitted slots carry the widened value type).
245
+ this.structuralAliases.set(name, stmt.type);
246
+ this.declOrder.push(name);
247
+ continue;
248
+ }
249
+ const strings = this.tast.stringLiteralUnionMembers(stmt.type);
250
+ if (strings) {
251
+ this.enums.set(name, { name, decl: stmt, members: strings, exported });
252
+ this.declOrder.push(name);
253
+ continue;
254
+ }
255
+ const numbers = this.tast.numberLiteralUnionMembers(stmt.type);
256
+ if (numbers) {
257
+ const repr = numbers.every((v) => Number.isInteger(v) && v >= 0 && v <= 255) ? "u8" : "i64";
258
+ this.numAliases.set(name, { name, decl: stmt, repr, values: numbers, exported });
259
+ this.declOrder.push(name);
260
+ continue;
261
+ }
262
+ const disc = this.tast.discriminatedUnionMembers(stmt.type, "kind");
263
+ if (disc) {
264
+ this.unions.set(name, { name, decl: stmt, arms: [], exported });
265
+ this.declOrder.push(name);
266
+ continue;
267
+ }
268
+ if (ts.isTypeReferenceNode(stmt.type) && ts.isIdentifier(stmt.type.typeName)) {
269
+ const target = stmt.type.typeName.text;
270
+ if (target === "Uint8Array") {
271
+ this.bytesAliases.add(name);
272
+ this.declOrder.push(name);
273
+ continue;
274
+ }
275
+ this.plainAliases.set(name, target);
276
+ this.declOrder.push(name);
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ private fill(file: ts.SourceFile): void {
283
+ for (const stmt of file.statements) {
284
+ if (ts.isClassDeclaration(stmt) && stmt.name) {
285
+ const info = this.structs.get(stmt.name.text);
286
+ if (info && info.decl === stmt) {
287
+ info.fields = this.tast.propsOfClass(stmt).map((p) => this.fieldOf(p));
288
+ }
289
+ } else if (ts.isInterfaceDeclaration(stmt)) {
290
+ const info = this.structs.get(stmt.name.text);
291
+ if (info && info.decl === stmt) {
292
+ info.fields = this.tast.propsOfInterface(stmt).map((p) => this.fieldOf(p));
293
+ }
294
+ } else if (ts.isTypeAliasDeclaration(stmt)) {
295
+ const info = this.unions.get(stmt.name.text);
296
+ if (info && info.decl === stmt) {
297
+ const disc = this.tast.discriminatedUnionMembers(stmt.type, "kind");
298
+ if (disc) {
299
+ info.arms = disc.map((m) => ({ tag: m.tag, fields: m.fields.map((p) => this.fieldOf(p)) }));
300
+ }
301
+ }
302
+ }
303
+ }
304
+ }
305
+
306
+ private fieldOf(p: PropInfo): ZField {
307
+ return {
308
+ tsName: p.name,
309
+ zigName: zigDeclName(p.name),
310
+ type: p.typeNode ? this.resolveTypeNode(p.typeNode) : { k: "void" },
311
+ decl: p.declaration,
312
+ };
313
+ }
314
+
315
+ /// R4: an interface is a by-value struct unless it is stored in the model
316
+ /// tree (Model and everything reachable from its fields), or is identity-
317
+ /// compared. When in doubt, stay a pointer.
318
+ private markPromotions(): void {
319
+ const pointerKind = new Set<string>();
320
+ const seenUnions = new Set<string>();
321
+ const visit = (t: ZType): void => {
322
+ switch (t.k) {
323
+ case "struct": {
324
+ if (pointerKind.has(t.name)) return;
325
+ pointerKind.add(t.name);
326
+ const info = this.structs.get(t.name);
327
+ if (info) for (const f of info.fields) visit(f.type);
328
+ return;
329
+ }
330
+ case "union": {
331
+ // A tagged union stored in the model tree keeps its by-value
332
+ // layout (the active arm lives inline), but every record its arms
333
+ // reference is model data and must be a heap node.
334
+ if (seenUnions.has(t.name)) return;
335
+ seenUnions.add(t.name);
336
+ const info = this.unions.get(t.name);
337
+ if (info) for (const arm of info.arms) for (const f of arm.fields) visit(f.type);
338
+ return;
339
+ }
340
+ case "slice":
341
+ return visit(t.elem);
342
+ case "optional":
343
+ return visit(t.inner);
344
+ default:
345
+ return;
346
+ }
347
+ };
348
+ const model = this.structs.get("Model");
349
+ if (model) visit({ k: "struct", name: "Model" });
350
+ // The text-input mirror contract is structural on the ZIG side too: the
351
+ // engines recognize a declared event union by its exact payload shapes
352
+ // (by-value selection/caret-move records) and TRANSLATE runtime events
353
+ // into it by constructing those records. A core that also stores the
354
+ // editor state in its Model (a perfectly idiomatic choice) would drag
355
+ // those records into pointer-kind here and silently break the mirror —
356
+ // so records referenced from a text-input-shaped union always stay
357
+ // by value (they are two-scalar records; by-value model storage is the
358
+ // promoted default everywhere else already).
359
+ for (const info of this.unions.values()) {
360
+ if (!isTextInputMirror(info)) continue;
361
+ for (const arm of info.arms) {
362
+ for (const f of arm.fields) {
363
+ if (f.type.k === "struct") pointerKind.delete(f.type.name);
364
+ }
365
+ }
366
+ }
367
+ for (const name of pointerKind) {
368
+ const info = this.structs.get(name);
369
+ if (info) info.promoted = false;
370
+ }
371
+ }
372
+
373
+ isPointerStruct(name: string): boolean {
374
+ const info = this.structs.get(name);
375
+ return info !== undefined && !info.promoted;
376
+ }
377
+
378
+ /// Exported single-Model-parameter helpers with a mapped return type:
379
+ /// each also emits as a forwarding declaration on the Model struct (the
380
+ /// markup fn-backed-scalar shape), under its own TS name — markup binds
381
+ /// `doneCount` as `{doneCount}`. The reserved entry points
382
+ /// (update/initialModel/subscriptions) never forward. Shared by the
383
+ /// checker (NS1031/NS1032) and the emitter.
384
+ ///
385
+ /// ENTRY-ONLY on purpose: under node the app's module object is the
386
+ /// entry's exports, so a helper exported from an imported module would
387
+ /// bind natively but not exist under node. An imported module's export
388
+ /// is cross-module API (`nextTrackId` for update to call), never a
389
+ /// markup binding — put binding helpers in core.ts.
390
+ modelHelperDecls(): { name: string; zigName: string; decl: ts.FunctionDeclaration }[] {
391
+ const out: { name: string; zigName: string; decl: ts.FunctionDeclaration }[] = [];
392
+ if (!this.structs.has("Model")) return out;
393
+ for (const stmt of this.files[0].statements) {
394
+ if (!ts.isFunctionDeclaration(stmt) || !stmt.name || !hasExportModifier(stmt)) continue;
395
+ if (!this.isModelHelperShape(stmt, stmt.name.text)) continue;
396
+ out.push({ name: stmt.name.text, zigName: zigDeclName(stmt.name.text), decl: stmt });
397
+ }
398
+ // Export-list bindings join the surface under their EXPORTED names —
399
+ // only where the declaration itself is entry-module (the entry-only
400
+ // rule above holds: a re-exported imported helper would bind natively
401
+ // but not exist on node's entry module object).
402
+ for (const b of exportListBindings(this.tast, this.files[0])) {
403
+ const t = b.target;
404
+ if (!t || !ts.isFunctionDeclaration(t) || t.getSourceFile() !== this.files[0]) continue;
405
+ if (!this.isModelHelperShape(t, b.exportedName)) continue;
406
+ if (out.some((h) => h.name === b.exportedName && h.decl === t)) continue;
407
+ out.push({ name: b.exportedName, zigName: zigDeclName(b.exportedName), decl: t });
408
+ }
409
+ return out;
410
+ }
411
+
412
+ /// The single-Model-parameter derived-value shape, under the name the
413
+ /// helper is exported as (the reserved entry points never forward).
414
+ private isModelHelperShape(stmt: ts.FunctionDeclaration, exportedName: string): boolean {
415
+ if (exportedName === "update" || exportedName === "initialModel" || exportedName === "subscriptions") return false;
416
+ if (stmt.parameters.length !== 1) return false;
417
+ const p = stmt.parameters[0];
418
+ if (!p.type || !stmt.type) return false;
419
+ const pt = this.resolveTypeNode(p.type);
420
+ if (pt.k !== "struct" || pt.name !== "Model") return false;
421
+ return this.resolveTypeNode(stmt.type).k !== "void";
422
+ }
423
+
424
+ resolveName(name: string): ZType | null {
425
+ const seen = new Set<string>();
426
+ let cur = name;
427
+ while (this.plainAliases.has(cur) && !seen.has(cur)) {
428
+ seen.add(cur);
429
+ cur = this.plainAliases.get(cur)!;
430
+ }
431
+ const structural = this.structuralAliases.get(cur);
432
+ if (structural) return this.resolveTypeNode(structural);
433
+ if (this.bytesAliases.has(cur)) return { k: "bytes" };
434
+ if (this.structs.has(cur)) return { k: "struct", name: cur };
435
+ if (this.unions.has(cur)) return { k: "union", name: cur };
436
+ if (this.enums.has(cur)) return { k: "enum", name: cur, members: this.enums.get(cur)!.members };
437
+ if (this.numAliases.has(cur)) {
438
+ const a = this.numAliases.get(cur)!;
439
+ return { k: "numAlias", name: cur, repr: a.repr, values: a.values };
440
+ }
441
+ if (cur === "Uint8Array") return { k: "bytes" };
442
+ return null;
443
+ }
444
+
445
+ resolveTypeNode(node: ts.TypeNode): ZType {
446
+ switch (node.kind) {
447
+ case ts.SyntaxKind.NumberKeyword:
448
+ return { k: "number" };
449
+ case ts.SyntaxKind.BooleanKeyword:
450
+ return { k: "bool" };
451
+ case ts.SyntaxKind.StringKeyword:
452
+ return { k: "string" };
453
+ case ts.SyntaxKind.VoidKeyword:
454
+ return { k: "void" };
455
+ default:
456
+ break;
457
+ }
458
+ if (ts.isParenthesizedTypeNode(node)) return this.resolveTypeNode(node.type);
459
+ if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) {
460
+ // A single string-literal type (`kind: "parse"` on an error record):
461
+ // the field holds exactly that literal, stored as rodata text — what
462
+ // lets an interface with a literal `kind` field exist as a struct and
463
+ // contribute its arm to the thrown union.
464
+ return { k: "string" };
465
+ }
466
+ if (ts.isTypeQueryNode(node)) {
467
+ // `typeof CONST` — the checker's own type query, widened to the
468
+ // value's slot type (type-level only; erases under node identically).
469
+ return this.zTypeOfTsType(this.tast.typeFromTypeNode(node)) ?? { k: "void" };
470
+ }
471
+ if (ts.isUnionTypeNode(node)) {
472
+ const nonNull = node.types.filter(
473
+ (t) =>
474
+ !(ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword) &&
475
+ t.kind !== ts.SyntaxKind.UndefinedKeyword,
476
+ );
477
+ if (nonNull.length === 1 && nonNull.length !== node.types.length) {
478
+ return { k: "optional", inner: this.resolveTypeNode(nonNull[0]) };
479
+ }
480
+ // Non-null inline unions must be named aliases (enum/tagged union).
481
+ return { k: "void" };
482
+ }
483
+ if (ts.isArrayTypeNode(node)) {
484
+ return { k: "slice", elem: this.resolveTypeNode(node.elementType) };
485
+ }
486
+ if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) {
487
+ return this.resolveTypeNode(node.type);
488
+ }
489
+ if (ts.isTypeReferenceNode(node) && ts.isQualifiedName(node.typeName)) {
490
+ // `ns.Config` through a namespace import: the alias erases and type
491
+ // names are unique across the core's files (NS1038), so the right
492
+ // side resolves directly against the table (declaration identity
493
+ // covers a re-aliased name).
494
+ const named = this.resolveName(node.typeName.right.text);
495
+ if (named) return named;
496
+ const decl = this.tast.declarationOf(node.typeName.right);
497
+ if (decl && (ts.isInterfaceDeclaration(decl) || ts.isTypeAliasDeclaration(decl))) {
498
+ const byDecl = this.resolveName(decl.name.text);
499
+ if (byDecl) return byDecl;
500
+ }
501
+ return { k: "void" };
502
+ }
503
+ if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
504
+ const name = node.typeName.text;
505
+ if (name === "ReadonlyArray" || name === "Array") {
506
+ const arg = node.typeArguments?.[0];
507
+ return { k: "slice", elem: arg ? this.resolveTypeNode(arg) : { k: "void" } };
508
+ }
509
+ const decl = this.tast.declarationOf(node.typeName);
510
+ // A type-parameter reference resolves through the active
511
+ // monomorphization scope (`T` -> the instantiation's concrete type).
512
+ if (decl && ts.isTypeParameterDeclaration(decl)) {
513
+ return this.typeParamScope?.get(decl) ?? { k: "void" };
514
+ }
515
+ // A generic template instantiates per concrete argument list.
516
+ const templateName = decl && (ts.isInterfaceDeclaration(decl) || ts.isTypeAliasDeclaration(decl)) ? decl.name.text : name;
517
+ const structTemplate = this.genericStructTemplates.get(templateName);
518
+ if (structTemplate) {
519
+ return this.instantiateStruct(structTemplate, (node.typeArguments ?? []).map((a) => this.resolveTypeNode(a)));
520
+ }
521
+ const aliasTemplate = this.genericAliasTemplates.get(templateName);
522
+ if (aliasTemplate) {
523
+ return this.instantiateAlias(aliasTemplate, (node.typeArguments ?? []).map((a) => this.resolveTypeNode(a)));
524
+ }
525
+ const named = this.resolveName(name);
526
+ if (named) return named;
527
+ // A renamed import (`import { Row as R }`): resolve through the
528
+ // symbol to the declared name — the table is keyed by declarations.
529
+ if (decl && (ts.isInterfaceDeclaration(decl) || ts.isTypeAliasDeclaration(decl)) && decl.name.text !== name) {
530
+ const byDecl = this.resolveName(decl.name.text);
531
+ if (byDecl) return byDecl;
532
+ }
533
+ }
534
+ return { k: "void" };
535
+ }
536
+
537
+ /// One concrete instantiation of a generic interface: a named struct per
538
+ /// distinct argument list (`Box<Task>` -> `Box__Task`), deduped by name.
539
+ /// Fields resolve under the template's parameter scope; a recursive
540
+ /// reference lands on the already-registered name.
541
+ instantiateStruct(template: ts.InterfaceDeclaration, args: readonly ZType[]): ZType {
542
+ if (args.length === 0 || args.some((a) => a.k === "void")) return { k: "void" };
543
+ const name = `${template.name.text}__${args.map(mangleZType).join("__")}`;
544
+ if (!this.structs.has(name)) {
545
+ const scope = new Map<ts.Declaration, ZType>();
546
+ template.typeParameters!.forEach((tp, i) => scope.set(tp, args[i] ?? { k: "void" }));
547
+ const info: StructInfo = {
548
+ name,
549
+ decl: template,
550
+ fields: [],
551
+ exported: hasExportModifier(template),
552
+ promoted: true, // instantiations follow the same promotion pass when model-reachable
553
+ };
554
+ this.structs.set(name, info);
555
+ this.instantiationOrder.push(name);
556
+ info.fields = this.withTypeParams(scope, () => this.tast.propsOfInterface(template).map((p) => this.fieldOf(p)));
557
+ }
558
+ return { k: "struct", name };
559
+ }
560
+
561
+ /// One concrete instantiation of a generic type alias. A discriminated
562
+ /// union body becomes a named union instantiation; every other body
563
+ /// (optionals, arrays, plain compositions) resolves structurally under
564
+ /// the argument scope.
565
+ instantiateAlias(template: ts.TypeAliasDeclaration, args: readonly ZType[]): ZType {
566
+ if (args.length === 0 || args.some((a) => a.k === "void")) return { k: "void" };
567
+ const scope = new Map<ts.Declaration, ZType>();
568
+ template.typeParameters!.forEach((tp, i) => scope.set(tp, args[i] ?? { k: "void" }));
569
+ const disc = this.tast.discriminatedUnionMembers(template.type, "kind");
570
+ if (!disc) {
571
+ return this.withTypeParams(scope, () => this.resolveTypeNode(template.type));
572
+ }
573
+ const name = `${template.name.text}__${args.map(mangleZType).join("__")}`;
574
+ if (!this.unions.has(name)) {
575
+ const info: UnionInfo = { name, decl: template, arms: [], exported: hasExportModifier(template) };
576
+ this.unions.set(name, info);
577
+ this.instantiationOrder.push(name);
578
+ info.arms = this.withTypeParams(scope, () =>
579
+ disc.map((m) => ({ tag: m.tag, fields: m.fields.map((p) => this.fieldOf(p)) })),
580
+ );
581
+ }
582
+ return { k: "union", name };
583
+ }
584
+
585
+ /// ts.Type -> ZType: the resolved-type side of the mapping, used where a
586
+ /// type arrives from the checker instead of a syntax node (type queries,
587
+ /// resolved generic arguments). Returns null for types with no mapping.
588
+ zTypeOfTsType(t: import("./typed_ast.ts").Type): ZType | null {
589
+ // A still-generic type parameter resolves through the active scope
590
+ // (generics calling generics inside a template body).
591
+ if ((t.flags & ts.TypeFlags.TypeParameter) !== 0) {
592
+ const decl = t.symbol?.declarations?.[0];
593
+ const mapped = decl ? this.typeParamScope?.get(decl) : undefined;
594
+ return mapped ?? null;
595
+ }
596
+ // A named generic-alias instantiation (`Opt<Task>`) resolves through
597
+ // its template under the resolved-argument scope.
598
+ if (t.aliasSymbol) {
599
+ const aliasName = t.aliasSymbol.name;
600
+ const aliasTemplate = this.genericAliasTemplates.get(aliasName);
601
+ if (aliasTemplate) {
602
+ const args: ZType[] = [];
603
+ for (const a of t.aliasTypeArguments ?? []) {
604
+ const z = this.zTypeOfTsType(a);
605
+ if (!z) return null;
606
+ args.push(z);
607
+ }
608
+ return this.instantiateAlias(aliasTemplate, args);
609
+ }
610
+ const named = this.resolveName(aliasName);
611
+ if (named) return named;
612
+ }
613
+ if ((t.flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) !== 0) return { k: "number" };
614
+ if ((t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0) return { k: "bool" };
615
+ if ((t.flags & (ts.TypeFlags.String | ts.TypeFlags.StringLiteral)) !== 0) return { k: "string" };
616
+ if (t.isUnion()) {
617
+ const members = t.types;
618
+ if (members.every((m) => (m.flags & (ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Boolean)) !== 0)) {
619
+ return { k: "bool" };
620
+ }
621
+ const nonNull = members.filter((m) => (m.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) === 0);
622
+ if (nonNull.length < members.length && nonNull.length >= 1) {
623
+ const inner = this.zTypeOfNonNullMembers(nonNull);
624
+ if (!inner) return null;
625
+ return inner.k === "optional" ? inner : { k: "optional", inner };
626
+ }
627
+ return this.zTypeOfNonNullMembers(nonNull);
628
+ }
629
+ return this.zTypeOfObjectType(t);
630
+ }
631
+
632
+ /// The non-null members of a resolved union, mapped as one type. A
633
+ /// single member maps directly; several string literals recover their
634
+ /// declared enum by exact member set (tsc flattens `Filter | null`, so
635
+ /// the alias name is gone by here); several number literals widen to the
636
+ /// number slot type; anything else has no single mapping.
637
+ private zTypeOfNonNullMembers(members: readonly import("./typed_ast.ts").Type[]): ZType | null {
638
+ if (members.length === 0) return null;
639
+ if (members.length === 1) return this.zTypeOfTsType(members[0]);
640
+ if (members.every((m) => m.isStringLiteral())) {
641
+ const set = new Set(members.map((m) => (m as { value: string }).value));
642
+ for (const en of this.enums.values()) {
643
+ if (en.members.length === set.size && en.members.every((x) => set.has(x))) {
644
+ return { k: "enum", name: en.name, members: en.members };
645
+ }
646
+ }
647
+ return null;
648
+ }
649
+ if (members.every((m) => (m.flags & (ts.TypeFlags.NumberLiteral | ts.TypeFlags.Number)) !== 0)) {
650
+ // An unnamed number-literal union widens to its slot type; named
651
+ // aliases resolve through resolveName before this point.
652
+ return { k: "number" };
653
+ }
654
+ return null;
655
+ }
656
+
657
+ private zTypeOfObjectType(t: import("./typed_ast.ts").Type): ZType | null {
658
+ const symName = t.symbol?.name;
659
+ if (symName === "Uint8Array") return { k: "bytes" };
660
+ if (this.tast.isArrayLikeType(t)) {
661
+ const elem = this.tast.typeArgumentsOf(t)[0];
662
+ const inner = elem ? this.zTypeOfTsType(elem) : null;
663
+ return inner ? { k: "slice", elem: inner } : null;
664
+ }
665
+ if (symName) {
666
+ const structTemplate = this.genericStructTemplates.get(symName);
667
+ if (structTemplate) {
668
+ const args: ZType[] = [];
669
+ for (const a of this.tast.typeArgumentsOf(t)) {
670
+ const z = this.zTypeOfTsType(a);
671
+ if (!z) return null;
672
+ args.push(z);
673
+ }
674
+ const inst = this.instantiateStruct(structTemplate, args);
675
+ return inst.k === "void" ? null : inst;
676
+ }
677
+ const named = this.resolveName(symName);
678
+ if (named) return named;
679
+ }
680
+ return null;
681
+ }
682
+
683
+ /// The Zig type reference for a resolved type, in field/param position.
684
+ zigTypeRef(t: ZType): string {
685
+ switch (t.k) {
686
+ case "number":
687
+ // Positions the slot inference does not cover (e.g. number-array
688
+ // elements) stay f64 — the JS-faithful conservative default (R2).
689
+ return "f64";
690
+ case "i64":
691
+ return "i64";
692
+ case "f64":
693
+ return "f64";
694
+ case "bool":
695
+ return "bool";
696
+ case "void":
697
+ return "void";
698
+ case "bytes":
699
+ case "string":
700
+ return this.bytesAliases.has("Bytes") ? "Bytes" : "[]const u8";
701
+ case "numAlias":
702
+ return t.name;
703
+ case "enum":
704
+ return t.name;
705
+ case "union":
706
+ return t.name;
707
+ case "struct":
708
+ return this.isPointerStruct(t.name) ? `*const ${t.name}` : t.name;
709
+ case "slice":
710
+ return `[]const ${this.zigTypeRef(t.elem)}`;
711
+ case "optional":
712
+ return `?${this.zigTypeRef(t.inner)}`;
713
+ }
714
+ }
715
+ }
716
+
717
+ /// The canvas text-input event vocabulary — a union carrying exactly these
718
+ /// eleven tags is the declared mirror the markup engines resolve `on-input`
719
+ /// through (matched structurally on the Zig side; see
720
+ /// ui_markup_reflect.declaredTextInputUnion).
721
+ const textInputMirrorTags = [
722
+ "insert_text",
723
+ "delete_backward",
724
+ "delete_forward",
725
+ "delete_word_backward",
726
+ "delete_word_forward",
727
+ "clear",
728
+ "move_caret",
729
+ "set_selection",
730
+ "set_composition",
731
+ "commit_composition",
732
+ "cancel_composition",
733
+ ];
734
+
735
+ function isTextInputMirror(info: { arms: readonly UnionArm[] }): boolean {
736
+ if (info.arms.length !== textInputMirrorTags.length) return false;
737
+ const tags = new Set(info.arms.map((a) => a.tag));
738
+ return textInputMirrorTags.every((tag) => tags.has(tag));
739
+ }
740
+
741
+ const zigReserved = new Set([
742
+ "error", "var", "const", "fn", "type", "test", "struct", "union", "enum", "opaque",
743
+ "align", "and", "or", "orelse", "return", "break", "continue", "defer", "errdefer",
744
+ "if", "else", "switch", "while", "for", "try", "catch", "pub", "export", "extern",
745
+ "inline", "noalias", "comptime", "unreachable", "undefined", "null", "true", "false",
746
+ "anytype", "async", "await", "resume", "suspend", "nosuspend", "threadlocal", "volatile",
747
+ "packed", "linksection", "callconv", "usingnamespace", "asm",
748
+ ]);
749
+
750
+ /// Readable monomorphization mangle: one emitted name component per
751
+ /// resolved type argument (`pick__Task`, `pick__f64`, `Box__Task`).
752
+ export function mangleZType(t: ZType): string {
753
+ switch (t.k) {
754
+ case "number":
755
+ case "f64":
756
+ return "f64";
757
+ case "i64":
758
+ return "i64";
759
+ case "bool":
760
+ return "bool";
761
+ case "bytes":
762
+ return "bytes";
763
+ case "string":
764
+ return "str";
765
+ case "void":
766
+ return "void";
767
+ case "numAlias":
768
+ case "enum":
769
+ case "struct":
770
+ case "union":
771
+ return t.name;
772
+ case "slice":
773
+ return `arr_${mangleZType(t.elem)}`;
774
+ case "optional":
775
+ return `opt_${mangleZType(t.inner)}`;
776
+ }
777
+ }
778
+
779
+ /// Emitted-name policy: your names are your names. A TS identifier passes
780
+ /// through verbatim, so the emitted Zig mirrors the source and markup binds
781
+ /// the model's field names exactly as written (`{nextId}`, `{doneCount}`).
782
+ ///
783
+ /// `zigDeclName` covers the binding surface (struct/union fields and Model
784
+ /// forwarding decls): a name that collides with a Zig keyword or primitive
785
+ /// type is @"..."-quoted, which keeps the reflected name — and therefore the
786
+ /// markup binding — byte-for-byte the TS name.
787
+ export function zigDeclName(name: string): string {
788
+ if (zigReserved.has(name) || isZigPrimitiveName(name) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
789
+ return `@"${name}"`;
790
+ }
791
+ return name;
792
+ }
793
+
794
+ /// `zigLocalName` covers locals and parameters (never a binding surface):
795
+ /// verbatim, with the trailing-underscore convention for Zig keywords —
796
+ /// locals go through the uniqueness suffixer, which cannot suffix a
797
+ /// @"..."-quoted name.
798
+ export function zigLocalName(name: string): string {
799
+ return zigReserved.has(name) ? `${name}_` : name;
800
+ }
801
+
802
+ /// Variable names that would shadow a Zig primitive type (i2, u8, f64, ...).
803
+ export function isZigPrimitiveName(name: string): boolean {
804
+ return /^([iu]\d+|f(16|32|64|80|128)|c_\w+|isize|usize|bool|void|comptime_(int|float)|any(opaque|error|frame|type)|noreturn)$/.test(
805
+ name,
806
+ );
807
+ }
808
+
809
+ /// Generated-file stems only (module-prefix disambiguation): camelCase ->
810
+ /// snake_case. User identifiers never pass through here.
811
+ export function snakeCase(name: string): string {
812
+ if (name.toUpperCase() === name) return name; // SCREAMING_CASE constants pass through
813
+ const out = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
814
+ return zigReserved.has(out) ? `${out}_` : out;
815
+ }