@native-sdk/cli 0.4.2 → 0.4.4

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 (46) hide show
  1. package/build/app.zig +121 -66
  2. package/build.zig +123 -6
  3. package/package.json +9 -9
  4. package/skill-data/core/SKILL.md +3 -0
  5. package/skill-data/native-ui/SKILL.md +16 -0
  6. package/skill-data/zig/SKILL.md +198 -0
  7. package/skills/native-sdk/SKILL.md +1 -1
  8. package/src/app_runner/root.zig +51 -9
  9. package/src/platform/linux/gtk_host.c +226 -21
  10. package/src/platform/windows/webview2_host.cpp +16 -10
  11. package/src/primitives/app_manifest/root.zig +8 -0
  12. package/src/primitives/app_manifest/types.zig +14 -0
  13. package/src/primitives/app_manifest/validation.zig +18 -0
  14. package/src/primitives/app_manifest/web_layer.zig +366 -0
  15. package/src/primitives/canvas/chart_tests.zig +2 -2
  16. package/src/primitives/canvas/markdown_tests.zig +1 -1
  17. package/src/primitives/canvas/reference.zig +135 -6
  18. package/src/primitives/canvas/reference_tests.zig +171 -6
  19. package/src/primitives/canvas/root.zig +3 -0
  20. package/src/primitives/canvas/test_support.zig +3 -0
  21. package/src/primitives/canvas/widget_builtin_tests.zig +249 -4
  22. package/src/primitives/canvas/widget_render_controls.zig +18 -1
  23. package/src/primitives/canvas/widget_runtime.zig +3 -0
  24. package/src/primitives/canvas/widget_text_input.zig +104 -1
  25. package/src/runtime/api.zig +7 -0
  26. package/src/runtime/bridge_responses.zig +2 -0
  27. package/src/runtime/builtin_bridge.zig +6 -0
  28. package/src/runtime/canvas_widget_runtime.zig +23 -3
  29. package/src/runtime/canvas_widget_text_tests.zig +101 -0
  30. package/src/runtime/flow.zig +8 -0
  31. package/src/runtime/platform_bridge_tests.zig +1 -0
  32. package/src/runtime/session_tests.zig +35 -8
  33. package/src/runtime/view.zig +1 -1
  34. package/src/runtime/view_widget_scroll.zig +12 -1
  35. package/src/runtime/view_widget_text.zig +6 -2
  36. package/src/runtime/web_layer_gate_tests.zig +242 -0
  37. package/src/runtime/window_storage.zig +5 -0
  38. package/src/runtime/window_view_runtime.zig +1 -0
  39. package/src/tooling/buildgraph.zig +119 -3
  40. package/src/tooling/junction.zig +247 -0
  41. package/src/tooling/manifest.zig +267 -1
  42. package/src/tooling/package.zig +598 -6
  43. package/src/tooling/raw_manifest.zig +1 -0
  44. package/src/tooling/root.zig +1 -0
  45. package/src/tooling/templates.zig +288 -61
  46. package/src/tooling/verbs.zig +5 -0
@@ -0,0 +1,247 @@
1
+ //! Windows directory-junction shim for cross-volume SDK wiring.
2
+ //!
3
+ //! build.zig.zon path dependencies must be relative to the build root (Zig
4
+ //! rejects absolute paths), but on Windows a relative path only exists when
5
+ //! both ends share a volume: no chain of `..` segments leads from an app on
6
+ //! D:\ to an SDK under the npm global prefix on C:\, nor between two
7
+ //! different \\server\share UNC roots. `std.fs.path.relative` signals that
8
+ //! case by returning the canonicalized absolute target instead of a
9
+ //! relative path. The bridge is a directory junction inside the app's
10
+ //! `.native/` directory pointing at the framework root, so the zon
11
+ //! dependency can stay relative by routing through it. Junctions — mount
12
+ //! points, not file symlinks — resolve on the filesystem like plain
13
+ //! directories and, unlike symlinks, need neither Administrator rights nor
14
+ //! Developer Mode to create, which is why this shim sets a MOUNT_POINT
15
+ //! reparse point instead of calling the symlink API.
16
+
17
+ const std = @import("std");
18
+ const builtin = @import("builtin");
19
+
20
+ /// True when a path computed by `std.fs.path.relative` could not actually
21
+ /// be made relative — the Windows cross-volume case (two drive letters, or
22
+ /// two different UNC shares), where the function degrades to the absolute
23
+ /// target path. Checks both path flavors so the decision is testable with
24
+ /// fabricated `C:\`/`D:\` strings on every host.
25
+ pub fn crossesVolumes(dependency_path: []const u8) bool {
26
+ return std.fs.path.isAbsoluteWindows(dependency_path) or
27
+ std.fs.path.isAbsolutePosix(dependency_path);
28
+ }
29
+
30
+ /// The two user-level ways out when the cross-volume junction bridge is
31
+ /// unavailable or does not apply (appended to every cross-volume teaching
32
+ /// error, so no failure ever ends at "absolute paths are rejected" without
33
+ /// a way forward).
34
+ pub const cross_volume_ways_out =
35
+ \\Two ways out:
36
+ \\ - keep the app on the same volume as the Native SDK install, or
37
+ \\ - move the npm global prefix onto the app's volume
38
+ \\ (`npm config set prefix <dir on the app's volume>`, then
39
+ \\ reinstall @native-sdk/cli there).
40
+ \\
41
+ ;
42
+
43
+ pub const EnsureError = error{
44
+ /// Junctions are a Windows (NTFS reparse point) concept; on other
45
+ /// platforms a genuinely relative path always exists and this shim is
46
+ /// never needed.
47
+ UnsupportedPlatform,
48
+ /// The reparse point could not be created (exotic filesystem, policy).
49
+ /// Callers must turn this into a teaching error, never into an
50
+ /// absolute zon path.
51
+ JunctionFailed,
52
+ /// Something that is not a junction (a non-empty real directory)
53
+ /// occupies the junction path; refusing beats silently deleting a tree
54
+ /// the CLI does not own.
55
+ JunctionPathOccupied,
56
+ } || std.mem.Allocator.Error || std.Io.Cancelable;
57
+
58
+ /// Make `junction_path` a directory junction resolving to `target` (both
59
+ /// absolute, symlink-free paths — realpath output). Idempotent per
60
+ /// generation: a junction already resolving to `target` is left untouched
61
+ /// (so repeated `native dev|build|test` runs are no-ops), one resolving
62
+ /// elsewhere (the SDK moved or was upgraded in place) or dangling (its old
63
+ /// target was deleted) is removed and recreated.
64
+ pub fn ensure(allocator: std.mem.Allocator, io: std.Io, junction_path: []const u8, target: []const u8) EnsureError!void {
65
+ if (builtin.os.tag != .windows) return error.UnsupportedPlatform;
66
+
67
+ const cwd = std.Io.Dir.cwd();
68
+ if (cwd.realPathFileAlloc(io, junction_path, allocator)) |resolved| {
69
+ defer allocator.free(resolved);
70
+ // Windows paths are case-insensitive; compare that way so a mere
71
+ // case difference between two realpath spellings never causes a
72
+ // delete/recreate cycle on every generation.
73
+ if (std.ascii.eqlIgnoreCase(resolved, target)) return;
74
+ } else |err| switch (err) {
75
+ error.Canceled => |e| return e,
76
+ // Missing entirely, or a junction whose target no longer exists
77
+ // (realpath cannot resolve through it) — either way, fall through
78
+ // and clear the name so creation below starts fresh.
79
+ else => {},
80
+ }
81
+
82
+ remove(io, junction_path) catch |err| switch (err) {
83
+ error.JunctionNotFound => {},
84
+ else => |e| return e,
85
+ };
86
+
87
+ create(io, junction_path, target) catch |err| switch (err) {
88
+ error.Canceled => |e| return e,
89
+ else => {
90
+ // A half-made junction is a plain empty directory; clear it so
91
+ // the next attempt (or a user retry) starts from nothing.
92
+ cwd.deleteDir(io, junction_path) catch {};
93
+ return error.JunctionFailed;
94
+ },
95
+ };
96
+ }
97
+
98
+ /// Delete whatever occupies `junction_path` without ever touching a
99
+ /// junction's target: RemoveDirectory deletes the reparse point itself
100
+ /// (dangling or not) and also clears a plain empty directory, while a
101
+ /// non-empty real directory fails DirNotEmpty — surfaced as occupied
102
+ /// rather than destroying data the CLI does not own.
103
+ fn remove(io: std.Io, junction_path: []const u8) error{ JunctionNotFound, JunctionPathOccupied, Canceled }!void {
104
+ const cwd = std.Io.Dir.cwd();
105
+ cwd.deleteDir(io, junction_path) catch |err| switch (err) {
106
+ error.FileNotFound => return error.JunctionNotFound,
107
+ error.Canceled => |e| return e,
108
+ // A regular file squatting on the name: clear it the file way.
109
+ error.NotDir => cwd.deleteFile(io, junction_path) catch |file_err| switch (file_err) {
110
+ error.FileNotFound => return error.JunctionNotFound,
111
+ error.Canceled => |e| return e,
112
+ else => return error.JunctionPathOccupied,
113
+ },
114
+ else => return error.JunctionPathOccupied,
115
+ };
116
+ }
117
+
118
+ /// Create the junction: make the directory and set a MOUNT_POINT reparse
119
+ /// point on it in one NtCreateFile + FSCTL_SET_REPARSE_POINT pair, the same
120
+ /// operation `mklink /J` performs. The substitute name is the NT-namespaced
121
+ /// target (`\??\C:\...`), the print name its Win32 spelling for `dir`
122
+ /// output.
123
+ fn create(io: std.Io, junction_path: []const u8, target: []const u8) !void {
124
+ if (builtin.os.tag != .windows) return error.UnsupportedPlatform;
125
+ const w = std.os.windows;
126
+
127
+ const junction_nt = try std.Io.Threaded.sliceToPrefixedFileW(null, junction_path, .{ .allow_relative = false });
128
+ const target_nt = try std.Io.Threaded.sliceToPrefixedFileW(null, target, .{ .allow_relative = false });
129
+ const substitute = target_nt.span();
130
+
131
+ var print_buffer: [w.PATH_MAX_WIDE]u16 = undefined;
132
+ // An empty print name is valid reparse data; the junction still
133
+ // resolves, it just lists without a pretty target in Explorer/`dir`.
134
+ const print_name: []const u16 = w.ntToWin32Namespace(substitute, &print_buffer) catch &.{};
135
+
136
+ // REPARSE_DATA_BUFFER header for IO_REPARSE_TAG_MOUNT_POINT, followed
137
+ // by PathBuffer holding substitute + NUL + print + NUL (WTF-16).
138
+ const MountPointData = extern struct {
139
+ ReparseTag: w.IO_REPARSE_TAG,
140
+ ReparseDataLength: w.USHORT,
141
+ Reserved: w.USHORT,
142
+ SubstituteNameOffset: w.USHORT,
143
+ SubstituteNameLength: w.USHORT,
144
+ PrintNameOffset: w.USHORT,
145
+ PrintNameLength: w.USHORT,
146
+ };
147
+ var buffer: [w.MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 = undefined;
148
+ const substitute_bytes = substitute.len * 2;
149
+ const print_bytes = print_name.len * 2;
150
+ const total_len = @sizeOf(MountPointData) + substitute_bytes + 2 + print_bytes + 2;
151
+ if (total_len > buffer.len) return error.NameTooLong;
152
+ const header: MountPointData = .{
153
+ .ReparseTag = .MOUNT_POINT,
154
+ // Everything after the 8-byte (tag + length + reserved) prefix.
155
+ .ReparseDataLength = @intCast(total_len - 8),
156
+ .Reserved = 0,
157
+ .SubstituteNameOffset = 0,
158
+ .SubstituteNameLength = @intCast(substitute_bytes),
159
+ .PrintNameOffset = @intCast(substitute_bytes + 2),
160
+ .PrintNameLength = @intCast(print_bytes),
161
+ };
162
+ @memcpy(buffer[0..@sizeOf(MountPointData)], std.mem.asBytes(&header));
163
+ var offset: usize = @sizeOf(MountPointData);
164
+ @memcpy(buffer[offset..][0..substitute_bytes], std.mem.sliceAsBytes(substitute));
165
+ offset += substitute_bytes;
166
+ buffer[offset] = 0;
167
+ buffer[offset + 1] = 0;
168
+ offset += 2;
169
+ @memcpy(buffer[offset..][0..print_bytes], std.mem.sliceAsBytes(print_name));
170
+ offset += print_bytes;
171
+ buffer[offset] = 0;
172
+ buffer[offset + 1] = 0;
173
+
174
+ // Create the directory and keep a synchronous write handle to it that
175
+ // does not follow reparse points — the handle FSCTL_SET_REPARSE_POINT
176
+ // stamps the mount point onto.
177
+ var handle: w.HANDLE = undefined;
178
+ const attr: w.OBJECT.ATTRIBUTES = .{
179
+ .RootDirectory = null,
180
+ .ObjectName = @constCast(&w.UNICODE_STRING.init(junction_nt.span())),
181
+ };
182
+ var iosb: w.IO_STATUS_BLOCK = undefined;
183
+ switch (w.ntdll.NtCreateFile(
184
+ &handle,
185
+ .{ .GENERIC = .{ .WRITE = true }, .STANDARD = .{ .SYNCHRONIZE = true } },
186
+ &attr,
187
+ &iosb,
188
+ null,
189
+ .{ .NORMAL = true },
190
+ .VALID_FLAGS,
191
+ .CREATE,
192
+ .{ .DIRECTORY_FILE = true, .IO = .SYNCHRONOUS_NONALERT, .OPEN_REPARSE_POINT = true },
193
+ null,
194
+ 0,
195
+ )) {
196
+ .SUCCESS => {},
197
+ .OBJECT_NAME_COLLISION => return error.PathAlreadyExists,
198
+ .ACCESS_DENIED => return error.AccessDenied,
199
+ else => return error.JunctionFailed,
200
+ }
201
+ defer w.CloseHandle(handle);
202
+
203
+ const result = try io.operate(.{ .device_io_control = .{
204
+ .file = .{ .handle = handle, .flags = .{ .nonblocking = false } },
205
+ .code = .SET_REPARSE_POINT,
206
+ .in = buffer[0..total_len],
207
+ } });
208
+ if (result.device_io_control.u.Status != .SUCCESS) return error.JunctionFailed;
209
+ }
210
+
211
+ test "cross-volume detection catches what std.fs.path.relative degrades to" {
212
+ // Same volume: a genuinely relative result, no junction needed.
213
+ try std.testing.expect(!crossesVolumes("../../.."));
214
+ try std.testing.expect(!crossesVolumes("..\\..\\sdk"));
215
+ try std.testing.expect(!crossesVolumes(""));
216
+ // Cross volume on Windows: relative() returns the absolute target.
217
+ try std.testing.expect(crossesVolumes("C:\\Users\\alpha\\AppData\\Roaming\\npm\\node_modules\\@native-sdk\\cli"));
218
+ try std.testing.expect(crossesVolumes("\\\\server\\share\\native-sdk"));
219
+ // POSIX absolute cannot happen from relative(), but stays covered.
220
+ try std.testing.expect(crossesVolumes("/opt/native-sdk"));
221
+ }
222
+
223
+ test "the reported cross-drive layout degrades to an absolute path and is detected" {
224
+ // The exact shape from the field report: app on D:\, npm-global SDK on
225
+ // C:\ — relativeWindows is pure, so this runs on every host.
226
+ const dependency_path = try std.fs.path.relativeWindows(
227
+ std.testing.allocator,
228
+ "D:\\Projects\\my_app",
229
+ null,
230
+ "D:\\Projects\\my_app\\.native\\build",
231
+ "C:\\Users\\alpha\\AppData\\Roaming\\npm\\node_modules\\@native-sdk\\cli",
232
+ );
233
+ defer std.testing.allocator.free(dependency_path);
234
+ try std.testing.expect(std.fs.path.isAbsoluteWindows(dependency_path));
235
+ try std.testing.expect(crossesVolumes(dependency_path));
236
+
237
+ // Control: same drive stays relative and is not routed.
238
+ const same_drive = try std.fs.path.relativeWindows(
239
+ std.testing.allocator,
240
+ "D:\\Projects\\my_app",
241
+ null,
242
+ "D:\\Projects\\my_app\\.native\\build",
243
+ "D:\\tools\\native-sdk",
244
+ );
245
+ defer std.testing.allocator.free(same_drive);
246
+ try std.testing.expect(!crossesVolumes(same_drive));
247
+ }
@@ -24,6 +24,10 @@ pub const Metadata = struct {
24
24
  capabilities: []const []const u8 = &.{},
25
25
  bridge_commands: []const BridgeCommandMetadata = &.{},
26
26
  web_engine: []const u8 = "system",
27
+ /// Whether the app ships the embedded web layer: "auto" (default,
28
+ /// inferred from the manifest's web declarations), "include", or
29
+ /// "exclude". See `webLayer` for the inference.
30
+ webview_layer: []const u8 = "auto",
27
31
  /// The built-in theme pack the app selects (`theme = "geist"`).
28
32
  /// Optional — absent keeps the house register. Validated against
29
33
  /// the known pack names so a typo is a check error, never a silent
@@ -52,6 +56,7 @@ pub const Metadata = struct {
52
56
  if (self.theme) |value| allocator.free(value);
53
57
  allocator.free(self.version);
54
58
  allocator.free(self.web_engine);
59
+ allocator.free(self.webview_layer);
55
60
  allocator.free(self.cef.dir);
56
61
  for (self.icons) |value| allocator.free(value);
57
62
  if (self.icons.len > 0) allocator.free(self.icons);
@@ -399,6 +404,7 @@ pub fn validateFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8)
399
404
  const url_schemes = parseUrlSchemes(allocator, metadata.url_schemes) catch return .{ .ok = false, .message = "app.zon URL schemes are invalid" };
400
405
  defer allocator.free(url_schemes);
401
406
  const manifest_web_engine = parseWebEngine(metadata.web_engine) catch return .{ .ok = false, .message = "app.zon web engine is invalid" };
407
+ const manifest_webview_layer = parseWebViewLayer(metadata.webview_layer) catch return .{ .ok = false, .message = "app.zon webview_layer is invalid - expected \"auto\", \"include\", or \"exclude\"" };
402
408
  const platform_settings = parsePlatformSettings(allocator, metadata.platforms) catch return .{ .ok = false, .message = "app.zon platforms are invalid" };
403
409
  defer allocator.free(platform_settings);
404
410
 
@@ -419,9 +425,16 @@ pub fn validateFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8)
419
425
  .file_associations = file_associations,
420
426
  .url_schemes = url_schemes,
421
427
  .cef = .{ .dir = metadata.cef.dir, .auto_install = metadata.cef.auto_install },
428
+ .webview_layer = manifest_webview_layer,
422
429
  .package = .{ .web_engine = manifest_web_engine },
423
430
  };
424
- app_manifest.validateManifest(manifest) catch return .{ .ok = false, .message = "manifest fields failed semantic validation" };
431
+ app_manifest.validateManifest(manifest) catch |err| return .{
432
+ .ok = false,
433
+ .message = switch (err) {
434
+ error.WebViewLayerConflict => web_layer_conflict_message,
435
+ else => "manifest fields failed semantic validation",
436
+ },
437
+ };
425
438
  return .{ .ok = true, .message = "app.zon is valid" };
426
439
  }
427
440
 
@@ -474,6 +487,7 @@ pub fn parseText(allocator: std.mem.Allocator, source: []const u8) !Metadata {
474
487
  .capabilities = try duplicateStringList(allocator, raw.capabilities),
475
488
  .bridge_commands = try convertRawBridgeCommands(allocator, raw.bridge.commands),
476
489
  .web_engine = try allocator.dupe(u8, raw.web_engine),
490
+ .webview_layer = try allocator.dupe(u8, raw.webview_layer),
477
491
  .cef = .{
478
492
  .dir = try allocator.dupe(u8, raw.cef.dir),
479
493
  .auto_install = raw.cef.auto_install,
@@ -1318,6 +1332,113 @@ fn parseWebEngine(value: []const u8) !app_manifest.WebEngine {
1318
1332
  return error.InvalidWebEngine;
1319
1333
  }
1320
1334
 
1335
+ fn parseWebViewLayer(value: []const u8) !app_manifest.WebViewLayer {
1336
+ if (std.mem.eql(u8, value, "auto")) return .auto;
1337
+ if (std.mem.eql(u8, value, "include")) return .include;
1338
+ if (std.mem.eql(u8, value, "exclude")) return .exclude;
1339
+ return error.InvalidWebViewLayer;
1340
+ }
1341
+
1342
+ /// The teaching message every boundary prints for the same
1343
+ /// contradiction: a manifest that excludes the web layer while declaring
1344
+ /// web content.
1345
+ pub const web_layer_conflict_message = "app.zon sets .webview_layer = \"exclude\" but the app declares web content (a .frontend block, the \"webview\" capability, a .shell webview view, or the Chromium web engine - from .web_engine or --web-engine) - remove the web declarations or drop the exclude";
1346
+
1347
+ /// The same contradiction arriving through the CLI flag instead of the
1348
+ /// manifest field: `--web-layer exclude` against an app that declares
1349
+ /// web content.
1350
+ pub const web_layer_flag_conflict_message = "--web-layer exclude contradicts the app's web declarations (a .frontend block, the \"webview\" capability, a .shell webview view, or the Chromium web engine - from .web_engine or --web-engine) - remove the web declarations or drop the flag";
1351
+
1352
+ /// Why the web layer is (or is not) in the build, for verdict lines —
1353
+ /// the shared contract's reason set.
1354
+ pub const WebLayerReason = app_manifest.web_layer.Reason;
1355
+
1356
+ /// The layer setting a boundary resolves before deciding: "auto",
1357
+ /// "include", or "exclude" — the shared contract's input enum, exported
1358
+ /// for the CLI's `--web-layer` flag.
1359
+ pub const WebViewLayerSetting = app_manifest.WebViewLayer;
1360
+
1361
+ /// Parse a `--web-layer` flag value (auto|include|exclude), via the
1362
+ /// shared contract so the flag and the app.zon field accept exactly the
1363
+ /// same vocabulary.
1364
+ pub const parseWebViewLayerSetting = app_manifest.web_layer.parseWebViewLayer;
1365
+
1366
+ pub const WebLayer = struct {
1367
+ enabled: bool,
1368
+ reason: WebLayerReason,
1369
+ /// Whether the deciding include/exclude came from the CLI's
1370
+ /// `--web-layer` flag rather than app.zon's `.webview_layer`; only
1371
+ /// meaningful for the declared_include/declared_exclude reasons.
1372
+ from_flag: bool = false,
1373
+
1374
+ /// The parenthesized half of a verdict line: `web layer: none
1375
+ /// (inferred)` / `web layer: webview2 (declared: capabilities)`.
1376
+ pub fn sourceText(self: WebLayer) []const u8 {
1377
+ return switch (self.reason) {
1378
+ .inferred_native_only => "inferred: nothing in app.zon declares web use",
1379
+ .declared_exclude => if (self.from_flag) "declared: --web-layer exclude" else "declared: .webview_layer = \"exclude\"",
1380
+ .capability => "declared: capabilities",
1381
+ .frontend => "declared: .frontend",
1382
+ .shell_webview => "declared: .shell webview view",
1383
+ .chromium_engine => "declared: the Chromium web engine (.web_engine or --web-engine)",
1384
+ .declared_include => if (self.from_flag) "declared: --web-layer include" else "declared: .webview_layer = \"include\"",
1385
+ // Only the build graph's lenient parse can produce this
1386
+ // reason; parsed metadata always reaches this fn readable.
1387
+ .unreadable_manifest => "kept: app.zon could not be parsed",
1388
+ };
1389
+ }
1390
+ };
1391
+
1392
+ pub const WebLayerError = error{ InvalidWebViewLayer, WebViewLayerConflict };
1393
+
1394
+ /// The CLI-side adapter over the shared web-layer contract
1395
+ /// (app_manifest.web_layer): the same declare-to-use rule the build
1396
+ /// graph and the runner apply, fed the engine this boundary RESOLVED —
1397
+ /// `--web-engine` orelse app.zon, already resolved by the CLI's verb
1398
+ /// handlers. `.webview_layer = "include"|"exclude"` overrides, and an
1399
+ /// exclude that contradicts a web declaration (including a resolved
1400
+ /// Chromium engine) is refused.
1401
+ pub fn webLayer(metadata: Metadata, resolved_engine: web_engine_tool.Engine) WebLayerError!WebLayer {
1402
+ return webLayerResolved(metadata, resolved_engine, null);
1403
+ }
1404
+
1405
+ /// `webLayer` with the CLI's `--web-layer` flag in play: the flag beats
1406
+ /// app.zon's `.webview_layer` exactly as `-Dweb-layer` beats it in the
1407
+ /// build graph (effective setting = flag orelse manifest), so the build
1408
+ /// graphs can forward their resolved decision and hand-run packages can
1409
+ /// override the field without editing app.zon. An exclude flag against
1410
+ /// a web declaration is the same refused conflict as a manifest exclude.
1411
+ pub fn webLayerResolved(metadata: Metadata, resolved_engine: web_engine_tool.Engine, layer_flag: ?WebViewLayerSetting) WebLayerError!WebLayer {
1412
+ const manifest_setting = parseWebViewLayer(metadata.webview_layer) catch return error.InvalidWebViewLayer;
1413
+ const engine: app_manifest.WebEngine = switch (resolved_engine) {
1414
+ .system => .system,
1415
+ .chromium => .chromium,
1416
+ };
1417
+ const decision = app_manifest.web_layer.infer(metadata, engine, layer_flag orelse manifest_setting) catch return error.WebViewLayerConflict;
1418
+ if (layer_flag != null) {
1419
+ // The flag decides, but the verdict line keeps app.zon's own
1420
+ // richer reason whenever the flag merely confirms what the
1421
+ // manifest already decides: the build graphs forward their
1422
+ // resolved decision on every `zig build package`, and the common
1423
+ // case must keep reporting "declared: capabilities", not the
1424
+ // forwarded flag. Only a flag that CHANGES the outcome names
1425
+ // itself as the cause.
1426
+ if (app_manifest.web_layer.infer(metadata, engine, manifest_setting)) |manifest_decision| {
1427
+ if (manifest_decision.enabled == decision.enabled) {
1428
+ return .{ .enabled = manifest_decision.enabled, .reason = manifest_decision.reason };
1429
+ }
1430
+ } else |_| {}
1431
+ return .{ .enabled = decision.enabled, .reason = decision.reason, .from_flag = true };
1432
+ }
1433
+ return .{ .enabled = decision.enabled, .reason = decision.reason };
1434
+ }
1435
+
1436
+ /// The web-layer verdict for callers with no engine flag in play
1437
+ /// (`native check`): the manifest's own engine is the resolved engine.
1438
+ pub fn webLayerFromManifest(metadata: Metadata) WebLayerError!WebLayer {
1439
+ return webLayer(metadata, web_engine_tool.Engine.parse(metadata.web_engine) orelse .system);
1440
+ }
1441
+
1321
1442
  fn validateRelativePath(path: []const u8) !void {
1322
1443
  if (path.len == 0) return error.InvalidPath;
1323
1444
  if (path[0] == '/' or path[0] == '\\') return error.InvalidPath;
@@ -1920,6 +2041,151 @@ test "validate accepts a square icon source and prebuilt containers" {
1920
2041
  try std.testing.expect(result.ok);
1921
2042
  }
1922
2043
 
2044
+ test "web layer inference is declare-to-use over parsed metadata" {
2045
+ // Nothing declared: native-only.
2046
+ const canvas_capabilities = [_][]const u8{ "native_views", "gpu_surfaces" };
2047
+ const canvas: Metadata = .{ .id = "dev.example.canvas", .name = "canvas", .version = "1.0.0", .capabilities = &canvas_capabilities };
2048
+ const canvas_layer = try webLayerFromManifest(canvas);
2049
+ try std.testing.expect(!canvas_layer.enabled);
2050
+ try std.testing.expectEqual(WebLayerReason.inferred_native_only, canvas_layer.reason);
2051
+
2052
+ // Each web declaration flips the inference.
2053
+ const webview_capabilities = [_][]const u8{"webview"};
2054
+ const by_capability = try webLayerFromManifest(.{ .id = "dev.example.a", .name = "a", .version = "1.0.0", .capabilities = &webview_capabilities });
2055
+ try std.testing.expect(by_capability.enabled);
2056
+ try std.testing.expectEqual(WebLayerReason.capability, by_capability.reason);
2057
+
2058
+ const by_frontend = try webLayerFromManifest(.{ .id = "dev.example.b", .name = "b", .version = "1.0.0", .frontend = .{} });
2059
+ try std.testing.expect(by_frontend.enabled);
2060
+ try std.testing.expectEqual(WebLayerReason.frontend, by_frontend.reason);
2061
+
2062
+ const shell_views = [_]ShellViewMetadata{.{ .label = "content", .kind = "webview", .url = "zero://app/index.html" }};
2063
+ const shell_windows = [_]ShellWindowMetadata{.{ .label = "main", .views = &shell_views }};
2064
+ const by_shell = try webLayerFromManifest(.{ .id = "dev.example.c", .name = "c", .version = "1.0.0", .shell = .{ .windows = &shell_windows } });
2065
+ try std.testing.expect(by_shell.enabled);
2066
+ try std.testing.expectEqual(WebLayerReason.shell_webview, by_shell.reason);
2067
+
2068
+ // The Chromium engine is web intent; the system default alone is not.
2069
+ const by_chromium = try webLayerFromManifest(.{ .id = "dev.example.d", .name = "d", .version = "1.0.0", .web_engine = "chromium" });
2070
+ try std.testing.expect(by_chromium.enabled);
2071
+ try std.testing.expectEqual(WebLayerReason.chromium_engine, by_chromium.reason);
2072
+
2073
+ // The RESOLVED engine decides, not the raw manifest value: a system
2074
+ // manifest packaged with `--web-engine chromium` ships the layer.
2075
+ const by_resolved_chromium = try webLayer(.{ .id = "dev.example.i", .name = "i", .version = "1.0.0" }, .chromium);
2076
+ try std.testing.expect(by_resolved_chromium.enabled);
2077
+ try std.testing.expectEqual(WebLayerReason.chromium_engine, by_resolved_chromium.reason);
2078
+
2079
+ // Explicit overrides.
2080
+ const included = try webLayerFromManifest(.{ .id = "dev.example.e", .name = "e", .version = "1.0.0", .webview_layer = "include" });
2081
+ try std.testing.expect(included.enabled);
2082
+ const excluded = try webLayerFromManifest(.{ .id = "dev.example.f", .name = "f", .version = "1.0.0", .webview_layer = "exclude" });
2083
+ try std.testing.expect(!excluded.enabled);
2084
+ try std.testing.expectEqual(WebLayerReason.declared_exclude, excluded.reason);
2085
+
2086
+ // Contradictions and typos are refused, never resolved silently —
2087
+ // including an exclude against a flag-resolved Chromium engine.
2088
+ try std.testing.expectError(error.WebViewLayerConflict, webLayerFromManifest(.{ .id = "dev.example.g", .name = "g", .version = "1.0.0", .capabilities = &webview_capabilities, .webview_layer = "exclude" }));
2089
+ try std.testing.expectError(error.WebViewLayerConflict, webLayer(.{ .id = "dev.example.j", .name = "j", .version = "1.0.0", .webview_layer = "exclude" }, .chromium));
2090
+ try std.testing.expectError(error.InvalidWebViewLayer, webLayerFromManifest(.{ .id = "dev.example.h", .name = "h", .version = "1.0.0", .webview_layer = "never" }));
2091
+ }
2092
+
2093
+ test "web layer --web-layer flag beats the manifest field like -Dweb-layer does" {
2094
+ const canvas_capabilities = [_][]const u8{ "native_views", "gpu_surfaces" };
2095
+ const canvas: Metadata = .{ .id = "dev.example.canvas", .name = "canvas", .version = "1.0.0", .capabilities = &canvas_capabilities };
2096
+ const webview_capabilities = [_][]const u8{"webview"};
2097
+ const web: Metadata = .{ .id = "dev.example.web", .name = "web", .version = "1.0.0", .capabilities = &webview_capabilities };
2098
+
2099
+ // An include flag that changes the outcome names itself as the cause.
2100
+ const forced_in = try webLayerResolved(canvas, .system, .include);
2101
+ try std.testing.expect(forced_in.enabled);
2102
+ try std.testing.expectEqual(WebLayerReason.declared_include, forced_in.reason);
2103
+ try std.testing.expectEqualStrings("declared: --web-layer include", forced_in.sourceText());
2104
+
2105
+ // A flag that merely confirms the inference keeps the manifest's own
2106
+ // richer reason, so graph-forwarded packages report like hand-run ones.
2107
+ const confirmed = try webLayerResolved(web, .system, .include);
2108
+ try std.testing.expect(confirmed.enabled);
2109
+ try std.testing.expectEqual(WebLayerReason.capability, confirmed.reason);
2110
+ try std.testing.expectEqualStrings("declared: capabilities", confirmed.sourceText());
2111
+ const confirmed_off = try webLayerResolved(canvas, .system, .exclude);
2112
+ try std.testing.expect(!confirmed_off.enabled);
2113
+ try std.testing.expectEqual(WebLayerReason.inferred_native_only, confirmed_off.reason);
2114
+
2115
+ // An exclude flag against a web declaration is the same refused
2116
+ // conflict as a manifest exclude — including a resolved Chromium engine.
2117
+ try std.testing.expectError(error.WebViewLayerConflict, webLayerResolved(web, .system, .exclude));
2118
+ try std.testing.expectError(error.WebViewLayerConflict, webLayerResolved(canvas, .chromium, .exclude));
2119
+
2120
+ // `--web-layer auto` overrides a manifest exclude back to inference,
2121
+ // exactly as `-Dweb-layer=auto` does in the build graph.
2122
+ const reopened = try webLayerResolved(.{ .id = "dev.example.k", .name = "k", .version = "1.0.0", .capabilities = &webview_capabilities, .webview_layer = "exclude" }, .system, .auto);
2123
+ try std.testing.expect(reopened.enabled);
2124
+ try std.testing.expectEqual(WebLayerReason.capability, reopened.reason);
2125
+
2126
+ // No flag: identical to `webLayer` (the manifest field decides).
2127
+ const plain = try webLayerResolved(canvas, .system, null);
2128
+ try std.testing.expect(!plain.enabled);
2129
+ try std.testing.expectEqual(WebLayerReason.inferred_native_only, plain.reason);
2130
+
2131
+ // The flag parser shares the contract's vocabulary.
2132
+ try std.testing.expectEqual(WebViewLayerSetting.include, parseWebViewLayerSetting("include").?);
2133
+ try std.testing.expectEqual(WebViewLayerSetting.exclude, parseWebViewLayerSetting("exclude").?);
2134
+ try std.testing.expectEqual(WebViewLayerSetting.auto, parseWebViewLayerSetting("auto").?);
2135
+ try std.testing.expectEqual(null, parseWebViewLayerSetting("never"));
2136
+ }
2137
+
2138
+ test "validate rejects a web-declaring manifest that excludes the web layer" {
2139
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
2140
+ defer arena.deinit();
2141
+ const gpa = arena.allocator();
2142
+ var cwd = std.Io.Dir.cwd();
2143
+ const root = ".zig-cache/test-validate-web-layer-conflict";
2144
+ try cwd.deleteTree(std.testing.io, root);
2145
+ defer cwd.deleteTree(std.testing.io, root) catch {};
2146
+ try cwd.createDirPath(std.testing.io, root);
2147
+ try cwd.writeFile(std.testing.io, .{ .sub_path = root ++ "/app.zon", .data =
2148
+ \\.{
2149
+ \\ .id = "dev.example.app",
2150
+ \\ .name = "demo",
2151
+ \\ .version = "1.0.0",
2152
+ \\ .capabilities = .{"webview"},
2153
+ \\ .webview_layer = "exclude",
2154
+ \\}
2155
+ });
2156
+
2157
+ const result = try validateFile(gpa, std.testing.io, root ++ "/app.zon");
2158
+ try std.testing.expect(!result.ok);
2159
+ try std.testing.expect(std.mem.indexOf(u8, result.message, ".webview_layer = \"exclude\"") != null);
2160
+ try std.testing.expect(std.mem.indexOf(u8, result.message, "declares web content") != null);
2161
+
2162
+ // A native-only manifest with the same exclude is valid.
2163
+ try cwd.writeFile(std.testing.io, .{ .sub_path = root ++ "/app.zon", .data =
2164
+ \\.{
2165
+ \\ .id = "dev.example.app",
2166
+ \\ .name = "demo",
2167
+ \\ .version = "1.0.0",
2168
+ \\ .capabilities = .{"gpu_surfaces"},
2169
+ \\ .webview_layer = "exclude",
2170
+ \\}
2171
+ });
2172
+ const native_only = try validateFile(gpa, std.testing.io, root ++ "/app.zon");
2173
+ try std.testing.expect(native_only.ok);
2174
+
2175
+ // A typo in the setting is its own teaching error.
2176
+ try cwd.writeFile(std.testing.io, .{ .sub_path = root ++ "/app.zon", .data =
2177
+ \\.{
2178
+ \\ .id = "dev.example.app",
2179
+ \\ .name = "demo",
2180
+ \\ .version = "1.0.0",
2181
+ \\ .webview_layer = "never",
2182
+ \\}
2183
+ });
2184
+ const invalid = try validateFile(gpa, std.testing.io, root ++ "/app.zon");
2185
+ try std.testing.expect(!invalid.ok);
2186
+ try std.testing.expect(std.mem.indexOf(u8, invalid.message, "webview_layer is invalid") != null);
2187
+ }
2188
+
1923
2189
  test "manifest validates the theme pack name" {
1924
2190
  const metadata = try parseText(std.testing.allocator,
1925
2191
  \\.{