@native-sdk/cli 0.4.4 → 0.5.1

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 (94) hide show
  1. package/build/app.zig +371 -5
  2. package/build/ts_run.mjs +102 -0
  3. package/build.zig +255 -1
  4. package/build.zig.zon +1 -0
  5. package/package.json +19 -10
  6. package/packages/core/package-lock.json +44 -0
  7. package/packages/core/package.json +38 -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 +546 -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/platform/windows/webview2_host.cpp +24 -0
  33. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  34. package/src/primitives/app_manifest/root.zig +5 -0
  35. package/src/primitives/canvas/commands.zig +14 -7
  36. package/src/primitives/canvas/layout_audit.zig +5 -5
  37. package/src/primitives/canvas/lazy_tls.zig +73 -0
  38. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  39. package/src/primitives/canvas/root.zig +11 -0
  40. package/src/primitives/canvas/tests.zig +1 -0
  41. package/src/primitives/canvas/text_atlas.zig +40 -32
  42. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  43. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  44. package/src/primitives/canvas/text_spans.zig +39 -26
  45. package/src/primitives/canvas/tokens.zig +69 -0
  46. package/src/primitives/canvas/ui.zig +125 -0
  47. package/src/primitives/canvas/ui_markup.zig +22 -3
  48. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  49. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  50. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  51. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  52. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  53. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  54. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  55. package/src/primitives/canvas/ui_schema.zig +8 -0
  56. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  57. package/src/primitives/canvas/widget_builtin_tests.zig +309 -5
  58. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  59. package/src/primitives/canvas/widget_layout.zig +138 -2
  60. package/src/primitives/canvas/widget_metrics.zig +16 -8
  61. package/src/primitives/canvas/widget_render.zig +25 -15
  62. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  63. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  64. package/src/root.zig +7 -0
  65. package/src/runtime/canvas_frame.zig +57 -36
  66. package/src/runtime/canvas_images.zig +9 -3
  67. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  68. package/src/runtime/canvas_widget_runtime.zig +7 -4
  69. package/src/runtime/core.zig +16 -0
  70. package/src/runtime/effects.zig +1525 -133
  71. package/src/runtime/effects_fetch_tests.zig +42 -0
  72. package/src/runtime/effects_file_tests.zig +220 -0
  73. package/src/runtime/effects_host_tests.zig +594 -0
  74. package/src/runtime/effects_tests.zig +287 -0
  75. package/src/runtime/root.zig +18 -0
  76. package/src/runtime/session_replay.zig +7 -1
  77. package/src/runtime/tests.zig +2 -0
  78. package/src/runtime/ts_core_host.zig +1505 -0
  79. package/src/runtime/ts_core_host_tests.zig +1408 -0
  80. package/src/runtime/ts_ui_app.zig +469 -0
  81. package/src/runtime/ui_app.zig +189 -38
  82. package/src/runtime/ui_app_tests.zig +221 -0
  83. package/src/runtime/ui_app_window_tests.zig +182 -0
  84. package/src/runtime/view_canvas.zig +24 -17
  85. package/src/runtime/view_widget_tree.zig +2 -2
  86. package/src/tooling/codesign.zig +212 -105
  87. package/src/tooling/doctor.zig +78 -0
  88. package/src/tooling/manifest.zig +47 -0
  89. package/src/tooling/package.zig +435 -20
  90. package/src/tooling/raw_manifest.zig +15 -0
  91. package/src/tooling/root.zig +1 -0
  92. package/src/tooling/templates.zig +777 -34
  93. package/src/tooling/ts_core.zig +1099 -0
  94. package/src/tooling/verbs.zig +105 -2
package/build/app.zig CHANGED
@@ -42,6 +42,294 @@ pub const AppOptions = struct {
42
42
  app_root: []const u8 = ".",
43
43
  };
44
44
 
45
+ /// Which core the app tree carries. No flag and no config anywhere: the
46
+ /// tree IS the truth — `src/core.ts` is a TypeScript core (transpiled at
47
+ /// build time, run through generated wiring), `src/main.zig` a Zig one,
48
+ /// and both at once is a teaching error naming the two files.
49
+ const CoreTree = enum { zig, ts, both, neither };
50
+
51
+ fn detectCoreTree(b: *std.Build, app_root: []const u8) CoreTree {
52
+ const has_ts = appFileExists(b, app_root, "src/core.ts");
53
+ const has_zig = appFileExists(b, app_root, "src/main.zig");
54
+ if (has_ts and has_zig) return .both;
55
+ if (has_ts) return .ts;
56
+ if (has_zig) return .zig;
57
+ return .neither;
58
+ }
59
+
60
+ fn appFileExists(b: *std.Build, app_root: []const u8, sub_path: []const u8) bool {
61
+ b.build_root.handle.access(b.graph.io, appPath(b, app_root, sub_path), .{}) catch return false;
62
+ return true;
63
+ }
64
+
65
+ /// The staged TypeScript-core wiring: one generated directory holding the
66
+ /// transpiled core (core.zig), its rt kernel, the app's markup, and the
67
+ /// SDK's generated-wiring entry (ts_core_main.zig as main.zig). Built once
68
+ /// per app build and shared by the exe and test modules.
69
+ const TsCoreStage = struct {
70
+ main_root: std.Build.LazyPath,
71
+ };
72
+
73
+ /// Whether the transpiler's TypeScript compiler (@typescript/old, the
74
+ /// exactly pinned npm alias of the real `typescript` package) RESOLVES
75
+ /// from the SDK's packages/core, by node's ancestor node_modules walk —
76
+ /// at the SDK's exactly pinned VERSION. The same semantics the CLI gates
77
+ /// on (src/tooling/ts_core.zig
78
+ /// transpilerResolution, this predicate's deliberate twin: keep the two
79
+ /// in lockstep).
80
+ ///
81
+ /// Validation tracks ONLY what runtime loads, from the same origin
82
+ /// runtime resolves from: typed_ast.ts imports "@typescript/old" directly
83
+ /// and build/ts_run.mjs's load hook requires it from the target
84
+ /// packages/core/src module — src/ never carries a node_modules, so
85
+ /// packages/core is the walk origin that mirrors both. Covers every
86
+ /// layout: a repo checkout's packages/core/node_modules (nearest wins),
87
+ /// and the npm-installed CLI whose own `dependencies` carry the alias
88
+ /// (nested under the package on global prefixes, hoisted to the project
89
+ /// root on local ones, pnpm's sibling node_modules).
90
+ ///
91
+ /// The @typescript/typescript6 wrapper is deliberately NOT probed:
92
+ /// nothing imports it at run time (typed_ast.ts bypasses its one-line
93
+ /// re-export on purpose), so holding the wrapper's resolution — or the
94
+ /// alias's version as seen FROM the wrapper's origin — against the pin
95
+ /// can only FALSE-REJECT healthy trees: npm's own conflict shape hoists
96
+ /// a consumer's conflicting `@typescript/old` at the project root while
97
+ /// our exact pin lands nested under the CLI, which is precisely the copy
98
+ /// runtime loads from packages/core; a consumer's own shadowing wrapper
99
+ /// must not sway the verdict either. The wrapper stays a DECLARED
100
+ /// dependency in both manifests — it is just not what validation vouches
101
+ /// for (see the twin's doc comment).
102
+ ///
103
+ /// Resolvable means the alias's manifest AND its entrypoint are present
104
+ /// (see tsAliasedCompilerVersion for node's error shape and the
105
+ /// mid-extraction slivers) and its installed version equals the pin —
106
+ /// read from the SDK dependency's own packages/core/package.json (the
107
+ /// `npm:typescript@X.Y.Z` alias suffix in devDependencies —
108
+ /// tsParseAliasedCompilerPin, mirroring the twin's
109
+ /// parseAliasedCompilerPin), never hardcoded, so version bumps stay a
110
+ /// one-file change.
111
+ const TsToolchainResolution = union(enum) {
112
+ resolved,
113
+ unresolved,
114
+ /// The aliased compiler resolves, but at a version other than the
115
+ /// SDK's exact pin (strings allocated on b.allocator, freed never —
116
+ /// this is configure-time teaching data).
117
+ version_mismatch: struct { resolved: []const u8, pinned: []const u8 },
118
+ };
119
+
120
+ fn tsToolchainResolution(b: *std.Build, dep: *std.Build.Dependency) TsToolchainResolution {
121
+ const sdk_root = tsSdkRoot(b.allocator, b.graph.io, dep);
122
+ // The pin first: an SDK tree whose packages/core/package.json is
123
+ // missing or pinless is not one this gate can vouch for (the file
124
+ // ships in every layout), so it concludes unresolved and the teaching
125
+ // path acts.
126
+ const pinned = tsPinnedCompilerVersion(b, sdk_root) orelse return .unresolved;
127
+ const resolved = tsAliasedCompilerVersion(b, b.pathJoin(&.{ sdk_root, "packages", "core" })) orelse return .unresolved;
128
+ if (std.mem.eql(u8, resolved, pinned)) return .resolved;
129
+ return .{ .version_mismatch = .{ .resolved = resolved, .pinned = pinned } };
130
+ }
131
+
132
+ /// How runtime's `import "@typescript/old"` resolves, by node's walk FROM
133
+ /// `origin_dir` upward: the nearest ancestor
134
+ /// `node_modules/@typescript/old` wins (skipping ancestors that are
135
+ /// themselves a node_modules directory, as node does). Callers pass the
136
+ /// SDK's packages/core — the origin typed_ast.ts and ts_run.mjs resolve
137
+ /// the alias from. The walk must be a real ancestor walk, not a
138
+ /// fixed-sibling probe: npm hoists the alias to the install root on flat
139
+ /// layouts and nests it under the CLI on version conflicts. Resolvable
140
+ /// means the alias's manifest AND its entrypoint — the alias is the real
141
+ /// `typescript` package, whose `"main"` is ./lib/typescript.js (no
142
+ /// `"exports"`): a bare directory (an interrupted install, a pruned
143
+ /// node_modules) is MODULE_NOT_FOUND at run time, and a manifest without
144
+ /// its entrypoint (npm extraction is not atomic; package.json rides
145
+ /// first in the tarball) fails just as opaquely. Hardcoding it is safe
146
+ /// because the alias is exactly pinned (`npm:typescript@X.Y.Z` in both
147
+ /// manifests plus the lockfile) and drift-checked by check-version-sync.
148
+ /// A manifest without its entrypoint THROWS in node rather than
149
+ /// consulting a deeper ancestor, so it concludes unresolvable here too
150
+ /// (this predicate's deliberate twin: src/tooling/ts_core.zig's
151
+ /// aliasedCompilerVersion — keep the two in lockstep).
152
+ ///
153
+ /// Returns the resolved alias's installed VERSION so the caller can hold
154
+ /// it against the SDK's pin; a resolvable-looking alias whose manifest
155
+ /// carries no version field returns null (every real npm install writes
156
+ /// one — its absence is a corrupt sliver, not a compiler to vouch for).
157
+ fn tsAliasedCompilerVersion(b: *std.Build, origin_dir: []const u8) ?[]const u8 {
158
+ const io = b.graph.io;
159
+ var dir: []const u8 = origin_dir;
160
+ while (true) {
161
+ if (!std.mem.eql(u8, std.fs.path.basename(dir), "node_modules")) {
162
+ found: {
163
+ const manifest_path = b.pathJoin(&.{ dir, "node_modules", "@typescript", "old", "package.json" });
164
+ std.Io.Dir.cwd().access(io, manifest_path, .{}) catch break :found;
165
+ std.Io.Dir.cwd().access(io, b.pathJoin(&.{ dir, "node_modules", "@typescript", "old", "lib", "typescript.js" }), .{}) catch return null;
166
+ const manifest = std.Io.Dir.cwd().readFileAlloc(io, manifest_path, b.allocator, .limited(64 * 1024)) catch return null;
167
+ return tsParseQuotedManifestValue(manifest, "\"version\"", "");
168
+ }
169
+ }
170
+ dir = std.fs.path.dirname(dir) orelse return null;
171
+ }
172
+ }
173
+
174
+ /// The version the SDK pins its aliased compiler to, read from the SDK
175
+ /// dependency's own packages/core/package.json — the same manifest the
176
+ /// CLI's gate reads, so both surfaces learn a version bump from one file.
177
+ fn tsPinnedCompilerVersion(b: *std.Build, sdk_root: []const u8) ?[]const u8 {
178
+ const manifest = std.Io.Dir.cwd().readFileAlloc(b.graph.io, b.pathJoin(&.{ sdk_root, "packages", "core", "package.json" }), b.allocator, .limited(64 * 1024)) catch return null;
179
+ const pin = tsParseQuotedManifestValue(manifest, "\"@typescript/old\"", "npm:typescript@") orelse return null;
180
+ // Exact X.Y.Z only (check-version-sync's pin shape), mirroring the
181
+ // twin's parseAliasedCompilerPin: a range is not a pin.
182
+ if (pin.len == 0) return null;
183
+ for (pin) |c| {
184
+ if (!std.ascii.isDigit(c) and c != '.') return null;
185
+ }
186
+ if (std.mem.count(u8, pin, ".") != 2) return null;
187
+ return pin;
188
+ }
189
+
190
+ /// Targeted scan for a manifest key's string value (the twin of
191
+ /// ts_core.zig's parsePackageVersion/parseAliasedCompilerPin scanners):
192
+ /// find `key`, expect `: "<required_prefix><value>"`, return `value`.
193
+ fn tsParseQuotedManifestValue(manifest_json: []const u8, comptime key: []const u8, comptime required_prefix: []const u8) ?[]const u8 {
194
+ const key_at = std.mem.indexOf(u8, manifest_json, key) orelse return null;
195
+ var rest = manifest_json[key_at + key.len ..];
196
+ rest = std.mem.trimStart(u8, rest, " \t\r\n");
197
+ if (rest.len == 0 or rest[0] != ':') return null;
198
+ rest = std.mem.trimStart(u8, rest[1..], " \t\r\n");
199
+ if (rest.len == 0 or rest[0] != '"') return null;
200
+ rest = rest[1..];
201
+ const end = std.mem.indexOfScalar(u8, rest, '"') orelse return null;
202
+ const value = rest[0..end];
203
+ if (!std.mem.startsWith(u8, value, required_prefix)) return null;
204
+ const suffix = value[required_prefix.len..];
205
+ if (suffix.len == 0) return null;
206
+ return suffix;
207
+ }
208
+
209
+ /// The SDK dependency's real root, resolved the way both the toolchain
210
+ /// check and its teaching name it.
211
+ fn tsSdkRoot(allocator: std.mem.Allocator, io: std.Io, dep: *std.Build.Dependency) []const u8 {
212
+ const raw_root = dep.builder.build_root.path orelse ".";
213
+ return std.Io.Dir.cwd().realPathFileAlloc(io, raw_root, allocator) catch raw_root;
214
+ }
215
+
216
+ fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8) TsCoreStage {
217
+ if (!appFileExists(b, app_root, "src/app.native")) {
218
+ @panic("\nthis app has a TypeScript core (src/core.ts) but no view: TS apps render markup," ++
219
+ " so add src/app.native (the whole view tier binds the core's emitted model)\n");
220
+ }
221
+ const node = b.findProgram(&.{"node"}, &.{}) catch {
222
+ @panic("\nbuilding a TypeScript app core needs node on PATH (the @native-sdk/core transpiler runs at" ++
223
+ " build time; the binary it emits ships no JS runtime).\nInstall Node.js 22.15+ (on the 23 line: 23.5+)" ++
224
+ " — https://nodejs.org or `brew install node` — and re-run.\n");
225
+ };
226
+ switch (tsToolchainResolution(b, dep)) {
227
+ .resolved => {},
228
+ .unresolved => {
229
+ // Safety net for direct `zig build` users: the `native` CLI
230
+ // gates this itself, so reaching here means zig was invoked by
231
+ // hand against an SDK whose toolchain resolves nowhere. Name
232
+ // the SDK dependency's real location as a RESOLVED path and
233
+ // fail the configure phase cleanly — a teaching message, never
234
+ // a panic stack trace.
235
+ const sdk_root = tsSdkRoot(dep.builder.allocator, dep.builder.graph.io, dep);
236
+ std.debug.print(
237
+ \\
238
+ \\error: the @native-sdk/core transpiler cannot resolve its TypeScript toolchain
239
+ \\(its compiler, @typescript/old). On a repo checkout, install it once with:
240
+ \\ cd {s}/packages/core && npm ci --include=dev
241
+ \\(An npm-installed @native-sdk/cli carries the toolchain automatically; if it
242
+ \\is missing there, the install is broken - reinstall @native-sdk/cli.)
243
+ \\
244
+ \\
245
+ , .{sdk_root});
246
+ std.process.exit(1);
247
+ },
248
+ .version_mismatch => |mismatch| {
249
+ // The wrong-VERSION shape gets its own teaching (the CLI's
250
+ // gate mirrors it): a conflicting consumer-tree
251
+ // @typescript/old shadows the SDK's exact pin, and no install
252
+ // command fixes what is already installed — the conflict has
253
+ // to move.
254
+ std.debug.print(
255
+ \\
256
+ \\error: the @native-sdk/core transpiler's TypeScript compiler resolves at the
257
+ \\wrong version: @typescript/old resolves to typescript {s}, but the SDK pins
258
+ \\npm:typescript@{s}. Another package in this tree pins a conflicting
259
+ \\@typescript/old - align it with the SDK's pin (or remove it) and reinstall,
260
+ \\so the SDK's exact pin is the copy that resolves.
261
+ \\
262
+ \\
263
+ , .{ mismatch.resolved, mismatch.pinned });
264
+ std.process.exit(1);
265
+ },
266
+ }
267
+
268
+ // The transpiler runs through build/ts_run.mjs, not as `node cli.ts`:
269
+ // on the npm-installed layout the transpiler's .ts sources live inside
270
+ // node_modules, where node refuses its builtin type stripping — the
271
+ // runner strips those modules with the transpiler's own installed
272
+ // TypeScript and is a pass-through on a repo checkout.
273
+ const transpile = b.addSystemCommand(&.{node});
274
+ transpile.addFileArg(dep.path("build/ts_run.mjs"));
275
+ transpile.addFileArg(dep.path("packages/core/src/cli.ts"));
276
+ transpile.addFileArg(b.path(appPath(b, app_root, "src/core.ts")));
277
+ transpile.addArg("-o");
278
+ const emitted_core = transpile.addOutputFileArg("core.zig");
279
+ // The transpiler reads its own sources, the SDK modules, and the core's
280
+ // WHOLE import graph at run time; declare them so a transpiler upgrade
281
+ // or an edit to ANY module of a multi-file core re-emits it. The graph
282
+ // is declared as every .ts under the app's src/ (a superset of the
283
+ // reachable imports: over-approximation only re-runs the transpile,
284
+ // never misses a stale input). Failure mode: the checker's NS
285
+ // diagnostics stream to stderr verbatim — they are the teaching layer,
286
+ // nothing wraps them.
287
+ addTsDirInputs(b, dep.builder, transpile, "packages/core/sdk");
288
+ addAppTsDirInputs(b, transpile, appPath(b, app_root, "src"));
289
+ const transpiler_sources = [_][]const u8{
290
+ "checker.ts", "cli.ts", "diagnostics.ts", "emitter.ts", "infer.ts", "modules.ts", "transpile.ts", "typed_ast.ts", "types.ts",
291
+ };
292
+ for (transpiler_sources) |source| {
293
+ transpile.addFileInput(dep.path(b.fmt("packages/core/src/{s}", .{source})));
294
+ }
295
+
296
+ // The wiring imports core.zig and app.native relatively; the emitted
297
+ // core imports rt.zig relatively: stage all four into one directory.
298
+ const staged = b.addWriteFiles();
299
+ _ = staged.addCopyFile(emitted_core, "core.zig");
300
+ _ = staged.addCopyFile(dep.path("packages/core/rt/rt.zig"), "rt.zig");
301
+ _ = staged.addCopyFile(b.path(appPath(b, app_root, "src/app.native")), "app.native");
302
+ const main_root = staged.addCopyFile(dep.path("src/app_runner/ts_core_main.zig"), "main.zig");
303
+ return .{ .main_root = main_root };
304
+ }
305
+
306
+ /// Declare every .ts file in an SDK-relative directory as a file input of
307
+ /// the transpile step (the SDK library modules an app may import).
308
+ fn addTsDirInputs(b: *std.Build, sdk_builder: *std.Build, transpile: *std.Build.Step.Run, dir_path: []const u8) void {
309
+ var dir = sdk_builder.build_root.handle.openDir(b.graph.io, dir_path, .{ .iterate = true }) catch return;
310
+ defer dir.close(b.graph.io);
311
+ var it = dir.iterate();
312
+ while (it.next(b.graph.io) catch null) |entry| {
313
+ if (entry.kind != .file) continue;
314
+ if (!std.mem.endsWith(u8, entry.name, ".ts")) continue;
315
+ transpile.addFileInput(sdk_builder.path(b.fmt("{s}/{s}", .{ dir_path, entry.name })));
316
+ }
317
+ }
318
+
319
+ /// Declare every .ts file under the app's src/ (recursively — a core may
320
+ /// split into subdirectories) as a file input of the transpile step.
321
+ fn addAppTsDirInputs(b: *std.Build, transpile: *std.Build.Step.Run, src_path: []const u8) void {
322
+ var dir = b.build_root.handle.openDir(b.graph.io, src_path, .{ .iterate = true }) catch return;
323
+ defer dir.close(b.graph.io);
324
+ var walker = dir.walk(b.allocator) catch return;
325
+ defer walker.deinit();
326
+ while (walker.next(b.graph.io) catch null) |entry| {
327
+ if (entry.kind != .file) continue;
328
+ if (!std.mem.endsWith(u8, entry.basename, ".ts")) continue;
329
+ transpile.addFileInput(b.path(b.fmt("{s}/{s}", .{ src_path, entry.path })));
330
+ }
331
+ }
332
+
45
333
  /// The `native_sdk_app_*` C ABI every embed static library exports.
46
334
  pub const mobile_export_symbol_names = [_][]const u8{
47
335
  "native_sdk_app_create",
@@ -190,11 +478,31 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
190
478
  const optimize = exampleOptimizeMode(b, optimize_request, .Debug);
191
479
  const app_optimize = exampleOptimizeMode(b, optimize_request, .ReleaseFast);
192
480
 
481
+ // The core role is detected from the tree (never a flag or config):
482
+ // builds with a custom `main` entry declared their core explicitly and
483
+ // skip detection.
484
+ const core_tree: CoreTree = if (std.mem.eql(u8, app_options.main, "src/main.zig"))
485
+ detectCoreTree(b, app_options.app_root)
486
+ else
487
+ .zig;
488
+ if (core_tree == .both) {
489
+ @panic("\nthis app declares two cores: src/core.ts (TypeScript) and src/main.zig (Zig)." ++
490
+ "\nAn app has exactly one core - the tree is the truth. Keep src/core.ts and delete" ++
491
+ " src/main.zig,\nor keep src/main.zig and delete src/core.ts. (Other Zig files under" ++
492
+ " src/ are fine either way.)\n");
493
+ }
494
+ const ts_stage: ?TsCoreStage = if (core_tree == .ts) tsCoreStage(b, dep, app_options.app_root) else null;
495
+
193
496
  // Mobile targets get the embed static library as a `lib` step: the
194
497
  // artifact the toolkit-owned iOS host (and any hand-written shim)
195
498
  // links, so `native dev|package --target ios` works against every
196
499
  // standard app build — generated graph or ejected — with nothing but
197
500
  // `-Dtarget`. Desktop targets keep the step absent.
501
+ if (ts_stage != null and (target.result.os.tag == .ios or target.result.abi.isAndroid())) {
502
+ @panic("\nTypeScript app cores build desktop apps today; the mobile embed library for TS" ++
503
+ " cores lands with the mobile host tier.\nBuild for a desktop target, or port the core" ++
504
+ " to a Zig `mobileOptions` app for mobile.\n");
505
+ }
198
506
  if (target.result.os.tag == .ios or target.result.abi.isAndroid()) {
199
507
  addMobileLibWithTarget(b, dep, target, optimize, .{
200
508
  .name = app_options.name,
@@ -248,11 +556,23 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
248
556
  options.addOption(bool, "web_layer", web_layer);
249
557
  const options_mod = options.createModule();
250
558
 
251
- const app_mod = appModule(b, dep, target, app_optimize, app_options, options_mod);
559
+ const app_mod = appModule(b, dep, target, app_optimize, app_options, options_mod, ts_stage);
252
560
  const exe = b.addExecutable(.{
253
561
  .name = app_options.name,
254
562
  .root_module = app_mod,
255
563
  });
564
+ // Windows subsystem posture: release-shaped exes (`native build`,
565
+ // and therefore everything `native package --target windows` wraps)
566
+ // are GUI-subsystem, so launching the app never flashes a console
567
+ // window behind it. Debug exes keep the console subsystem — the dev
568
+ // loop's logs live there, and a double-clicked Debug binary opening
569
+ // its own log console is a feature. Redirected logging still works
570
+ // on GUI exes (handles inherit; only console AUTO-allocation is
571
+ // gated by the subsystem), so automation harnesses that pipe
572
+ // `app.exe > log 2>&1` keep their logs either way.
573
+ if (target.result.os.tag == .windows and app_optimize != .Debug) {
574
+ exe.subsystem = .windows;
575
+ }
256
576
  linkPlatform(b, dep, target, app_mod, exe, selected_platform, web_engine, web_layer, cef_dir, cef_auto_install);
257
577
  const install = b.addInstallArtifact(exe, .{});
258
578
  b.getInstallStep().dependOn(&install.step);
@@ -263,11 +583,42 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
263
583
  const run_step = b.step("run", "Run the app");
264
584
  run_step.dependOn(&run.step);
265
585
 
266
- const test_app_mod = if (app_optimize == optimize) app_mod else appModule(b, dep, target, optimize, app_options, options_mod);
586
+ const test_app_mod = if (app_optimize == optimize) app_mod else appModule(b, dep, target, optimize, app_options, options_mod, ts_stage);
267
587
  const tests = b.addTest(.{ .root_module = test_app_mod, .use_llvm = useLlvmWorkaround(target) });
268
588
  const test_step = b.step("test", "Run tests");
269
589
  test_step.dependOn(&b.addRunArtifact(tests).step);
270
590
 
591
+ // `native test` must surface the app's compile-time teaching errors,
592
+ // not just its test failures. Test builds never analyze `main` (the
593
+ // test runner replaces the entry point), so rules that fire inside it
594
+ // — UiApp.create's Model-defaults rule above all — used to ambush at
595
+ // `native build`, the LAST step in the loop. Compiling this object
596
+ // forces full semantic analysis of the app module, entry point
597
+ // included; nothing links or runs.
598
+ const analysis_root = b.addWriteFiles().add("app_analysis.zig",
599
+ \\//! Generated by the app build: force semantic analysis of the
600
+ \\//! app's entry point at test time. Exactly `main`, transitively —
601
+ \\//! the same surface `native build` analyzes — so test-time can
602
+ \\//! never be stricter than the build it fronts.
603
+ \\comptime {
604
+ \\ const app = @import("app");
605
+ \\ if (@hasDecl(app, "main")) _ = &app.main;
606
+ \\}
607
+ \\
608
+ );
609
+ const analysis_mod = b.createModule(.{
610
+ .root_source_file = analysis_root,
611
+ .target = target,
612
+ .optimize = optimize,
613
+ });
614
+ analysis_mod.addImport("app", test_app_mod);
615
+ const analysis_obj = b.addObject(.{
616
+ .name = b.fmt("{s}-analysis", .{app_options.name}),
617
+ .root_module = analysis_mod,
618
+ .use_llvm = useLlvmWorkaround(target),
619
+ });
620
+ test_step.dependOn(&analysis_obj.step);
621
+
271
622
  // `zig build model-contract`: reflect the app's Model/Msg into
272
623
  // zig-out/model-contract.zon so `native check` can verify markup
273
624
  // bindings against the app's real surface without compiling the app.
@@ -388,20 +739,35 @@ fn exampleOptimizeMode(b: *std.Build, requested: ?std.builtin.OptimizeMode, defa
388
739
  };
389
740
  }
390
741
 
391
- fn appModule(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, app_options: AppOptions, options_mod: *std.Build.Module) *std.Build.Module {
742
+ fn appModule(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, app_options: AppOptions, options_mod: *std.Build.Module, ts_stage: ?TsCoreStage) *std.Build.Module {
392
743
  const native_sdk_mod = nativeSdkModule(b, dep, target, optimize);
393
744
  const runner_mod = b.createModule(.{
394
745
  .root_source_file = dep.path("src/app_runner/root.zig"),
395
746
  .target = target,
396
747
  .optimize = optimize,
397
748
  });
749
+ const manifest_mod = b.createModule(.{ .root_source_file = b.path(appPath(b, app_options.app_root, "app.zon")) });
398
750
  runner_mod.addImport("native_sdk", native_sdk_mod);
399
751
  runner_mod.addImport("build_options", options_mod);
400
- runner_mod.addImport("app_manifest_zon", b.createModule(.{ .root_source_file = b.path(appPath(b, app_options.app_root, "app.zon")) }));
752
+ runner_mod.addImport("app_manifest_zon", manifest_mod);
401
753
 
402
- const app_mod = localModule(b, target, optimize, appPath(b, app_options.app_root, app_options.main));
754
+ const app_mod = if (ts_stage) |stage|
755
+ // TypeScript core: the app module roots at the staged generated
756
+ // wiring (ts_core_main.zig beside the transpiled core.zig, its rt
757
+ // kernel, and the app's markup).
758
+ b.createModule(.{
759
+ .root_source_file = stage.main_root,
760
+ .target = target,
761
+ .optimize = optimize,
762
+ })
763
+ else
764
+ localModule(b, target, optimize, appPath(b, app_options.app_root, app_options.main));
403
765
  app_mod.addImport("native_sdk", native_sdk_mod);
404
766
  app_mod.addImport("runner", runner_mod);
767
+ if (ts_stage != null) {
768
+ // The wiring derives scene/identity/security from app.zon itself.
769
+ app_mod.addImport("app_manifest_zon", manifest_mod);
770
+ }
405
771
  return app_mod;
406
772
  }
407
773
 
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Run a TypeScript module of the @native-sdk/core transpiler tier under
4
+ // node from ANY SDK layout:
5
+ //
6
+ // node ts_run.mjs <module.ts> [args...]
7
+ //
8
+ // ONE code path for every layout: a load hook strips EVERY .ts module with
9
+ // the transpiler's own pinned TypeScript compiler (shipped as a dependency
10
+ // of @native-sdk/cli, or a repo checkout's `npm ci` install inside
11
+ // packages/core — either way resolved from the target module's location by
12
+ // node's ancestor node_modules walk). Node's own type stripping is never
13
+ // relied on: it refuses node_modules-resident .ts by design
14
+ // (ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING), and outside node_modules
15
+ // it only became DEFAULT in node 22.18 — so a checkout target on
16
+ // 22.15-22.17 would die with ERR_UNKNOWN_FILE_EXTENSION if the hook let it
17
+ // "fall through". Hooking everything makes the 22.15 floor true for both
18
+ // layouts. Then the runner imports the requested module with argv
19
+ // respliced so the target sees its usual shape (its own path at argv[1],
20
+ // its arguments from argv[2]).
21
+ //
22
+ // On node builds without module.registerHooks (pre-22.15, or 23.0-23.4 —
23
+ // the hook landed in 22.15 and 23.5, so ">=22.15" alone is not the
24
+ // capability line) NO .ts target can run — node_modules-resident
25
+ // stripping is refused by design and default stripping outside
26
+ // node_modules only landed in 22.18, which is above this tier anyway —
27
+ // so the runner fails fast with one teaching line (upgrade to Node.js
28
+ // 22.15+, on the 23 line 23.5+) before importing it, instead of
29
+ // surfacing node's raw extension/stripping error.
30
+
31
+ import module, { createRequire } from 'node:module';
32
+ import { readFileSync } from 'node:fs';
33
+ import { resolve } from 'node:path';
34
+ import { pathToFileURL, fileURLToPath } from 'node:url';
35
+
36
+ const target = process.argv[2];
37
+ if (!target) {
38
+ console.error('usage: node ts_run.mjs <module.ts> [args...]');
39
+ process.exit(2);
40
+ }
41
+ const targetPath = resolve(target);
42
+ // Drop the runner from argv so the target module parses its own argv
43
+ // exactly as when node runs it directly.
44
+ process.argv.splice(1, 1);
45
+
46
+ if (typeof module.registerHooks !== 'function') {
47
+ // No load hooks on this node (pre-22.15, or a 23.0-23.4 build). Every
48
+ // .ts target needs the hook — node_modules-resident stripping is
49
+ // refused by design, and native default stripping outside node_modules
50
+ // is 22.18+ — so any .ts target would fail deep inside node with a raw
51
+ // extension/stripping error. Teach the fix instead.
52
+ if (targetPath.endsWith('.ts')) {
53
+ console.error(
54
+ `TypeScript apps need Node.js 22.15+ (on the 23 line: 23.5+); you're running ${process.version} - upgrade node and re-run.`,
55
+ );
56
+ process.exit(1);
57
+ }
58
+ } else {
59
+ let ts = null;
60
+ module.registerHooks({
61
+ load(url, context, nextLoad) {
62
+ if (url.startsWith('file:') && url.endsWith('.ts')) {
63
+ const filePath = fileURLToPath(url);
64
+ // The transpiler's own pinned compiler, resolved from the target
65
+ // module's location (packages/core/node_modules after the taught
66
+ // `npm ci`, or the dependency npm installed beside the CLI). The
67
+ // ALIAS is required directly — not the @typescript/typescript6
68
+ // wrapper — because the wrapper's re-export resolves
69
+ // "@typescript/old" from the WRAPPER's own location, where a
70
+ // consumer tree's conflicting hoisted copy would win nearest-wins
71
+ // over our exact pin; resolving from the target finds our own
72
+ // nested/hoisted pin first (same reasoning as typed_ast.ts).
73
+ if (ts === null) {
74
+ try {
75
+ ts = createRequire(targetPath)('@typescript/old');
76
+ } catch {
77
+ // A missing toolchain reaches here only on a direct
78
+ // `node ts_run.mjs` run: every CLI verb gates resolution with
79
+ // a fuller per-layout teaching before this runner is spawned.
80
+ // Keep the direct-run error sane and name the checkout fix.
81
+ console.error(
82
+ `ts_run.mjs: the transpiler's TypeScript toolchain (@typescript/old) does not resolve from ${targetPath} - on a repo checkout, run \`npm ci --include=dev\` in packages/core.`,
83
+ );
84
+ process.exit(1);
85
+ }
86
+ }
87
+ const { outputText } = ts.transpileModule(readFileSync(filePath, 'utf8'), {
88
+ fileName: filePath,
89
+ compilerOptions: {
90
+ target: ts.ScriptTarget.ESNext,
91
+ module: ts.ModuleKind.ESNext,
92
+ verbatimModuleSyntax: true,
93
+ },
94
+ });
95
+ return { format: 'module', source: outputText, shortCircuit: true };
96
+ }
97
+ return nextLoad(url, context);
98
+ },
99
+ });
100
+ }
101
+
102
+ await import(pathToFileURL(targetPath).href);