@native-sdk/cli 0.8.4 → 0.9.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 (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -12,7 +12,7 @@ Two rules resolve most failures:
12
12
  - Operations on the outside world take a `std.Io` first (or right after the receiver). Get one from `init.io` in `main(init: std.process.Init)`, from `std.testing.io` in tests, or from `std.Io.Threaded` in code with no `Init` to thread through.
13
13
  - Containers are unmanaged: initialize with `.empty` and pass the allocator to every mutating call.
14
14
 
15
- In a UiApp, `update` never sees an `Io` — persistence, subprocesses, HTTP, clocks, and timers go through the typed effects channel (`fx.readFile`, `fx.spawn`, `fx.fetch`, `fx.wallMs`, `fx.startTimer`; see `native skills get native-ui`). Raw `std.Io` belongs in `main`, tests, and standalone tools. And because Zig analyzes lazily, a 0.15-ism can hide in code only one build path references: run BOTH `zig build` and `zig build test` before calling a change done.
15
+ In a UiApp, `update` never sees an `Io` — persistence, record and relational storage, secure credentials, subprocesses, HTTP, clocks, and timers go through the typed effects channel (`fx.persist`, `fx.storeSet`/`storeGet`/`storeDelete`/`storeScan`/`storeSetMany`, `fx.dbQuery`/`dbExec`, `fx.credentialsSet`/`credentialsGet`/`credentialsDelete`, `fx.readFile`/`appendFile`/`statFile`/`deleteFile`/streaming file verbs, `fx.spawn`, `fx.fetch`, `fx.wallMs`, `fx.startTimer`; see `native skills get native-ui`). Whole-file IO stays capped at 1 MiB; streamed reads deliver 256-KiB chunks, and streamed writes finalize atomically on close. External raw paths require the `filesystem` permission, while the app's six resolved directories are exempt after symlink-safe canonicalization. Raw `std.Io` belongs in `main`, tests, and standalone tools. Record-store apps declare `"store"`; relational apps declare `"sqlite"`; credentials require both the `"credentials"` capability and permission. Credential Msg arms carry `EffectCredentialsResult`; consume successful get bytes immediately and never retain them in Model. The engine owns database paths and app-scoped credential namespaces, while every result still returns as a Msg and crosses the replay journal (credential bytes are redacted). Use `TestHarness().createWithRelationalStore` for a hermetic in-memory relational database and `TestHarness().createWithCredentials` for a hermetic in-memory credential store. And because Zig analyzes lazily, a 0.15-ism can hide in code only one build path references: run BOTH `zig build` and `zig build test` before calling a change done.
16
16
 
17
17
  ## error: struct 'heap' has no member named 'GeneralPurposeAllocator' — allocators come from `main(init: std.process.Init)`
18
18
 
@@ -20,7 +20,7 @@ native skills get native-ui
20
20
  native skills get ts-core
21
21
  ```
22
22
 
23
- Use `native skills get core` for initial orientation. For the default app-authoring path, load **both** `native-ui` (views, bindings, the app loop) and `ts-core` (the TypeScript subset, effects, subscriptions, and modules) before implementing. Use `native skills get core --full` when work reaches lower-level runtime wiring, WebViews, bridge/security, native capabilities, packaging, or debugging. Use `native skills get automation` when testing a running app, taking snapshots, requesting reloads, or using the built-in automation server. Use `native skills get zig` only for an existing Zig core, a toolkit extension, SDK implementation work, or a Zig 0.16 compile error.
23
+ Use `native skills get core` for initial orientation. For the default app-authoring path, load **both** `native-ui` (views, bindings, the app loop) and `ts-core` (the TypeScript subset, effects, subscriptions, and modules) before implementing. Load `ts-services` too when the tree has `src/services/` or ordinary TypeScript needs filesystem/process/JSON/regex/Map/Date/class work behind `Cmd.request`. Use `native skills get core --full` when work reaches lower-level runtime wiring, WebViews, bridge/security, native capabilities, packaging, or debugging. Use `native skills get automation` when testing a running app, taking snapshots, requesting reloads, or using the built-in automation server. Use `native skills get zig` only for an existing Zig core, a toolkit extension, SDK implementation work, or a Zig 0.16 compile error.
24
24
 
25
25
  ## Quick orientation
26
26
 
@@ -0,0 +1,3 @@
1
+ const relational = @import("native_sdk").relational_store;
2
+
3
+ pub const migrations = [_]relational.Migration{};
@@ -0,0 +1,20 @@
1
+ //! Generated-runner stub for apps without src/services/.
2
+ pub const enabled = false;
3
+ pub const protocol_version: u8 = 3;
4
+ pub const compiler_version = "";
5
+ pub const inproc_symbol_prefix = "nsc_svc_";
6
+ pub const contract_fingerprint = [_]u8{0} ** 32;
7
+ pub const Operation = struct { name: []const u8, index: u16, deadline_ms: ?u32, cancellable: bool, streaming: bool, in_flight: u8 };
8
+ pub const operations = [_]Operation{};
9
+ pub fn indexOf(name: []const u8) ?u16 {
10
+ _ = name;
11
+ return null;
12
+ }
13
+ pub fn operationAt(index: u16) ?Operation {
14
+ _ = index;
15
+ return null;
16
+ }
17
+ pub fn isStreaming(index: u16) bool {
18
+ _ = index;
19
+ return false;
20
+ }
@@ -2,6 +2,7 @@ const std = @import("std");
2
2
  const build_options = @import("build_options");
3
3
  const native_sdk = @import("native_sdk");
4
4
  const app_manifest = @import("app_manifest_zon");
5
+ const built_relational_migrations = @import("relational_migrations");
5
6
  const manifest_shortcuts = if (@hasField(@TypeOf(app_manifest), "shortcuts")) app_manifest.shortcuts else .{};
6
7
  const manifest_windows = if (@hasField(@TypeOf(app_manifest), "windows")) app_manifest.windows else .{};
7
8
 
@@ -54,6 +55,17 @@ pub const RunOptions = struct {
54
55
  security: native_sdk.SecurityPolicy = .{},
55
56
  menus: []const native_sdk.Menu = &.{},
56
57
  shortcuts: ?[]const native_sdk.Shortcut = null,
58
+ /// Filled by `runWithOptions` from the manifest capability. App entry
59
+ /// points do not set this themselves; the field only carries the owned
60
+ /// binding uniformly into each platform's runtime options.
61
+ record_store: ?native_sdk.RecordStoreBinding = null,
62
+ relational_store: ?native_sdk.RelationalStoreBinding = null,
63
+ credentials_enabled: bool = false,
64
+ file_access: ?native_sdk.FileAccessBinding = null,
65
+ /// Migration/testing switch. Shipping defaults to the final enforced
66
+ /// posture; set false for the preceding warn-only behavior.
67
+ file_access_enforce: bool = true,
68
+ relational_migrations: []const native_sdk.relational_store.Migration = &built_relational_migrations.migrations,
57
69
 
58
70
  fn appInfo(self: RunOptions, buffers: *StateBuffers) native_sdk.AppInfo {
59
71
  var info: native_sdk.AppInfo = .{
@@ -98,6 +110,7 @@ pub const RunOptions = struct {
98
110
  info.main_window.always_on_top = manifestShellStartupBool("always_on_top", false);
99
111
  info.main_window.click_through = manifestShellStartupBool("click_through", false);
100
112
  info.main_window.activate_on_show = manifestShellStartupBool("activate_on_show", true);
113
+ info.main_window.allows_fullscreen = manifestShellStartupBool("allows_fullscreen", true);
101
114
  // Min-size floors ride the create call like the titlebar:
102
115
  // the scene re-applies size/title later, but the window's
103
116
  // enforced floor is host state from the first frame on.
@@ -164,10 +177,12 @@ fn manifestWindow(comptime window: anytype, comptime index: usize) native_sdk.Wi
164
177
  .restore_state = windowBool(window, "restore_state", true),
165
178
  .restore_policy = windowRestorePolicy(window),
166
179
  .titlebar = windowTitlebarStyle(window),
180
+ .show = if (windowBool(window, "initially_hidden", false)) .hidden else .immediate,
167
181
  .transparent = windowBool(window, "transparent", false),
168
182
  .always_on_top = windowBool(window, "always_on_top", false),
169
183
  .click_through = windowBool(window, "click_through", false),
170
184
  .activate_on_show = windowBool(window, "activate_on_show", true),
185
+ .allows_fullscreen = windowBool(window, "allows_fullscreen", true),
171
186
  .min_width = windowMinSize(window, "min_width"),
172
187
  .min_height = windowMinSize(window, "min_height"),
173
188
  .close_policy = windowClosePolicy(window),
@@ -259,6 +274,7 @@ fn manifestShellStartupShowMode() native_sdk.WindowShowMode {
259
274
  if (comptime !@hasField(@TypeOf(shell), "windows")) return .immediate;
260
275
  if (comptime shell.windows.len == 0) return .immediate;
261
276
  const window = shell.windows[0];
277
+ if (comptime windowBool(window, "initially_hidden", false)) return .hidden;
262
278
  if (comptime !@hasField(@TypeOf(window), "views")) return .immediate;
263
279
  inline for (window.views) |view| {
264
280
  if (comptime @hasField(@TypeOf(view), "kind")) {
@@ -431,6 +447,35 @@ fn manifestDeclaresTrayCapability() bool {
431
447
  return false;
432
448
  }
433
449
 
450
+ /// Whether app.zon declares the Tier-2 record store. This is comptime so
451
+ /// apps without the capability never analyze the SQLite open/deinit path.
452
+ fn manifestDeclaresStore() bool {
453
+ if (comptime !@hasField(@TypeOf(app_manifest), "capabilities")) return false;
454
+ inline for (app_manifest.capabilities) |capability| {
455
+ const name: []const u8 = capability;
456
+ if (comptime std.mem.eql(u8, name, "store")) return true;
457
+ }
458
+ return false;
459
+ }
460
+
461
+ fn manifestDeclaresSqlite() bool {
462
+ if (comptime !@hasField(@TypeOf(app_manifest), "capabilities")) return false;
463
+ inline for (app_manifest.capabilities) |capability| {
464
+ const name: []const u8 = capability;
465
+ if (comptime std.mem.eql(u8, name, "sqlite")) return true;
466
+ }
467
+ return false;
468
+ }
469
+
470
+ fn manifestDeclaresCredentials() bool {
471
+ if (comptime !@hasField(@TypeOf(app_manifest), "capabilities")) return false;
472
+ inline for (app_manifest.capabilities) |capability| {
473
+ const name: []const u8 = capability;
474
+ if (comptime std.mem.eql(u8, name, "credentials")) return true;
475
+ }
476
+ return false;
477
+ }
478
+
434
479
  fn shortcutModifiers(comptime shortcut: anytype) native_sdk.ShortcutModifiers {
435
480
  const values = if (@hasField(@TypeOf(shortcut), "modifiers")) shortcut.modifiers else .{};
436
481
  var modifiers: native_sdk.ShortcutModifiers = .{};
@@ -462,14 +507,82 @@ pub fn runWithOptions(app: native_sdk.App, options: RunOptions, init: std.proces
462
507
  if (init.environ_map.get("NATIVE_SDK_SESSION_REPLAY")) |journal_path| {
463
508
  return runSessionReplay(app, options, init, journal_path);
464
509
  }
510
+ const RecordStoreType = if (comptime manifestDeclaresStore()) native_sdk.RecordStore else void;
511
+ var record_store_value: RecordStoreType = undefined;
512
+ var record_store_open = false;
513
+ var resolved_options = options;
514
+ resolved_options.credentials_enabled = manifestDeclaresCredentials();
515
+ var file_root_buffers: [6][1024]u8 = undefined;
516
+ var file_roots: [6][]const u8 = undefined;
517
+ const resolved_file_dirs = native_sdk.app_dirs.resolve(
518
+ .{ .name = options.bundle_id },
519
+ native_sdk.app_dirs.currentPlatform(),
520
+ native_sdk.debug.envFromMap(init.environ_map),
521
+ native_sdk.app_dirs.Buffers.fromArray(1024, &file_root_buffers),
522
+ ) catch null;
523
+ var file_root_count: usize = 0;
524
+ if (resolved_file_dirs) |dirs| {
525
+ file_roots = .{ dirs.config, dirs.cache, dirs.data, dirs.state, dirs.logs, dirs.temp };
526
+ file_root_count = file_roots.len;
527
+ }
528
+ // Fail closed if app-dir resolution is unavailable: a filesystem grant
529
+ // still opens arbitrary paths, while an ungranted app gets no accidental
530
+ // unrestricted fallback merely because HOME/XDG data was malformed.
531
+ resolved_options.file_access = .{
532
+ .roots = file_roots[0..file_root_count],
533
+ .permitted = native_sdk.security.hasPermission(options.security.permissions, native_sdk.security.permission_filesystem),
534
+ .enforce = options.file_access_enforce,
535
+ };
536
+ if (comptime manifestDeclaresStore()) {
537
+ var data_dir_buffer: [512]u8 = undefined;
538
+ const app_data_dir = native_sdk.app_dirs.resolveOne(
539
+ .{ .name = options.bundle_id },
540
+ native_sdk.app_dirs.currentPlatform(),
541
+ native_sdk.debug.envFromMap(init.environ_map),
542
+ .data,
543
+ &data_dir_buffer,
544
+ ) catch return error.StoreDataDirUnavailable;
545
+ try std.Io.Dir.cwd().createDirPath(init.io, app_data_dir);
546
+ record_store_value = try native_sdk.RecordStore.open(std.heap.page_allocator, app_data_dir);
547
+ record_store_open = true;
548
+ resolved_options.record_store = record_store_value.binding();
549
+ }
550
+ defer if (comptime manifestDeclaresStore()) {
551
+ if (record_store_open) record_store_value.deinit();
552
+ };
553
+ const RelationalStoreType = if (comptime manifestDeclaresSqlite()) native_sdk.RelationalStore else void;
554
+ var relational_store_value: RelationalStoreType = undefined;
555
+ var relational_store_open = false;
556
+ if (comptime manifestDeclaresSqlite()) {
557
+ var data_dir_buffer: [512]u8 = undefined;
558
+ const app_data_dir = native_sdk.app_dirs.resolveOne(
559
+ .{ .name = options.bundle_id },
560
+ native_sdk.app_dirs.currentPlatform(),
561
+ native_sdk.debug.envFromMap(init.environ_map),
562
+ .data,
563
+ &data_dir_buffer,
564
+ ) catch return error.SqliteDataDirUnavailable;
565
+ try std.Io.Dir.cwd().createDirPath(init.io, app_data_dir);
566
+ const open_result = try native_sdk.RelationalStore.openMigrated(std.heap.page_allocator, app_data_dir, options.relational_migrations);
567
+ switch (open_result.outcome) {
568
+ .ok => relational_store_value = open_result.database.?,
569
+ .migrate_failed => return error.SqliteMigrationFailed,
570
+ .version_unknown => return error.SqliteVersionUnknown,
571
+ }
572
+ relational_store_open = true;
573
+ resolved_options.relational_store = relational_store_value.binding();
574
+ }
575
+ defer if (comptime manifestDeclaresSqlite()) {
576
+ if (relational_store_open) relational_store_value.deinit();
577
+ };
465
578
  if (comptime std.mem.eql(u8, build_options.platform, "macos")) {
466
- try runMacos(app, options, init);
579
+ try runMacos(app, resolved_options, init);
467
580
  } else if (comptime std.mem.eql(u8, build_options.platform, "linux")) {
468
- try runLinux(app, options, init);
581
+ try runLinux(app, resolved_options, init);
469
582
  } else if (comptime std.mem.eql(u8, build_options.platform, "windows")) {
470
- try runWindows(app, options, init);
583
+ try runWindows(app, resolved_options, init);
471
584
  } else {
472
- try runNull(app, options, init);
585
+ try runNull(app, resolved_options, init);
473
586
  }
474
587
  }
475
588
 
@@ -525,6 +638,10 @@ fn runNull(app: native_sdk.App, options: RunOptions, init: std.process.Init) !vo
525
638
  .shortcuts = shortcuts,
526
639
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
527
640
  .window_state_store = store,
641
+ .record_store = options.record_store,
642
+ .relational_store = options.relational_store,
643
+ .credentials_enabled = options.credentials_enabled,
644
+ .file_access = options.file_access,
528
645
  .environ = init.minimal.environ,
529
646
  .session_recorder = session_recorder,
530
647
  });
@@ -589,6 +706,10 @@ fn runMacos(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
589
706
  .shortcuts = shortcuts,
590
707
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
591
708
  .window_state_store = store,
709
+ .record_store = options.record_store,
710
+ .relational_store = options.relational_store,
711
+ .credentials_enabled = options.credentials_enabled,
712
+ .file_access = options.file_access,
592
713
  .environ = init.minimal.environ,
593
714
  .session_recorder = session_recorder,
594
715
  });
@@ -650,6 +771,10 @@ fn runLinux(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
650
771
  .shortcuts = shortcuts,
651
772
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
652
773
  .window_state_store = store,
774
+ .record_store = options.record_store,
775
+ .relational_store = options.relational_store,
776
+ .credentials_enabled = options.credentials_enabled,
777
+ .file_access = options.file_access,
653
778
  .environ = init.minimal.environ,
654
779
  .session_recorder = session_recorder,
655
780
  });
@@ -710,6 +835,10 @@ fn runWindows(app: native_sdk.App, options: RunOptions, init: std.process.Init)
710
835
  .shortcuts = shortcuts,
711
836
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
712
837
  .window_state_store = store,
838
+ .record_store = options.record_store,
839
+ .relational_store = options.relational_store,
840
+ .credentials_enabled = options.credentials_enabled,
841
+ .file_access = options.file_access,
713
842
  .environ = init.minimal.environ,
714
843
  .session_recorder = session_recorder,
715
844
  });
@@ -25,8 +25,12 @@
25
25
  //! from src/app.native in Debug.
26
26
  //! menus/shortcuts a core exporting `commandMsg(name): Msg | null`
27
27
  //! receives command events (menus, shortcuts, chrome
28
- //! tabs) as ordinary Msgs; without the export command
29
- //! events stay host-handled only.
28
+ //! tabs, status-item rows) as ordinary Msgs; without
29
+ //! the export command events stay host-handled only.
30
+ //! status item a core exporting `statusItem(model)` supplies the
31
+ //! install-time icon/click hooks and live menu-bar
32
+ //! presentation + rows; the adapter patches the two
33
+ //! live parts independently after committed updates.
30
34
  //! host events the adapter wires the core's opt-in channels from
31
35
  //! its exports (export exists -> wired): `frameMsg`
32
36
  //! (presented frames), `keyMsg` (the app-level key
@@ -58,6 +62,10 @@ const runner = @import("runner");
58
62
  const native_sdk = @import("native_sdk");
59
63
  const manifest = @import("app_manifest_zon");
60
64
  pub const core = @import("core.zig");
65
+ const services = @import("services.zig");
66
+ const service_carrier = @import("service_carrier.zig");
67
+ const relational_migrations = @import("migrations.zig");
68
+ const window_views = @import("window_views.zig");
61
69
 
62
70
  pub const panic = std.debug.FullPanic(native_sdk.debug.capturePanic);
63
71
 
@@ -92,6 +100,10 @@ pub fn main(init: std.process.Init) !void {
92
100
  .theme = comptime runner.manifestThemePack(),
93
101
  .theme_accent = comptime runner.manifestThemeAccent(),
94
102
  };
103
+ if (comptime @hasDecl(core.Model, "windows")) {
104
+ options.window_view = window_views.build;
105
+ options.fragment_watch = .{ .fragments = &window_views.fragments, .io = init.io };
106
+ }
95
107
  if (comptime @hasDecl(core, "commandMsg")) {
96
108
  // Menus, shortcuts, and chrome tabs dispatch through the core's
97
109
  // exported command mapper.
@@ -111,19 +123,68 @@ pub fn main(init: std.process.Init) !void {
111
123
  .cache,
112
124
  &cache_dir_buffer,
113
125
  ) catch "";
114
- // The durable per-app data directory, resolved by the same platform
115
- // convention as Zig-core apps. TS cores request it through the
116
- // ordinary journaled envMsgs boundary under `app_data_dir_env`; it
117
- // is framework-provided rather than trusted from the ambient
118
- // environment, so package launch cwd and env differences disappear.
126
+ // The durable per-app data directory, resolved by the platform app-data
127
+ // convention and keyed by the manifest's stable bundle identity. TS cores
128
+ // request it through the ordinary journaled envMsgs boundary under
129
+ // `app_data_dir_env`; it is framework-provided rather than trusted from
130
+ // the ambient environment, so package launch cwd and env differences
131
+ // disappear.
119
132
  var data_dir_buffer: [512]u8 = undefined;
120
133
  const app_data_dir = native_sdk.app_dirs.resolveOne(
121
- .{ .name = manifest.name },
134
+ // Durable state follows the reverse-DNS bundle identity, not the
135
+ // mutable short machine name. Two installed apps may share a name;
136
+ // their manifest ids are the stable isolation boundary.
137
+ .{ .name = manifest.id },
122
138
  native_sdk.app_dirs.currentPlatform(),
123
139
  native_sdk.debug.envFromMap(init.environ_map),
124
140
  .data,
125
141
  &data_dir_buffer,
126
142
  ) catch "";
143
+ if (app_data_dir.len > 0) std.Io.Dir.cwd().createDirPath(init.io, app_data_dir) catch {};
144
+
145
+ // TypeScript services, on the build-selected carrier (service_carrier.zig).
146
+ // In-process (explicit opt-in): the service archive is linked into this
147
+ // binary and ServicePool runs one instance per worker thread. Child (the
148
+ // auto/default carrier): a lazily-spawned sibling executable with an
149
+ // explicit environment allowlist and the app data directory as its cwd.
150
+ // Either way, replay never calls the binding, so nothing starts under replay.
151
+ const use_pool = comptime (services.enabled and service_carrier.kind == .in_process);
152
+ const use_child = comptime (services.enabled and !use_pool);
153
+ var service_env = std.process.Environ.Map.init(std.heap.page_allocator);
154
+ defer service_env.deinit();
155
+ var service_path_buffer: [std.Io.Dir.max_path_bytes]u8 = undefined;
156
+ const ChildTransport = native_sdk.ServiceHost(services);
157
+ const PoolTransport = native_sdk.ServicePool(services);
158
+ var child_transport: if (use_child) ChildTransport else void = undefined;
159
+ var pool_transport: if (use_pool) PoolTransport else void = undefined;
160
+ if (comptime use_child) {
161
+ const env_keys = init.environ_map.keys();
162
+ const env_values = init.environ_map.values();
163
+ for (env_keys, env_values) |key, value| {
164
+ if (native_sdk.serviceEnvironmentVariableAllowed(key)) service_env.put(key, value) catch {};
165
+ }
166
+ const service_path = siblingServiceHostPath(init.io, &service_path_buffer);
167
+ child_transport = ChildTransport.init(
168
+ std.heap.page_allocator,
169
+ init.io,
170
+ service_path,
171
+ app_data_dir,
172
+ &service_env,
173
+ );
174
+ }
175
+ if (comptime use_pool) {
176
+ // The pool's cwd holds the cooperative-cancellation markers and
177
+ // stream-relay files; the service operations themselves run with the
178
+ // app process's own working directory.
179
+ pool_transport = PoolTransport.init(
180
+ std.heap.page_allocator,
181
+ init.io,
182
+ app_data_dir,
183
+ .{ .max_workers = service_carrier.pool_workers },
184
+ );
185
+ }
186
+ defer if (comptime use_child) child_transport.deinit();
187
+ defer if (comptime use_pool) pool_transport.deinit();
127
188
  // app.zon-declared images, read once at launch (bounded; a missing or
128
189
  // over-bound file skips its entry and the views keep their fallback)
129
190
  // and registered by the adapter on the installing frame.
@@ -157,6 +218,65 @@ pub fn main(init: std.process.Init) !void {
157
218
  }
158
219
  }
159
220
 
221
+ // Model persistence is a build-time capability: without `"persist"`
222
+ // this branch (store, paths, binding) is not analyzed into the app. A
223
+ // replay launch never reads the live snapshot; its journal feeds the
224
+ // recorded restore result before the installing app-start event.
225
+ var persist_store_value: native_sdk.PersistStore = undefined;
226
+ var persist_coordinator_value: native_sdk.persist_store.Coordinator = undefined;
227
+ var persist_coordinator_started = false;
228
+ var persist_host_value: PersistHost = .{};
229
+ var persist_outcome_handle: native_sdk.ChannelHandle = .{};
230
+ var persist_restore_value: native_sdk.persist_store.RestoreResult = .{ .outcome = .none };
231
+ var persist_options: ?Adapter.PersistOptions = null;
232
+ if (comptime manifestDeclaresPersist()) {
233
+ const config = comptime manifestPersistConfig();
234
+ comptime Adapter.validatePersistRoutes(.{
235
+ .ok = config.restore.ok,
236
+ .none = config.restore.none,
237
+ .err = config.restore.err,
238
+ });
239
+ const replay = init.environ_map.get("NATIVE_SDK_SESSION_REPLAY") != null;
240
+ persist_store_value = native_sdk.PersistStore.init(init.io, std.heap.page_allocator, app_data_dir, .{
241
+ .schema_version = config.version,
242
+ .model_fingerprint = core.sidecar_model_fingerprint,
243
+ .snapshot_format = core.sidecar_snapshot_format,
244
+ });
245
+ persist_host_value.outcome_handle = &persist_outcome_handle;
246
+ if (!replay) {
247
+ persist_restore_value = persist_store_value.restore();
248
+ if (persist_restore_value.used_backup) {
249
+ std.log.warn("model persistence: primary snapshot unavailable or corrupt; restored snapshot.nsd.bak", .{});
250
+ }
251
+ try persist_coordinator_value.startWithOutcomeHandler(
252
+ persist_store_value,
253
+ manifestPersistDebounce(config),
254
+ .{ .context = &persist_host_value, .report_fn = PersistHost.reportOutcome },
255
+ );
256
+ persist_coordinator_started = true;
257
+ persist_host_value.coordinator = &persist_coordinator_value;
258
+ }
259
+ persist_options = .{
260
+ // Replay binds the same named service to a no-op host. The
261
+ // command remains on the wire for fingerprint parity but can
262
+ // never mutate the live snapshot.
263
+ .binding = persist_host_value.binding(),
264
+ .routes = .{
265
+ .ok = config.restore.ok,
266
+ .none = config.restore.none,
267
+ .err = config.restore.err,
268
+ },
269
+ .restore = .{
270
+ .outcome = persist_restore_value.outcome,
271
+ .bytes = persist_restore_value.bytes,
272
+ .migration_from_version = persist_restore_value.migration_from_version,
273
+ },
274
+ .outcome_handle = &persist_outcome_handle,
275
+ };
276
+ }
277
+ defer if (comptime manifestDeclaresPersist()) persist_restore_value.deinit(std.heap.page_allocator);
278
+ defer if (persist_coordinator_started) persist_coordinator_value.deinit();
279
+
160
280
  // The app struct (and any real model) is multi-MB: `create`
161
281
  // heap-allocates and constructs in place, so neither rides the stack.
162
282
  const app_state = try Adapter.create(std.heap.page_allocator, .{
@@ -167,6 +287,18 @@ pub fn main(init: std.process.Init) !void {
167
287
  .image_cache_dir = audio_cache_dir,
168
288
  .boot_images = boot_images_buffer[0..boot_image_count],
169
289
  .env_values = env_values_buffer[0..env_value_count],
290
+ .host_calls = if (comptime use_pool)
291
+ pool_transport.binding()
292
+ else if (comptime use_child)
293
+ child_transport.binding()
294
+ else
295
+ null,
296
+ .service_results = if (comptime services.enabled) .{
297
+ .index_fn = services.indexOf,
298
+ .streaming_fn = services.isStreaming,
299
+ .decode_fn = services.resultDecoder(core),
300
+ } else null,
301
+ .persist = persist_options,
170
302
  }, options);
171
303
  defer app_state.destroy();
172
304
 
@@ -182,9 +314,61 @@ pub fn main(init: std.process.Init) !void {
182
314
  .permissions = app_permissions,
183
315
  .navigation = .{ .allowed_origins = allowed_origins },
184
316
  },
317
+ .relational_migrations = &relational_migrations.migrations,
185
318
  }, init);
186
319
  }
187
320
 
321
+ fn siblingServiceHostPath(io: std.Io, buffer: []u8) []const u8 {
322
+ var executable_buffer: [std.Io.Dir.max_path_bytes]u8 = undefined;
323
+ const len = std.process.executablePath(io, &executable_buffer) catch return "";
324
+ const dir = std.fs.path.dirname(executable_buffer[0..len]) orelse return "";
325
+ const suffix = if (@import("builtin").os.tag == .windows) ".exe" else "";
326
+ return std.fmt.bufPrint(buffer, "{s}/{s}_services{s}", .{ dir, manifest.name, suffix }) catch "";
327
+ }
328
+
329
+ const PersistHost = struct {
330
+ coordinator: ?*native_sdk.persist_store.Coordinator = null,
331
+ outcome_handle: ?*native_sdk.ChannelHandle = null,
332
+
333
+ fn binding(self: *PersistHost) native_sdk.HostCallBinding {
334
+ return .{ .context = self, .send_fn = send, .request_fn = request };
335
+ }
336
+
337
+ fn send(context: *anyopaque, name: []const u8, snapshot: []const u8) void {
338
+ const self: *PersistHost = @ptrCast(@alignCast(context));
339
+ const coordinator = self.coordinator orelse return;
340
+ if (std.mem.eql(u8, name, "core.persist.flush")) {
341
+ coordinator.flush();
342
+ return;
343
+ }
344
+ if (!std.mem.eql(u8, name, "core.persist")) return;
345
+ const outcome = coordinator.enqueue(snapshot);
346
+ if (outcome != .ok) reportOutcome(context, outcome);
347
+ }
348
+
349
+ fn reportOutcome(context: *anyopaque, outcome: native_sdk.persist_store.Outcome) void {
350
+ if (outcome == .ok) return;
351
+ const self: *PersistHost = @ptrCast(@alignCast(context));
352
+ const handle = self.outcome_handle orelse {
353
+ std.log.err("model persistence write failed before its result channel installed: {s}", .{@tagName(outcome)});
354
+ return;
355
+ };
356
+ switch (handle.post(@tagName(outcome))) {
357
+ .accepted => {},
358
+ .dropped_full, .dropped_oversized, .closed => {
359
+ std.log.err("model persistence write failed after its result channel closed: {s}", .{@tagName(outcome)});
360
+ },
361
+ }
362
+ }
363
+
364
+ fn request(context: *anyopaque, name: []const u8, key: u64, payload: []const u8) void {
365
+ _ = context;
366
+ _ = name;
367
+ _ = key;
368
+ _ = payload;
369
+ }
370
+ };
371
+
188
372
  /// The startup window title: the scene's first window title, else the
189
373
  /// manifest display name, else the app name.
190
374
  fn windowTitle() []const u8 {
@@ -251,6 +435,68 @@ fn manifestStringList(comptime m: anytype, comptime field: []const u8) []const [
251
435
  }
252
436
  }
253
437
 
438
+ fn manifestDeclaresPersist() bool {
439
+ comptime {
440
+ for (manifestStringList(manifest, "capabilities")) |capability| {
441
+ if (std.mem.eql(u8, capability, "persist")) {
442
+ if (!@hasField(@TypeOf(manifest), "persist")) {
443
+ @compileError("app.zon declares the persist capability but has no .persist = .{ .version, .restore = .{ .ok, .none, .err } } configuration");
444
+ }
445
+ return true;
446
+ }
447
+ }
448
+ if (@hasField(@TypeOf(manifest), "persist")) {
449
+ @compileError("app.zon configures .persist but does not declare \"persist\" in .capabilities");
450
+ }
451
+ return false;
452
+ }
453
+ }
454
+
455
+ fn ManifestPersistType() type {
456
+ if (@hasField(@TypeOf(manifest), "persist")) return @TypeOf(manifest.persist);
457
+ return void;
458
+ }
459
+
460
+ fn manifestPersistConfig() ManifestPersistType() {
461
+ comptime {
462
+ if (!manifestDeclaresPersist()) unreachable;
463
+ if (manifest.persist.version == 0 or manifest.persist.version > 9_007_199_254_740_991) {
464
+ @compileError("app.zon .persist.version must be a positive exact integer and monotonically increased for every Model shape change");
465
+ }
466
+ if (@hasField(@TypeOf(manifest.persist), "debounce_ms") and manifest.persist.debounce_ms > 60_000) {
467
+ @compileError("app.zon .persist.debounce_ms must be at most 60000");
468
+ }
469
+ validatePersistRoutes(manifest.persist.restore);
470
+ return manifest.persist;
471
+ }
472
+ }
473
+
474
+ fn manifestPersistDebounce(comptime config: anytype) u32 {
475
+ if (@hasField(@TypeOf(config), "debounce_ms")) return config.debounce_ms;
476
+ return 500;
477
+ }
478
+
479
+ fn validatePersistRoutes(comptime routes: anytype) void {
480
+ if (!persistRouteMatches(routes.ok, void)) {
481
+ @compileError("app.zon .persist.restore.ok must name a void Msg arm in src/core.ts");
482
+ }
483
+ if (!persistRouteMatches(routes.none, void)) {
484
+ @compileError("app.zon .persist.restore.none must name a void Msg arm in src/core.ts");
485
+ }
486
+ if (!persistRouteMatches(routes.err, []const u8)) {
487
+ @compileError("app.zon .persist.restore.err must name a one-Uint8Array-field Msg arm in src/core.ts");
488
+ }
489
+ }
490
+
491
+ fn persistRouteMatches(comptime name: []const u8, comptime Payload: type) bool {
492
+ const info = @typeInfo(core.Msg);
493
+ if (info != .@"union") return false;
494
+ inline for (info.@"union".fields) |field| {
495
+ if (std.mem.eql(u8, field.name, name)) return field.type == Payload;
496
+ }
497
+ return false;
498
+ }
499
+
254
500
  fn manifestAllowedOrigins() []const []const u8 {
255
501
  comptime {
256
502
  if (!@hasField(@TypeOf(manifest), "security")) return &.{};