@native-sdk/cli 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (462) hide show
  1. package/README.md +8 -6
  2. package/bin/native.js +2 -1
  3. package/build/app.zig +320 -60
  4. package/build/corewire.zig +53 -0
  5. package/build/test_shards.zig +49 -0
  6. package/build/ts_run.mjs +3 -3
  7. package/build.zig +1796 -83
  8. package/package.json +19 -14
  9. package/packages/core/compile-surface/core.ts +134 -72
  10. package/packages/core/package-lock.json +75 -357
  11. package/packages/core/package.json +25 -4
  12. package/packages/core/scripts/compiler_command.mjs +17 -12
  13. package/packages/core/scripts/compiler_typecheck.mjs +1 -0
  14. package/packages/core/scripts/gen_declarations.mjs +3 -2
  15. package/packages/core/scripts/gen_service_surface.mjs +22 -10
  16. package/packages/core/scripts/install_scriptc.mjs +182 -0
  17. package/packages/core/scripts/invoke_scriptc.mjs +18 -0
  18. package/packages/core/scripts/merge_static_archives.mjs +6 -1
  19. package/packages/core/scripts/npm_static_spike.mjs +2 -2
  20. package/packages/core/scripts/run_external_core_compiler.mjs +22 -10
  21. package/packages/core/scripts/run_external_service_compiler.mjs +15 -15
  22. package/packages/core/scripts/run_library_compiler.mjs +51 -0
  23. package/packages/core/scripts/run_native_tests.mjs +22 -0
  24. package/packages/core/scripts/scriptc-toolchain.json +101 -0
  25. package/packages/core/scripts/scriptc_toolchain.mjs +121 -0
  26. package/packages/core/scripts/stage_external_core.mjs +57 -1
  27. package/packages/core/scripts/surface_manifest_diff.mjs +19 -12
  28. package/packages/core/sdk/bytes.d.ts +2 -0
  29. package/packages/core/sdk/bytes.ts +86 -0
  30. package/packages/core/sdk/core.d.ts +308 -4
  31. package/packages/core/sdk/core.ts +320 -84
  32. package/packages/core/sdk/events.d.ts +247 -0
  33. package/packages/core/sdk/events.ts +230 -2
  34. package/packages/core/sdk/internal/image_identity.d.ts +7 -0
  35. package/packages/core/sdk/internal/image_identity.ts +71 -0
  36. package/packages/core/sdk/internal/markdown_policy.d.ts +5 -0
  37. package/packages/core/sdk/internal/markdown_policy.ts +878 -0
  38. package/packages/core/sdk/text.d.ts +27 -0
  39. package/packages/core/sdk/text.ts +206 -15
  40. package/packages/core/sdk/theme.d.ts +251 -0
  41. package/packages/core/sdk/theme.ts +267 -0
  42. package/packages/core/src/authorization.ts +137 -0
  43. package/packages/core/src/automation_commands.ts +201 -0
  44. package/packages/core/src/automation_interactions.ts +92 -0
  45. package/packages/core/src/bridge_descriptors.ts +104 -0
  46. package/packages/core/src/builtin_coordination.ts +172 -0
  47. package/packages/core/src/canvas_frame_coordination.ts +81 -0
  48. package/packages/core/src/canvas_presentation_lifecycle.ts +84 -0
  49. package/packages/core/src/canvas_scene_observation.ts +145 -0
  50. package/packages/core/src/chart_content.ts +161 -0
  51. package/packages/core/src/chart_plans.ts +432 -0
  52. package/packages/core/src/checker.ts +166 -19
  53. package/packages/core/src/code_content.ts +580 -0
  54. package/packages/core/src/command_coordination.ts +140 -0
  55. package/packages/core/src/component_composition.ts +94 -0
  56. package/packages/core/src/component_construction.ts +149 -0
  57. package/packages/core/src/contract.ts +25 -7
  58. package/packages/core/src/control_appearance.ts +232 -0
  59. package/packages/core/src/control_commands.ts +115 -0
  60. package/packages/core/src/control_content.ts +105 -0
  61. package/packages/core/src/control_geometry.ts +107 -0
  62. package/packages/core/src/control_payloads.ts +119 -0
  63. package/packages/core/src/control_primitives.ts +134 -0
  64. package/packages/core/src/devhost.ts +82 -7
  65. package/packages/core/src/devhost_journal.mjs +30 -7
  66. package/packages/core/src/effect_plans.ts +71 -0
  67. package/packages/core/src/flow_measurement.ts +121 -0
  68. package/packages/core/src/font_registry.ts +37 -0
  69. package/packages/core/src/glyph_atlas.ts +86 -0
  70. package/packages/core/src/gpu_packet_preparation.ts +130 -0
  71. package/packages/core/src/gpu_planning.ts +123 -0
  72. package/packages/core/src/gpu_presentation.ts +55 -0
  73. package/packages/core/src/host_flow.ts +89 -0
  74. package/packages/core/src/host_input_regions.ts +165 -0
  75. package/packages/core/src/image_registry.ts +66 -0
  76. package/packages/core/src/indicator_plans.ts +132 -0
  77. package/packages/core/src/infer.ts +150 -8
  78. package/packages/core/src/input_composition.ts +116 -0
  79. package/packages/core/src/intrinsic_measure.ts +100 -0
  80. package/packages/core/src/layout_coordination.ts +207 -0
  81. package/packages/core/src/leaf_plans.ts +134 -0
  82. package/packages/core/src/markup_development.ts +160 -0
  83. package/packages/core/src/measurement_coordination.ts +185 -0
  84. package/packages/core/src/modules.ts +1 -1
  85. package/packages/core/src/motion_sampling.ts +100 -0
  86. package/packages/core/src/paragraph_layout.ts +192 -0
  87. package/packages/core/src/portable_sources.json +74 -0
  88. package/packages/core/src/portable_sources.ts +17 -0
  89. package/packages/core/src/registered_font.ts +93 -0
  90. package/packages/core/src/render_animation_lifecycle.ts +128 -0
  91. package/packages/core/src/render_coordination.ts +170 -0
  92. package/packages/core/src/render_resources.ts +234 -0
  93. package/packages/core/src/runtime_policy.ts +3930 -0
  94. package/packages/core/src/scalar_text.ts +84 -0
  95. package/packages/core/src/service_contract.ts +2 -1
  96. package/packages/core/src/session_codecs.ts +309 -0
  97. package/packages/core/src/shell_admission.ts +126 -0
  98. package/packages/core/src/shell_coordination.ts +93 -0
  99. package/packages/core/src/sqlite_cli.ts +11 -0
  100. package/packages/core/src/status_validation.ts +232 -0
  101. package/packages/core/src/stream_policy.ts +63 -0
  102. package/packages/core/src/surface_recipes.ts +136 -0
  103. package/packages/core/src/system_admission.ts +60 -0
  104. package/packages/core/src/terminal_paint.ts +436 -0
  105. package/packages/core/src/text_document_width.ts +81 -0
  106. package/packages/core/src/text_measurement_cache.ts +69 -0
  107. package/packages/core/src/text_query_layout.ts +179 -0
  108. package/packages/core/src/text_run_layout.ts +410 -0
  109. package/packages/core/src/text_span_queries.ts +355 -0
  110. package/packages/core/src/typed_ast.ts +18 -1
  111. package/packages/core/src/types.ts +7 -5
  112. package/packages/core/src/vector_effects.ts +98 -0
  113. package/packages/core/src/vector_raster.ts +243 -0
  114. package/packages/core/src/view_components.ts +2415 -0
  115. package/packages/core/src/view_coordination.ts +198 -0
  116. package/packages/core/src/view_frontend.ts +980 -0
  117. package/packages/core/src/widget_audits.ts +202 -0
  118. package/packages/core/src/widget_changes.ts +258 -0
  119. package/packages/core/src/widget_metrics.ts +139 -0
  120. package/packages/core/src/widget_motion.ts +171 -0
  121. package/packages/core/src/widget_paint.ts +272 -0
  122. package/packages/core/src/widget_paint_walk.ts +203 -0
  123. package/packages/core/src/widget_presentation.ts +141 -0
  124. package/packages/core/src/widget_routing.ts +262 -0
  125. package/packages/core/src/window_lifecycle.ts +92 -0
  126. package/packages/core/testing/index.ts +430 -0
  127. package/schemas/app.schema.json +13 -0
  128. package/skill-data/core/SKILL.md +2 -2
  129. package/skill-data/native-ui/SKILL.md +76 -17
  130. package/skill-data/ts-core/SKILL.md +113 -9
  131. package/skill-data/ts-services/SKILL.md +1 -1
  132. package/skill-data/ts-services/references/service-surface.md +264 -144
  133. package/src/app_runner/root.zig +25 -12
  134. package/src/app_runner/ts_compiled_view.zig +1631 -0
  135. package/src/app_runner/ts_core_main.zig +143 -10
  136. package/src/app_runner/ts_core_mobile.zig +24 -12
  137. package/src/automation/server.zig +1 -3
  138. package/src/automation/snapshot.zig +9 -637
  139. package/src/automation/snapshot_reference.zig +656 -0
  140. package/src/automation/snapshot_serialization.zig +566 -0
  141. package/src/platform/linux/gtk_host.c +36 -24
  142. package/src/platform/linux/gtk_pixels.h +118 -0
  143. package/src/platform/linux/gtk_pixels_test.c +241 -0
  144. package/src/platform/linux/root.zig +2 -0
  145. package/src/platform/macos/appkit_host.m +188 -30
  146. package/src/platform/macos/pointer_motion_test.m +96 -0
  147. package/src/platform/macos/scroll_driver_test.m +105 -0
  148. package/src/platform/macos/spectrum_bins.h +34 -0
  149. package/src/platform/macos/spectrum_bins_test.c +56 -0
  150. package/src/platform/macos/text_keyboard_test.m +80 -0
  151. package/src/platform/macos/widget_focus_test.m +66 -0
  152. package/src/platform/null_platform.zig +26 -2
  153. package/src/platform/null_platform_tests.zig +13 -0
  154. package/src/platform/root.zig +1 -0
  155. package/src/platform/types.zig +13 -0
  156. package/src/platform/windows/root.zig +2 -0
  157. package/src/platform/windows/webview2_host.cpp +7 -2
  158. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  159. package/src/primitives/app_manifest/root.zig +2 -0
  160. package/src/primitives/app_manifest/tests.zig +4 -1
  161. package/src/primitives/app_manifest/validation.zig +2 -0
  162. package/src/primitives/canvas/a11y_audit.zig +3 -1
  163. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  164. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  165. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  166. package/src/primitives/canvas/code_content_policy.zig +162 -0
  167. package/src/primitives/canvas/commands.zig +29 -1
  168. package/src/primitives/canvas/component_composition.zig +125 -0
  169. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  170. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  171. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  172. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  173. package/src/primitives/canvas/control_command_policy.zig +75 -0
  174. package/src/primitives/canvas/control_content_policy.zig +90 -0
  175. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  176. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  177. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  178. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  179. package/src/primitives/canvas/events.zig +1027 -1
  180. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  181. package/src/primitives/canvas/frame.zig +92 -23
  182. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  183. package/src/primitives/canvas/gpu.zig +10 -0
  184. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  185. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  186. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  187. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  188. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  189. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  190. package/src/primitives/canvas/intrinsic_measure_policy.zig +128 -0
  191. package/src/primitives/canvas/layout_audit.zig +5 -2
  192. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  193. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  194. package/src/primitives/canvas/markdown.zig +13 -3
  195. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  196. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  197. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  198. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  199. package/src/primitives/canvas/reference.zig +12 -6
  200. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  201. package/src/primitives/canvas/render.zig +48 -0
  202. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  203. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  204. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  205. package/src/primitives/canvas/render_effects.zig +14 -0
  206. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  207. package/src/primitives/canvas/render_images.zig +14 -0
  208. package/src/primitives/canvas/render_layers.zig +14 -0
  209. package/src/primitives/canvas/render_override_policy.zig +119 -0
  210. package/src/primitives/canvas/render_paths.zig +14 -0
  211. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  212. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  213. package/src/primitives/canvas/root.zig +100 -0
  214. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  215. package/src/primitives/canvas/serialization.zig +8 -1
  216. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  217. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  218. package/src/primitives/canvas/terminal_grid.zig +10 -696
  219. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  220. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  221. package/src/primitives/canvas/text.zig +1 -0
  222. package/src/primitives/canvas/text_atlas.zig +113 -0
  223. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  224. package/src/primitives/canvas/text_document_policy.zig +120 -0
  225. package/src/primitives/canvas/text_layout.zig +51 -2
  226. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  227. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  228. package/src/primitives/canvas/text_layout_types.zig +3 -0
  229. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  230. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  231. package/src/primitives/canvas/text_metrics.zig +23 -0
  232. package/src/primitives/canvas/text_query_policy.zig +156 -0
  233. package/src/primitives/canvas/text_run_policy.zig +252 -0
  234. package/src/primitives/canvas/text_scalar_policy.zig +156 -0
  235. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  236. package/src/primitives/canvas/text_spans.zig +280 -8
  237. package/src/primitives/canvas/text_tests.zig +10 -0
  238. package/src/primitives/canvas/tokens.zig +38 -0
  239. package/src/primitives/canvas/ui.zig +250 -83
  240. package/src/primitives/canvas/ui_markup.zig +139 -33
  241. package/src/primitives/canvas/ui_markup_compiled.zig +319 -59
  242. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  243. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  244. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  245. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  246. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  247. package/src/primitives/canvas/ui_markup_view.zig +258 -32
  248. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  249. package/src/primitives/canvas/ui_schema.zig +13 -1
  250. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  251. package/src/primitives/canvas/ui_tests.zig +1 -0
  252. package/src/primitives/canvas/vector.zig +36 -2
  253. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  254. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  255. package/src/primitives/canvas/virtual_extent_policy.zig +292 -0
  256. package/src/primitives/canvas/virtual_extents.zig +99 -3
  257. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  258. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  259. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  260. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  261. package/src/primitives/canvas/widget_layout.zig +673 -128
  262. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  263. package/src/primitives/canvas/widget_metric_policy.zig +126 -0
  264. package/src/primitives/canvas/widget_metrics.zig +45 -6
  265. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  266. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  267. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  268. package/src/primitives/canvas/widget_render.zig +744 -74
  269. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  270. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  271. package/src/primitives/canvas/widget_render_style.zig +94 -0
  272. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  273. package/src/primitives/canvas/widget_routing.zig +75 -0
  274. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  275. package/src/primitives/canvas/widget_runtime.zig +20 -1
  276. package/src/primitives/canvas/widget_semantics.zig +25 -0
  277. package/src/primitives/canvas/widget_text_input.zig +86 -23
  278. package/src/primitives/canvas/widget_text_select.zig +1 -0
  279. package/src/primitives/canvas/widget_tree.zig +8 -1
  280. package/src/primitives/canvas/widgets.zig +42 -12
  281. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  282. package/src/root.zig +21 -0
  283. package/src/runtime/accessibility_policy.zig +122 -0
  284. package/src/runtime/api.zig +28 -0
  285. package/src/runtime/app_dispatch_policy.zig +68 -0
  286. package/src/runtime/authorization_policy.zig +150 -0
  287. package/src/runtime/automation_command_policy.zig +241 -0
  288. package/src/runtime/automation_interaction_policy.zig +107 -0
  289. package/src/runtime/automation_snapshot.zig +52 -22
  290. package/src/runtime/automation_snapshot_reference.zig +290 -0
  291. package/src/runtime/automation_widget_dispatch.zig +267 -355
  292. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  293. package/src/runtime/blob_policy.zig +58 -0
  294. package/src/runtime/blob_reference.zig +64 -0
  295. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  296. package/src/runtime/builtin_bridge.zig +180 -44
  297. package/src/runtime/builtin_coordination_policy.zig +121 -0
  298. package/src/runtime/callback_policy_test_reference.zig +97 -0
  299. package/src/runtime/canvas_drag_policy.zig +94 -0
  300. package/src/runtime/canvas_fonts.zig +38 -10
  301. package/src/runtime/canvas_frame.zig +590 -134
  302. package/src/runtime/canvas_frame_helpers.zig +1 -0
  303. package/src/runtime/canvas_hover_policy.zig +131 -0
  304. package/src/runtime/canvas_images.zig +59 -30
  305. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  306. package/src/runtime/canvas_limits.zig +1 -1
  307. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  308. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  309. package/src/runtime/canvas_widget_context_menu.zig +4 -4
  310. package/src/runtime/canvas_widget_display.zig +110 -9
  311. package/src/runtime/canvas_widget_events.zig +718 -328
  312. package/src/runtime/canvas_widget_runtime.zig +437 -81
  313. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  314. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  315. package/src/runtime/canvas_widget_state.zig +93 -56
  316. package/src/runtime/channel_sources.zig +80 -0
  317. package/src/runtime/command_policy.zig +161 -0
  318. package/src/runtime/component_policy.zig +83 -0
  319. package/src/runtime/core.zig +156 -6
  320. package/src/runtime/desktop_files.zig +189 -0
  321. package/src/runtime/effects.zig +466 -29
  322. package/src/runtime/effects_tests.zig +28 -0
  323. package/src/runtime/file_policy_test_reference.zig +113 -0
  324. package/src/runtime/flow.zig +418 -341
  325. package/src/runtime/flow_reference.zig +1426 -0
  326. package/src/runtime/font_registry_policy.zig +72 -0
  327. package/src/runtime/frame_profile.zig +24 -33
  328. package/src/runtime/gpu_surface_events.zig +97 -35
  329. package/src/runtime/host_event_pump.zig +303 -0
  330. package/src/runtime/host_event_pump_reference.zig +268 -0
  331. package/src/runtime/host_flow_policy.zig +155 -0
  332. package/src/runtime/host_input_regions_policy.zig +156 -0
  333. package/src/runtime/image_registry_policy.zig +94 -0
  334. package/src/runtime/input_composition_policy.zig +138 -0
  335. package/src/runtime/journal_policy.zig +66 -0
  336. package/src/runtime/journal_reference.zig +53 -0
  337. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  338. package/src/runtime/markup_development_policy.zig +91 -0
  339. package/src/runtime/media_surface.zig +40 -1
  340. package/src/runtime/motion_sampling_policy.zig +159 -0
  341. package/src/runtime/recording_policy.zig +42 -0
  342. package/src/runtime/render_animation_policy.zig +206 -0
  343. package/src/runtime/replay_policy.zig +66 -0
  344. package/src/runtime/replay_policy_reference.zig +326 -0
  345. package/src/runtime/replay_progress_policy.zig +64 -0
  346. package/src/runtime/replay_progress_reference.zig +34 -0
  347. package/src/runtime/request_policy_test_reference.zig +188 -0
  348. package/src/runtime/root.zig +13 -0
  349. package/src/runtime/session_blobs.zig +157 -58
  350. package/src/runtime/session_blobs_reference.zig +692 -0
  351. package/src/runtime/session_codec.zig +361 -0
  352. package/src/runtime/session_codec_reference.zig +1027 -0
  353. package/src/runtime/session_journal.zig +246 -983
  354. package/src/runtime/session_record.zig +224 -45
  355. package/src/runtime/session_replay.zig +157 -415
  356. package/src/runtime/session_tests.zig +552 -0
  357. package/src/runtime/shell_admission_policy.zig +225 -0
  358. package/src/runtime/shell_coordination_policy.zig +138 -0
  359. package/src/runtime/shell_layout.zig +126 -1
  360. package/src/runtime/snapshot_policy.zig +60 -0
  361. package/src/runtime/snapshot_reference.zig +64 -0
  362. package/src/runtime/state.zig +16 -0
  363. package/src/runtime/status_validation.zig +190 -0
  364. package/src/runtime/system_admission_policy.zig +140 -0
  365. package/src/runtime/system_services.zig +46 -36
  366. package/src/runtime/tests.zig +1 -0
  367. package/src/runtime/ts_canvas_hooks.zig +261 -0
  368. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  369. package/src/runtime/ts_canvas_icons.zig +234 -0
  370. package/src/runtime/ts_core_host.zig +2325 -411
  371. package/src/runtime/ts_core_host_tests.zig +1982 -0
  372. package/src/runtime/ts_test_host.zig +699 -0
  373. package/src/runtime/ts_ui_app.zig +1087 -45
  374. package/src/runtime/ui_app.zig +1117 -629
  375. package/src/runtime/ui_app_provenance.zig +147 -5
  376. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  377. package/src/runtime/ui_app_tests.zig +619 -9
  378. package/src/runtime/ui_app_window_tests.zig +89 -0
  379. package/src/runtime/view.zig +25 -0
  380. package/src/runtime/view_canvas.zig +30 -6
  381. package/src/runtime/view_coordination_policy.zig +147 -0
  382. package/src/runtime/view_widget_control.zig +51 -14
  383. package/src/runtime/view_widget_scroll.zig +16 -5
  384. package/src/runtime/view_widget_text.zig +153 -68
  385. package/src/runtime/view_widget_tree.zig +460 -56
  386. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  387. package/src/runtime/widget_motion_policy.zig +238 -0
  388. package/src/runtime/window_command_bridge_tests.zig +63 -0
  389. package/src/runtime/window_lifecycle_policy.zig +127 -0
  390. package/src/runtime/window_storage.zig +74 -8
  391. package/src/runtime/window_view_runtime.zig +148 -33
  392. package/src/runtime/window_views.zig +163 -10
  393. package/src/tooling/components/identity_tests.zig +62 -36
  394. package/src/tooling/components/stepper.native +24 -0
  395. package/src/tooling/components/stepper.zig +0 -19
  396. package/src/tooling/components/timeline-item.native +22 -0
  397. package/src/tooling/components/timeline.native +5 -3
  398. package/src/tooling/components/timeline_item.zig +0 -32
  399. package/src/tooling/eject_components.zig +76 -8
  400. package/src/tooling/ios.zig +66 -12
  401. package/src/tooling/manifest.zig +35 -0
  402. package/src/tooling/raw_manifest.zig +6 -0
  403. package/src/tooling/templates.zig +15 -3
  404. package/src/tooling/ts_core.zig +13 -3
  405. package/src/tooling/verbs.zig +22 -0
  406. package/tools/corewire/build_profile.mjs +54 -0
  407. package/tools/corewire/contract_intake.ts +303 -0
  408. package/tools/corewire/contract_intake.zig +82 -0
  409. package/tools/corewire/core.test.ts +166 -0
  410. package/tools/corewire/core_abi.zig +51 -0
  411. package/tools/corewire/core_cases.ts +233 -0
  412. package/tools/corewire/core_contract.ts +407 -0
  413. package/tools/corewire/core_emission.ts +136 -0
  414. package/tools/corewire/core_emission.zig +69 -0
  415. package/tools/corewire/core_goldens.json +3110 -0
  416. package/tools/corewire/core_policy.ts +14 -0
  417. package/tools/corewire/core_policy.zig +48 -0
  418. package/tools/corewire/core_projection.ts +360 -0
  419. package/tools/corewire/core_vocabulary.ts +6 -0
  420. package/tools/corewire/emit.zig +19 -1590
  421. package/tools/corewire/emit_facade.ts +714 -0
  422. package/tools/corewire/emit_facade.zig +10 -3752
  423. package/tools/corewire/emit_mirror.ts +290 -0
  424. package/tools/corewire/emit_profile.ts +50 -0
  425. package/tools/corewire/emit_service.ts +331 -0
  426. package/tools/corewire/emit_service.zig +23 -842
  427. package/tools/corewire/entry.test.ts +95 -0
  428. package/tools/corewire/entry_coordination.ts +127 -0
  429. package/tools/corewire/entry_coordination.zig +190 -0
  430. package/tools/corewire/facade_templates.ts +85 -0
  431. package/tools/corewire/filesystem.test.ts +166 -0
  432. package/tools/corewire/filesystem_coordination.ts +213 -0
  433. package/tools/corewire/filesystem_coordination.zig +245 -0
  434. package/tools/corewire/intake.test.ts +35 -0
  435. package/tools/corewire/intake_cases.ts +55 -0
  436. package/tools/corewire/intake_goldens.json +12237 -0
  437. package/tools/corewire/invocation.test.ts +24 -0
  438. package/tools/corewire/invocation.ts +175 -0
  439. package/tools/corewire/invocation.zig +136 -0
  440. package/tools/corewire/invocation_cases.ts +60 -0
  441. package/tools/corewire/invocation_fixture.ts +33 -0
  442. package/tools/corewire/invocation_goldens.json +1143 -0
  443. package/tools/corewire/invocation_tests.zig +111 -0
  444. package/tools/corewire/invocation_usage.ts +2 -0
  445. package/tools/corewire/lossless_projection.ts +96 -0
  446. package/tools/corewire/main.zig +7 -680
  447. package/tools/corewire/main_reference.zig +415 -0
  448. package/tools/corewire/mirror_templates.ts +55 -0
  449. package/tools/corewire/profile.test.ts +248 -0
  450. package/tools/corewire/profile.zig +56 -0
  451. package/tools/corewire/profile_emission.ts +202 -0
  452. package/tools/corewire/profile_library.json +29 -0
  453. package/tools/corewire/profile_tests.zig +136 -0
  454. package/tools/corewire/service.test.ts +75 -0
  455. package/tools/corewire/service_cases.ts +61 -0
  456. package/tools/corewire/service_contract.zig +40 -146
  457. package/tools/corewire/service_goldens.json +650 -0
  458. package/tools/corewire/service_projection.zig +52 -0
  459. package/tools/corewire/service_templates.ts +14 -0
  460. package/tools/corewire/shim_rt.zig +9 -0
  461. package/tools/corewire/sidecar.zig +267 -1438
  462. package/tools/corewire/emit_profile.zig +0 -521
@@ -1,3766 +1,24 @@
1
- //! core_facade.ts emission: the compiled-core ENTRY MODULE generated
2
- //! from the same contract sidecar the Zig mirror derives from. One
3
- //! sidecar, three projections — the host imports core_shim.zig, an
4
- //! external core compiler consumes this module as its compile entry
5
- //! (with the generated core_profile.json beside it), and the two sides
6
- //! can never skew: types, declaration orders, number classes, wire
7
- //! tags, and the canonical value encoding all derive from one artifact.
8
- //!
9
- //! The emitted module is the generated twin of a hand-written adapter:
10
- //! it imports the AUTHOR'S core module (staged beside it, with its SDK
11
- //! imports resolved to the staged ./sdk/ copies), owns the committed
12
- //! model in module state, and exports the profile-declared dispatch
13
- //! surface:
14
- //!
15
- //! - type re-exports for every named contract-table type, each from its
16
- //! own declaring module (the sidecar's origin facts) — the compiler's
17
- //! sidecar emitter reads the entry module's exported declarations;
18
- //! - the exported-const channel conventions (appearanceMsg, chromeMsg,
19
- //! envMsgs) and the single name-resolved viewUnbound list;
20
- //! - one exported wrapper per model helper, in declaration order (the
21
- //! compiled contract's model_helpers table and helper_call's index
22
- //! space both derive from it), with the inline wholeness proof on
23
- //! every i64-classed helper return;
24
- //! - the designated shape-flag entries (init, coreUpdate, and — for a
25
- //! subscribing contract — coreSubscriptions), whose return shapes
26
- //! restate init_returns_cmd/update_returns_cmd/has_subscriptions;
27
- //! - the ABI dispatch surface (boot_cmd, the nine dispatch entries, the
28
- //! wired channel entries, abi_subscriptions, model_snapshot,
29
- //! persist_snapshot, restore_model, helper_call),
30
- //! decoding inbound payloads with the generated wire codec below and
31
- //! encoding results byte-identically to the transpiler lane;
32
- //! - provable ingress everywhere a wire value crosses into an
33
- //! i64-classed slot: bind to a local, range-guard with ordered
34
- //! comparisons against +-(2^53 - 1) (which excludes NaN), and state
35
- //! wholeness with Math.trunc at the write.
36
- //!
37
- //! Deterministic: a pure function of the sidecar value, pinned by a
38
- //! test. Everything module-internal lives in the reserved nscf name
39
- //! space, which the fences below keep authored names out of.
40
-
1
+ //! Compiled TypeScript projection over the native structural decoder.
41
2
  const std = @import("std");
42
3
  const sidecar_mod = @import("sidecar.zig");
43
- const emit_mod = @import("emit.zig");
44
-
45
4
  const Sidecar = sidecar_mod.Sidecar;
46
- const TypeRef = sidecar_mod.TypeRef;
47
- const IntegerClass = sidecar_mod.IntegerClass;
48
-
49
5
  pub const Error = error{ Refused, OutOfMemory };
50
6
 
51
- /// The exact-integer window an f64 carries, as the generated guards spell
52
- /// it. Signed slots use `min_safe`; unsigned slots start at zero.
53
- const max_safe = "9007199254740991";
54
- const min_safe = "-9007199254740991";
55
-
56
- fn integerLowerBound(class: IntegerClass) []const u8 {
57
- return if (class == .u64) "0" else min_safe;
7
+ pub fn emitFacade(arena: std.mem.Allocator, sidecar: Sidecar, diags: *sidecar_mod.Diagnostics) Error![]const u8 {
8
+ return @import("core_emission.zig").emit(arena, sidecar, .facade, diags);
58
9
  }
59
10
 
60
- /// The scroll-state field vocabulary (the mirror's routing twin in
61
- /// emit.zig): a record arm carrying exactly these eight numeric fields
62
- /// in either the TypeScript or canvas spelling also answers the dedicated
63
- /// scroll entry. The ABI parameters use the TypeScript spellings.
11
+ const testing = std.testing;
12
+ // Retained native fixtures exercise both authored scroll spellings.
64
13
  const scroll_state_fields_ts = [_][]const u8{
65
- "offsetX", "offsetY",
66
- "velocityX", "velocityY",
67
- "viewportExtentX", "viewportExtentY",
68
- "contentExtentX", "contentExtentY",
14
+ "offsetX", "offsetY", "velocityX", "velocityY",
15
+ "viewportExtentX", "viewportExtentY", "contentExtentX", "contentExtentY",
69
16
  };
70
17
  const scroll_state_fields_canvas = [_][]const u8{
71
- "offset_x", "offset_y",
72
- "velocity_x", "velocity_y",
73
- "viewport_extent_x", "viewport_extent_y",
74
- "content_extent_x", "content_extent_y",
75
- };
76
-
77
- pub fn emitFacade(arena: std.mem.Allocator, sidecar: Sidecar, diags: *sidecar_mod.Diagnostics) Error![]const u8 {
78
- var emitter = FacadeEmitter{
79
- .arena = arena,
80
- .sidecar = sidecar,
81
- .diags = diags,
82
- .out = .empty,
83
- };
84
- try emitter.run();
85
- if (diags.hasErrors()) return error.Refused;
86
- return emitter.out.items;
87
- }
88
-
89
- /// TypeScript reserved words a declaration may not take (no quoting
90
- /// escape exists on that side, unlike Zig's @"..." names).
91
- const ts_reserved_words = [_][]const u8{
92
- "break", "case", "catch", "class", "const", "continue", "debugger", "default",
93
- "delete", "do", "else", "enum", "export", "extends", "false", "finally",
94
- "for", "function", "if", "import", "in", "instanceof", "new", "null",
95
- "return", "super", "switch", "this", "throw", "true", "try", "typeof",
96
- "var", "void", "while", "with", "let", "static", "yield", "await",
97
- "interface", "type", "number", "boolean", "string", "object", "undefined",
98
- // Intrinsic type keywords: a declaration under one would make every
99
- // reference bind the built-in, erasing the contract silently.
100
- "any",
101
- "unknown", "never", "bigint", "symbol",
102
- // Strict-mode reservations (modules are always strict).
103
- "implements", "package", "private", "protected",
104
- "public", "arguments", "eval",
105
- };
106
-
107
- /// The value-space names this module itself exports; an authored helper
108
- /// or type may not take one.
109
- const fixed_exports = [_][]const u8{
110
- "init", "coreUpdate", "coreSubscriptions", "boot_cmd",
111
- "dispatch_void", "dispatch_bytes", "dispatch_number", "dispatch_number_bytes",
112
- "dispatch_bool", "dispatch_enum", "dispatch_record", "dispatch_text_input",
113
- "dispatch_scroll_state", "abi_subscriptions", "model_snapshot", "persist_snapshot",
114
- "restore_model", "migrate_model", "helper_call", "abi_command_msg",
115
- "abi_frame_msg", "abi_key_msg", "abi_pinch_msg", "abi_drop_msg",
116
- "appearanceMsg", "chromeMsg", "envMsgs", "viewUnbound",
18
+ "offset_x", "offset_y", "velocity_x", "velocity_y",
19
+ "viewport_extent_x", "viewport_extent_y", "content_extent_x", "content_extent_y",
117
20
  };
118
21
 
119
- /// Ambient VALUE bindings generated code calls directly. A model helper is
120
- /// re-declared as an exported function in this module, so taking one of these
121
- /// names would shadow the ambient and turn `Math.trunc`, `Buffer.from`, etc.
122
- /// into member accesses on the wrapper itself.
123
- const ambient_value_names = [_][]const u8{
124
- "Math", "Buffer", "Uint8Array", "Error", "String",
125
- };
126
-
127
- /// The wire-codec snippets, emitted exactly when generated code reaches
128
- /// them (an unused module function is noise a strict compiler may
129
- /// refuse). `use` marks dependencies transitively.
130
- const Codec = enum {
131
- trap,
132
- read_u8,
133
- read_u32,
134
- read_f64,
135
- read_i64,
136
- read_i64_saturating,
137
- read_u64_saturating,
138
- read_bool,
139
- read_bytes_body,
140
- assert_consumed,
141
- sink,
142
- w_u8,
143
- w_u32,
144
- w_f64,
145
- w_i64,
146
- w_u64,
147
- w_bool,
148
- w_bytes,
149
- short_text,
150
- utf8_text,
151
- trunc_toward_zero,
152
- enum_index,
153
- ascii_string,
154
- cmd_encoder,
155
- sub_encoder,
156
- };
157
-
158
- const FacadeEmitter = struct {
159
- arena: std.mem.Allocator,
160
- sidecar: Sidecar,
161
- diags: *sidecar_mod.Diagnostics,
162
- out: std.ArrayListUnmanaged(u8),
163
- inlined: []const []const u8 = &.{},
164
- flattened: []const []const u8 = &.{},
165
- node_stored: []const []const u8 = &.{},
166
- used_codec: std.EnumSet(Codec) = .initEmpty(),
167
- /// Named types the generated code references in type position (the
168
- /// import list derives from it).
169
- referenced: std.ArrayListUnmanaged([]const u8) = .empty,
170
- /// Whether the pinch channel's SDK vocabulary import is needed.
171
- needs_pinch_phase: bool = false,
172
- /// Whether the shared member-index teaching is needed.
173
- needs_member_trap: bool = false,
174
- /// Monotonic temp-name counter (unique const names inside one
175
- /// emitted function; reset at each function boundary).
176
- temp_counter: usize = 0,
177
- /// Deduped on-demand generation queues, drained by generatedTables.
178
- needed_enum_tables: std.ArrayListUnmanaged([]const u8) = .empty,
179
- needed_enum_indexes: std.ArrayListUnmanaged([]const u8) = .empty,
180
- needed_record_writers: std.ArrayListUnmanaged([]const u8) = .empty,
181
- needed_union_writers: std.ArrayListUnmanaged([]const u8) = .empty,
182
- needed_union_decoders: std.ArrayListUnmanaged([]const u8) = .empty,
183
-
184
- fn print(self: *FacadeEmitter, comptime fmt: []const u8, args: anytype) Error!void {
185
- const text = try std.fmt.allocPrint(self.arena, fmt, args);
186
- try self.out.appendSlice(self.arena, text);
187
- }
188
-
189
- fn raw(self: *FacadeEmitter, text: []const u8) Error!void {
190
- try self.out.appendSlice(self.arena, text);
191
- }
192
-
193
- fn use(self: *FacadeEmitter, id: Codec) void {
194
- if (self.used_codec.contains(id)) return;
195
- self.used_codec.insert(id);
196
- // Dependency closure: every snippet marks what its own body
197
- // calls, so the emitted set is always self-contained.
198
- const deps: []const Codec = switch (id) {
199
- .read_i64, .read_i64_saturating, .read_u64_saturating => &.{.read_u32},
200
- .read_u8, .read_u32, .read_f64, .read_bool, .read_bytes_body, .assert_consumed => &.{.trap},
201
- .w_u32 => &.{.sink},
202
- .w_u8, .w_f64, .w_bool => &.{.sink},
203
- .w_i64 => &.{ .w_u32, .trunc_toward_zero, .trap },
204
- .w_u64 => &.{ .w_u32, .trunc_toward_zero, .trap },
205
- .w_bytes => &.{.w_u32},
206
- .short_text => &.{ .sink, .trap },
207
- .utf8_text => &.{},
208
- .enum_index => &.{.trap},
209
- .cmd_encoder => &.{ .w_u8, .w_f64, .w_bytes, .short_text, .utf8_text, .enum_index, .trap },
210
- .sub_encoder => &.{ .w_u8, .w_u32, .w_f64, .w_bytes, .short_text, .utf8_text, .trap },
211
- else => &.{},
212
- };
213
- for (deps) |dep| self.use(dep);
214
- }
215
-
216
- /// Note a named type the generated code spells in type position.
217
- fn reference(self: *FacadeEmitter, name: []const u8) Error!void {
218
- // Current sidecars leave generated-only table names originless.
219
- // They either flatten at their sole reference site or validation
220
- // refuses them, so importing one would always name a nonexistent
221
- // authored export (generic monomorphizations are the common case).
222
- if (self.isGeneratedOnlyType(name)) return;
223
- if (!self.isExportedType(name)) return;
224
- if (nameListed(self.referenced.items, name)) return;
225
- try self.referenced.append(self.arena, name);
226
- }
227
-
228
- // ----------------------------------------------------- fact lookup
229
-
230
- /// The authored member name of a single-payload arm. Validation requires
231
- /// the fact everywhere emission consumes it; `value` remains only as an
232
- /// unreachable-safe spelling for bare/multi-field branches that compute
233
- /// this local before switching on their payload shape.
234
- fn memberOf(_: *FacadeEmitter, member: ?[]const u8) []const u8 {
235
- return member orelse "value";
236
- }
237
-
238
- /// The declaring module of a table type. Facade validation requires an
239
- /// origin for every authored table; the entry fallback is only for Msg,
240
- /// whose root designation is not duplicated in the type tables.
241
- fn originOf(self: *FacadeEmitter, name: []const u8) []const u8 {
242
- for (self.sidecar.types.structs) |entry| {
243
- if (std.mem.eql(u8, entry.name, name)) return entry.origin orelse self.entryBasename();
244
- }
245
- for (self.sidecar.types.enums) |entry| {
246
- if (std.mem.eql(u8, entry.name, name)) return entry.origin orelse self.entryBasename();
247
- }
248
- for (self.sidecar.types.unions) |entry| {
249
- if (std.mem.eql(u8, entry.name, name)) return entry.origin orelse self.entryBasename();
250
- }
251
- return self.entryBasename();
252
- }
253
-
254
- fn entryBasename(self: *FacadeEmitter) []const u8 {
255
- return std.fs.path.basenamePosix(self.sidecar.entry);
256
- }
257
-
258
- /// A table name synthesized by the transpiler rather than declared in
259
- /// an authored module. These names flatten at their one legal reference
260
- /// site or refuse; they are never imports or re-exports.
261
- fn isGeneratedOnlyType(self: *FacadeEmitter, name: []const u8) bool {
262
- if (std.mem.eql(u8, name, self.sidecar.model) or std.mem.eql(u8, name, self.sidecar.msg.name)) return false;
263
- for (self.sidecar.types.structs) |entry| {
264
- if (std.mem.eql(u8, entry.name, name)) return entry.origin == null;
265
- }
266
- for (self.sidecar.types.enums) |entry| {
267
- if (std.mem.eql(u8, entry.name, name)) return entry.origin == null;
268
- }
269
- for (self.sidecar.types.unions) |entry| {
270
- if (std.mem.eql(u8, entry.name, name)) return entry.origin == null;
271
- }
272
- return false;
273
- }
274
-
275
- fn isExportedType(self: *FacadeEmitter, name: []const u8) bool {
276
- if (std.mem.eql(u8, name, self.sidecar.model) or std.mem.eql(u8, name, self.sidecar.msg.name)) return true;
277
- for (self.sidecar.types.structs) |entry| {
278
- if (std.mem.eql(u8, entry.name, name)) return entry.exported;
279
- }
280
- for (self.sidecar.types.enums) |entry| {
281
- if (std.mem.eql(u8, entry.name, name)) return entry.exported;
282
- }
283
- for (self.sidecar.types.unions) |entry| {
284
- if (std.mem.eql(u8, entry.name, name)) return entry.exported;
285
- }
286
- return true;
287
- }
288
-
289
- fn slotClassAt(self: *FacadeEmitter, path: []const u8) ?IntegerClass {
290
- for (self.sidecar.integer_slots) |entry| {
291
- if (std.mem.eql(u8, entry.slot, path)) return entry.class;
292
- }
293
- return null;
294
- }
295
-
296
- fn slotClass(self: *FacadeEmitter, container: []const u8, member: []const u8) ?IntegerClass {
297
- const path = std.fmt.allocPrint(self.arena, "{s}.{s}", .{ container, member }) catch return null;
298
- return self.slotClassAt(path);
299
- }
300
-
301
- fn nestedSlotClass(self: *FacadeEmitter, container: []const u8, member: []const u8, field: []const u8) ?IntegerClass {
302
- const path = std.fmt.allocPrint(self.arena, "{s}.{s}.{s}", .{ container, member, field }) catch return null;
303
- return self.slotClassAt(path);
304
- }
305
-
306
- /// The integer writer for a slot: unsigned twin for u64-attested
307
- /// slots, two's complement otherwise.
308
- fn intWriter(self: *FacadeEmitter, container: []const u8, member: []const u8) []const u8 {
309
- if (self.slotClass(container, member)) |class| {
310
- if (class == .u64) {
311
- self.use(.w_u64);
312
- return "nscfWU64";
313
- }
314
- }
315
- self.use(.w_i64);
316
- return "nscfWI64";
317
- }
318
-
319
- // ------------------------------------------------------------- run
320
-
321
- fn run(self: *FacadeEmitter) Error!void {
322
- self.inlined = try emit_mod.inlinedTableNames(self.arena, self.sidecar);
323
- self.flattened = try self.flattenedTableNames();
324
- self.node_stored = try self.nodeStoredTableNames();
325
- self.validateFacadeFacts();
326
- try self.validateNames();
327
- self.validateOptionalDepth();
328
- if (self.diags.hasErrors()) return;
329
-
330
- // The body emits first into its own buffer so the import lists
331
- // (referenced types, used codec snippets) can assemble after the
332
- // walk; the final module is header + imports + body.
333
- var body_emitter = FacadeEmitter{
334
- .arena = self.arena,
335
- .sidecar = self.sidecar,
336
- .diags = self.diags,
337
- .out = .empty,
338
- .inlined = self.inlined,
339
- .flattened = self.flattened,
340
- .node_stored = self.node_stored,
341
- };
342
- const body = &body_emitter;
343
- try body.privateTypeDeclarations();
344
- try body.channelConsts();
345
- try body.unboundDecl();
346
- try body.helperWrappers();
347
- try body.entryPoints();
348
- try body.tagTable();
349
- try body.dispatchSurface();
350
- try body.channelEntries();
351
- try body.postCycle();
352
- try body.helperCall();
353
- try body.generatedTables();
354
- try body.codecSection();
355
- if (self.diags.hasErrors()) return;
356
-
357
- try self.header();
358
- try self.imports(body);
359
- try self.reexports();
360
- try self.out.appendSlice(self.arena, body.out.items);
361
- }
362
-
363
- // ------------------------------------------------------- fencing
364
-
365
- /// Facade/profile emission needs facts that format-1 readers keep
366
- /// optional for backward-compatible MIRROR generation. An older sidecar
367
- /// still generates core_shim.zig, but it cannot truthfully reconstruct
368
- /// authored module paths or payload property names; refuse instead of
369
- /// guessing an entry-module origin or a `value` member.
370
- fn validateFacadeFacts(self: *FacadeEmitter) void {
371
- const model = sidecar_mod.findStruct(self.sidecar.types, self.sidecar.model);
372
- if (model == null or model.?.origin == null) {
373
- self.diags.flag("types", "the model declaration carries no authored type-origin fact — this sidecar predates facade metadata; regenerate it with the current compiler before requesting --facade, --profile, or --check", .{});
374
- }
375
- for (self.sidecar.msg.arms) |arm| {
376
- if (self.msgArmNeedsMember(arm) and arm.member == null) {
377
- self.diags.flag("msg.arms", "arm \"{s}\" carries one payload but no authored member-name fact — this sidecar predates facade metadata; regenerate it with the current compiler", .{arm.name});
378
- }
379
- }
380
- for (self.sidecar.types.unions) |entry| {
381
- for (entry.arms) |arm| {
382
- if (arm.payload == .void or self.synthesizedRecordOf(arm.payload, entry.name, arm.name) != null) continue;
383
- if (arm.member == null) {
384
- self.diags.flag("types.unions", "arm \"{s}\" of \"{s}\" carries one payload but no authored member-name fact — this sidecar predates facade metadata; regenerate it with the current compiler", .{ arm.name, entry.name });
385
- }
386
- }
387
- }
388
- }
389
-
390
- fn msgArmNeedsMember(self: *FacadeEmitter, arm: sidecar_mod.MsgArm) bool {
391
- return switch (arm.payload) {
392
- .void, .number_bytes => false,
393
- .record => self.synthesizedRecordOf(recordPayloadRef(arm.payload), self.sidecar.msg.name, arm.name) == null,
394
- else => true,
395
- };
396
- }
397
-
398
- fn validateNames(self: *FacadeEmitter) Error!void {
399
- // Declaration names (type-table entries and the message union)
400
- // must be plain TypeScript identifiers: TypeScript has no
401
- // quoted-declaration escape, and re-export lists take
402
- // identifiers verbatim.
403
- var names: std.ArrayListUnmanaged([]const u8) = .empty;
404
- for (self.sidecar.types.structs) |entry| try names.append(self.arena, entry.name);
405
- for (self.sidecar.types.enums) |entry| try names.append(self.arena, entry.name);
406
- for (self.sidecar.types.unions) |entry| try names.append(self.arena, entry.name);
407
- try names.append(self.arena, self.sidecar.msg.name);
408
- try names.append(self.arena, self.sidecar.model);
409
-
410
- for (names.items) |name| {
411
- if (pipelineIdentifierIssue(name, .declaration)) |issue| {
412
- self.diags.flag("types", "type name \"{s}\" {s} — the facade must stay declarable end to end (TypeScript source, then the compiled module, which takes identifiers verbatim); rename it in the core source", .{ name, issue });
413
- }
414
- // Ambient globals the generated module leans on: a
415
- // re-exported declaration under one would shadow them out
416
- // from under the codec.
417
- if (std.mem.eql(u8, name, "Uint8Array")) {
418
- self.diags.flag("types", "\"Uint8Array\" shadows the ambient byte type every encoder in the generated facade uses; rename the type in the core source", .{});
419
- }
420
- if (std.mem.eql(u8, name, "Buffer")) {
421
- self.diags.flag("types", "\"Buffer\" shadows the ambient buffer type the generated f64 codec uses; rename the type in the core source", .{});
422
- }
423
- if (self.sidecar.channels.pinch_msg and std.mem.eql(u8, name, "PinchPhase")) {
424
- self.diags.flag("types", "\"PinchPhase\" collides with the SDK vocabulary the wired pinch channel imports; rename the type in the core source", .{});
425
- }
426
- if (self.sidecar.channels.drop_msg and std.mem.eql(u8, name, "FileDropPoint")) {
427
- self.diags.flag("types", "\"FileDropPoint\" collides with the SDK vocabulary the wired file-drop channel imports; rename the type in the core source", .{});
428
- }
429
- }
430
- // Arm, member, and field names become the compiled module's
431
- // union members and struct fields verbatim.
432
- for (self.sidecar.msg.arms) |arm| {
433
- if (pipelineIdentifierIssue(arm.name, .member)) |issue| {
434
- self.diags.flag("msg.arms", "arm \"{s}\" {s} — the facade must stay declarable end to end; rename it in the core source", .{ arm.name, issue });
435
- }
436
- if (arm.member) |member| {
437
- if (std.mem.eql(u8, member, "kind")) {
438
- self.diags.flag("msg.arms", "arm \"{s}\" names its payload member \"kind\", the discriminator's own spelling — the constructed arm object would declare it twice; rename the member in the core source", .{arm.name});
439
- }
440
- }
441
- }
442
- for (self.sidecar.types.unions) |entry| {
443
- for (entry.arms) |arm| {
444
- if (pipelineIdentifierIssue(arm.name, .member)) |issue| {
445
- self.diags.flag("types.unions", "arm \"{s}\" of \"{s}\" {s} — the facade must stay declarable end to end; rename it in the core source", .{ arm.name, entry.name, issue });
446
- }
447
- if (arm.member) |member| {
448
- if (std.mem.eql(u8, member, "kind")) {
449
- self.diags.flag("types.unions", "arm \"{s}\" of \"{s}\" names its payload member \"kind\", the discriminator's own spelling; rename the member in the core source", .{ arm.name, entry.name });
450
- }
451
- }
452
- }
453
- }
454
- for (self.sidecar.types.enums) |entry| {
455
- for (entry.members) |member| {
456
- if (pipelineIdentifierIssue(member, .member)) |issue| {
457
- self.diags.flag("types.enums", "member \"{s}\" of \"{s}\" {s} — the facade must stay declarable end to end; rename it in the core source", .{ member, entry.name, issue });
458
- }
459
- }
460
- if (entry.members.len < 2) {
461
- self.diags.flag("types", "enum \"{s}\" has one member — a single string literal is not a union in the projected subset, so no source can author it; give the state a second member or fold it away in the core source", .{entry.name});
462
- }
463
- }
464
- for (self.sidecar.types.structs) |entry| {
465
- for (entry.fields) |field| {
466
- if (pipelineIdentifierIssue(field.name, .member)) |issue| {
467
- self.diags.flag("types", "field \"{s}\" {s} — the facade must stay declarable end to end; rename it in the core source", .{ field.name, issue });
468
- }
469
- if (std.mem.startsWith(u8, field.name, "nsc_core_") or std.mem.startsWith(u8, field.name, "nscf")) {
470
- self.diags.flag("types", "field \"{s}\" takes the facade's reserved nsc name space; rename it in the core source", .{field.name});
471
- }
472
- }
473
- }
474
- for (self.sidecar.msg.arms) |arm| {
475
- switch (arm.payload) {
476
- .number_bytes => |desc| {
477
- for ([_][]const u8{ desc.number_field, desc.bytes_field }) |field_name| {
478
- if (pipelineIdentifierIssue(field_name, .member)) |issue| {
479
- self.diags.flag("msg.arms", "field \"{s}\" {s} — the facade must stay declarable end to end; rename it in the core source", .{ field_name, issue });
480
- }
481
- if (std.mem.eql(u8, field_name, "kind")) {
482
- self.diags.flag("msg.arms", "arm \"{s}\" flattens a field spelled \"kind\" beside the message discriminator of the same name; rename the field in the core source", .{arm.name});
483
- }
484
- if (std.mem.startsWith(u8, field_name, "nsc_core_") or std.mem.startsWith(u8, field_name, "nscf")) {
485
- self.diags.flag("msg.arms", "field \"{s}\" takes the facade's reserved nsc name space; rename it in the core source", .{field_name});
486
- }
487
- }
488
- },
489
- .record => {
490
- if (self.synthesizedRecordOf(recordPayloadRef(arm.payload), self.sidecar.msg.name, arm.name)) |record| {
491
- for (record.fields) |field| {
492
- if (std.mem.eql(u8, field.name, "kind")) {
493
- self.diags.flag("msg.arms", "arm \"{s}\" flattens a field spelled \"kind\" beside the message discriminator of the same name; rename the field in the core source", .{arm.name});
494
- }
495
- }
496
- }
497
- },
498
- else => {},
499
- }
500
- }
501
- for (self.sidecar.types.unions) |entry| {
502
- for (entry.arms) |arm| {
503
- if (arm.payload == .void) continue;
504
- if (self.synthesizedRecordOf(arm.payload, entry.name, arm.name)) |record| {
505
- for (record.fields) |field| {
506
- if (std.mem.eql(u8, field.name, "kind")) {
507
- self.diags.flag("types.unions", "arm \"{s}\" of \"{s}\" flattens a field spelled \"kind\" beside the arm discriminator of the same name; rename the field in the core source", .{ arm.name, entry.name });
508
- }
509
- }
510
- }
511
- }
512
- }
513
- // Helper names become this module's own exported wrapper
514
- // functions, and their aliases live in the nscf import space.
515
- for (self.sidecar.model_helpers) |helper| {
516
- if (!isTsIdentifier(helper.name) or pipelineIdentifierIssue(helper.name, .declaration) != null) {
517
- self.diags.flag("model_helpers", "helper \"{s}\" is not declarable as an exported function in both pipeline languages; rename it in the core source", .{helper.name});
518
- continue;
519
- }
520
- if (std.mem.startsWith(u8, helper.name, "nsc_core_") or std.mem.startsWith(u8, helper.name, "nscf")) {
521
- self.diags.flag("model_helpers", "helper \"{s}\" takes the facade's reserved nsc name space; rename it in the core source", .{helper.name});
522
- }
523
- for (fixed_exports) |fixed| {
524
- if (std.mem.eql(u8, helper.name, fixed)) {
525
- self.diags.flag("model_helpers", "helper \"{s}\" collides with a declaration the generated facade itself must export; rename it in the core source", .{helper.name});
526
- }
527
- }
528
- for (ambient_value_names) |ambient| {
529
- if (std.mem.eql(u8, helper.name, ambient)) {
530
- self.diags.flag("model_helpers", "helper \"{s}\" shadows an ambient value the generated facade calls; rename it in the core source", .{helper.name});
531
- }
532
- }
533
- if (helper.params.len > 0) {
534
- self.diags.flag("model_helpers", "helper \"{s}\" declares extra parameters — the generated dispatch surface carries model-only helpers (no producer emits parameters today); drop them in the core source", .{helper.name});
535
- }
536
- }
537
- for (self.sidecar.types.structs) |entry| try self.fenceDecl(entry.name);
538
- for (self.sidecar.types.enums) |entry| try self.fenceDecl(entry.name);
539
- for (self.sidecar.types.unions) |entry| try self.fenceDecl(entry.name);
540
- try self.fenceDecl(self.sidecar.msg.name);
541
-
542
- // An originless table name in a current sidecar is compiler-created,
543
- // not a TypeScript export the facade can import. Single-use inline
544
- // records disappear back into their arm literals; every other such
545
- // name (most notably a monomorphized generic like `Box__Item`) would
546
- // make the facade invalid, and the external library compiler cannot
547
- // project the authored generic contract surface either. Refuse at the
548
- // generator boundary instead of emitting a downstream failure.
549
- for (self.sidecar.types.structs) |entry| {
550
- if (self.isGeneratedOnlyType(entry.name) and !nameListed(self.flattened, entry.name)) {
551
- self.diags.flag("types", "compiler-generated table type \"{s}\" has no authored TypeScript declaration the facade can name — generic instantiations cannot cross the compiled-core contract surface yet; replace the contract-facing generic with an authored concrete record", .{entry.name});
552
- }
553
- }
554
- for (self.sidecar.types.enums) |entry| {
555
- if (self.isGeneratedOnlyType(entry.name)) {
556
- self.diags.flag("types", "compiler-generated table type \"{s}\" has no authored TypeScript declaration the facade can name — generic instantiations cannot cross the compiled-core contract surface yet; replace the contract-facing generic with an authored concrete type", .{entry.name});
557
- }
558
- }
559
- for (self.sidecar.types.unions) |entry| {
560
- if (self.isGeneratedOnlyType(entry.name)) {
561
- self.diags.flag("types", "compiler-generated table type \"{s}\" has no authored TypeScript declaration the facade can name — generic instantiations cannot cross the compiled-core contract surface yet; replace the contract-facing generic with an authored concrete union", .{entry.name});
562
- }
563
- }
564
-
565
- // Declaration form spells storage ONCE per record, so a record
566
- // referenced both by node and by value has no projection — one
567
- // declaration cannot say both. (The transpiled lane decides
568
- // storage per TYPE, so its contracts never mix; a hand contract
569
- // that does must split the type.)
570
- var value_refs: std.ArrayListUnmanaged([]const u8) = .empty;
571
- for (self.sidecar.types.structs) |entry| {
572
- for (entry.fields) |field| try noteValueRefs(&value_refs, self.arena, field.type);
573
- }
574
- for (self.sidecar.types.unions) |entry| {
575
- for (entry.arms) |arm| try noteValueRefs(&value_refs, self.arena, arm.payload);
576
- }
577
- for (self.sidecar.model_helpers) |helper| {
578
- try noteValueRefs(&value_refs, self.arena, helper.returns);
579
- for (helper.params) |param| try noteValueRefs(&value_refs, self.arena, param);
580
- }
581
- for (self.sidecar.msg.arms) |arm| {
582
- switch (arm.payload) {
583
- .scalar => |ref| try noteValueRefs(&value_refs, self.arena, ref),
584
- else => {},
585
- }
586
- }
587
- for (value_refs.items) |name| {
588
- if (nameListed(self.node_stored, name)) {
589
- self.diags.flag("types", "\"{s}\" is stored by reference at one site and by value at another — the projection states storage once per declaration, so one record cannot say both; split the type in the core source", .{name});
590
- }
591
- }
592
-
593
- // Value records the MODEL keeps carry scalar fields only, and
594
- // model sequences carry reference-stored records: the compiled
595
- // core commits by-value records shallowly, so heap-backed
596
- // fields would dangle across frames and by-value arrays have no
597
- // commit walk. Refuse here, where the teaching can name the
598
- // record, instead of emitting a facade its compiler refuses.
599
- try self.validateModelValueRecords();
600
-
601
- // The host-constructed channels build their event record's
602
- // fields DIRECTLY on the named arm, so the arm's record must
603
- // flatten into the arm literal (the single-use synthesized
604
- // shape). A shared named record would project as a nested
605
- // member no host construction can fill.
606
- if (self.sidecar.channels.appearance_msg) |arm_name| {
607
- try self.requireFlattenedChannelArm("channels.appearance_msg", arm_name);
608
- }
609
- if (self.sidecar.channels.chrome_msg) |arm_name| {
610
- try self.requireFlattenedChannelArm("channels.chrome_msg", arm_name);
611
- }
612
- }
613
-
614
- /// Walk the model tree and refuse the value-record shapes the
615
- /// compiled core cannot carry: a model-kept value record with a
616
- /// non-scalar field, and a model sequence of value records.
617
- fn validateModelValueRecords(self: *FacadeEmitter) Error!void {
618
- var visited: std.ArrayListUnmanaged([]const u8) = .empty;
619
- const model = sidecar_mod.findStruct(self.sidecar.types, self.sidecar.model) orelse return;
620
- for (model.fields) |field| {
621
- try self.visitModelRef(&visited, field.type);
622
- }
623
- }
624
-
625
- fn visitModelRef(self: *FacadeEmitter, visited: *std.ArrayListUnmanaged([]const u8), ref: TypeRef) Error!void {
626
- switch (ref) {
627
- .value => |name| {
628
- if (nameListed(visited.items, name)) return;
629
- try visited.append(self.arena, name);
630
- const entry = sidecar_mod.findStruct(self.sidecar.types, name) orelse return;
631
- for (entry.fields) |field| {
632
- const scalar = switch (field.type) {
633
- .f64, .i64, .bool, .enum_ref => true,
634
- else => false,
635
- };
636
- if (!scalar) {
637
- self.diags.flag("types", "\"{s}\" is a value-stored record the model keeps, but field \"{s}\" is not a scalar — the compiled projection commits value records shallowly, so heap-backed fields would dangle across frames; store \"{s}\" by reference in the core source", .{ name, field.name, name });
638
- break;
639
- }
640
- }
641
- },
642
- .node => |name| {
643
- if (nameListed(visited.items, name)) return;
644
- try visited.append(self.arena, name);
645
- const entry = sidecar_mod.findStruct(self.sidecar.types, name) orelse return;
646
- for (entry.fields) |field| {
647
- try self.visitModelRef(visited, field.type);
648
- }
649
- },
650
- .union_ref => |name| {
651
- if (nameListed(visited.items, name)) return;
652
- try visited.append(self.arena, name);
653
- const entry = sidecar_mod.findUnion(self.sidecar.types, name) orelse return;
654
- for (entry.arms) |arm| {
655
- try self.visitModelRef(visited, arm.payload);
656
- }
657
- },
658
- .slice => |elem| {
659
- const element = if (elem.* == .optional) elem.optional.* else elem.*;
660
- if (element == .value) {
661
- self.diags.flag("types", "a model sequence holds \"{s}\" by value — sequences the model keeps carry reference-stored records (the compiled projection has no by-value sequence commit); store \"{s}\" by reference in the core source", .{ element.value, element.value });
662
- }
663
- try self.visitModelRef(visited, elem.*);
664
- },
665
- .optional => |inner| try self.visitModelRef(visited, inner.*),
666
- else => {},
667
- }
668
- }
669
-
670
- /// Refuse a host-constructed channel arm whose record does not
671
- /// flatten into its arm literal.
672
- fn requireFlattenedChannelArm(self: *FacadeEmitter, at: []const u8, arm_name: []const u8) Error!void {
673
- const arm = sidecar_mod.findArm(self.sidecar.msg, arm_name) orelse return;
674
- switch (arm.payload) {
675
- .record => |name| {
676
- if (nameListed(self.flattened, name)) return;
677
- self.diags.flag(at, "arm \"{s}\" carries the named record \"{s}\", which the projection cannot flatten into the arm (the host fills the event's fields directly on the arm) — declare the event's fields inline on the arm in the core source", .{ arm_name, name });
678
- },
679
- else => {},
680
- }
681
- }
682
-
683
- fn fenceDecl(self: *FacadeEmitter, name: []const u8) Error!void {
684
- if (name.len == 0) return;
685
- if (std.mem.startsWith(u8, name, "nsc_core_") or std.mem.startsWith(u8, name, "nscf")) {
686
- self.diags.flag("types", "\"{s}\" collides with the facade's reserved nsc name space; rename it in the core source", .{name});
687
- return;
688
- }
689
- for (fixed_exports) |decl| {
690
- if (std.mem.eql(u8, name, decl)) {
691
- self.diags.flag("types", "\"{s}\" collides with a declaration the generated facade itself must make; rename it in the core source", .{name});
692
- }
693
- }
694
- }
695
-
696
- /// TypeScript's null carries exactly one absence level, so a nested
697
- /// optional has no faithful projection (its own source language
698
- /// cannot author one either: `T | null | null` collapses).
699
- fn validateOptionalDepth(self: *FacadeEmitter) void {
700
- for (self.sidecar.types.structs, 0..) |entry, index| {
701
- for (entry.fields, 0..) |field, field_index| {
702
- self.flagNestedOptional(field.type, false, pathText(self.arena, "types.structs[{d}].fields[{d}].type", .{ index, field_index }));
703
- }
704
- }
705
- for (self.sidecar.types.unions, 0..) |entry, index| {
706
- for (entry.arms, 0..) |arm, arm_index| {
707
- self.flagNestedOptional(arm.payload, false, pathText(self.arena, "types.unions[{d}].arms[{d}].payload", .{ index, arm_index }));
708
- }
709
- }
710
- for (self.sidecar.model_helpers, 0..) |helper, index| {
711
- self.flagNestedOptional(helper.returns, false, pathText(self.arena, "model_helpers[{d}].returns", .{index}));
712
- for (helper.params, 0..) |param, param_index| {
713
- self.flagNestedOptional(param, false, pathText(self.arena, "model_helpers[{d}].params[{d}]", .{ index, param_index }));
714
- }
715
- }
716
- for (self.sidecar.msg.arms, 0..) |arm, index| {
717
- switch (arm.payload) {
718
- .scalar => |ref| self.flagNestedOptional(ref, false, pathText(self.arena, "msg.arms[{d}].payload.type", .{index})),
719
- else => {},
720
- }
721
- }
722
- }
723
-
724
- fn flagNestedOptional(self: *FacadeEmitter, ref: TypeRef, inside_optional: bool, at: []const u8) void {
725
- switch (ref) {
726
- .optional => |inner| {
727
- if (inside_optional) {
728
- self.diags.flag(at, "a nested optional has no TypeScript projection — one null carries one absence level, and the source language cannot author a second; flatten the state in the core source", .{});
729
- return;
730
- }
731
- self.flagNestedOptional(inner.*, true, at);
732
- },
733
- .slice => |elem| self.flagNestedOptional(elem.*, false, at),
734
- else => {},
735
- }
736
- }
737
-
738
- // ------------------------------------------- header and imports
739
-
740
- fn header(self: *FacadeEmitter) Error!void {
741
- try self.print(
742
- \\// Generated by corewire from this app's core.contract.json — the
743
- \\// compiled-core entry module. It imports the author's core module
744
- \\// (staged beside this file with its SDK imports resolved locally),
745
- \\// owns the committed model in module state, and exports the
746
- \\// profile-declared dispatch surface. Inbound payloads decode
747
- \\// through the generated wire codec below; returned Cmd/Sub data
748
- \\// encodes through the same codec's v3 wires — byte-identical to
749
- \\// the transpiler lane's output. The same sidecar generates the
750
- \\// host's Zig mirror (core_shim.zig), so the two sides carry one
751
- \\// set of types, wire tags, field orders, and byte encodings by
752
- \\// construction. Do not edit; regenerate from the sidecar.
753
- \\//
754
- \\// Contract identity: entry {s}, compiler {s}, build_id
755
- \\// {x:0>16}.
756
- \\
757
- , .{ try commentText(self.arena, self.sidecar.entry), try commentText(self.arena, self.sidecar.compiler_version), self.sidecar.build_id });
758
- }
759
-
760
- /// The import block: the author's behavioral exports under nscf
761
- /// aliases, the referenced contract types from their declaring
762
- /// modules, and the SDK effect types the codec spells.
763
- fn imports(self: *FacadeEmitter, body: *FacadeEmitter) Error!void {
764
- const entry_module = try self.importPath(self.entryBasename());
765
- // Behavioral value imports, all from the entry module.
766
- var values: std.ArrayListUnmanaged([]const u8) = .empty;
767
- try values.append(self.arena, "initialModel as nscfInitialModel");
768
- try values.append(self.arena, "update as nscfUpdate");
769
- if (self.sidecar.has_migrate) try values.append(self.arena, "migrate as nscfMigrate");
770
- if (self.sidecar.has_subscriptions) try values.append(self.arena, "subscriptions as nscfSubscriptions");
771
- if (self.sidecar.channels.command_msg) try values.append(self.arena, "commandMsg as nscfChanCommandMsg");
772
- if (self.sidecar.channels.frame_msg) try values.append(self.arena, "frameMsg as nscfChanFrameMsg");
773
- if (self.sidecar.channels.key_msg) try values.append(self.arena, "keyMsg as nscfChanKeyMsg");
774
- if (self.sidecar.channels.pinch_msg) try values.append(self.arena, "pinchMsg as nscfChanPinchMsg");
775
- if (self.sidecar.channels.drop_msg) try values.append(self.arena, "dropMsg as nscfChanDropMsg");
776
- for (self.sidecar.model_helpers) |helper| {
777
- try values.append(self.arena, try std.fmt.allocPrint(self.arena, "{s} as nscfH_{s}", .{ helper.name, helper.name }));
778
- }
779
- try self.raw("\nimport {\n");
780
- for (values.items) |item| try self.print(" {s},\n", .{item});
781
- try self.print("}} from {s};\n", .{entry_module});
782
-
783
- // Referenced contract types, grouped by declaring module in
784
- // first-reference order (Model and Msg lead).
785
- var groups: std.ArrayListUnmanaged(struct { origin: []const u8, names: std.ArrayListUnmanaged([]const u8) }) = .empty;
786
- var ordered: std.ArrayListUnmanaged([]const u8) = .empty;
787
- try ordered.append(self.arena, self.sidecar.model);
788
- try ordered.append(self.arena, self.sidecar.msg.name);
789
- for (body.referenced.items) |name| {
790
- if (!nameListed(ordered.items, name)) try ordered.append(self.arena, name);
791
- }
792
- for (ordered.items) |name| {
793
- const origin = self.originOf(name);
794
- const group = for (groups.items) |*candidate| {
795
- if (std.mem.eql(u8, candidate.origin, origin)) break candidate;
796
- } else blk: {
797
- try groups.append(self.arena, .{ .origin = origin, .names = .empty });
798
- break :blk &groups.items[groups.items.len - 1];
799
- };
800
- try group.names.append(self.arena, name);
801
- }
802
- for (groups.items) |group| {
803
- try self.raw("import type { ");
804
- for (group.names.items, 0..) |name, index| {
805
- try self.print("{s}{s}", .{ if (index == 0) "" else ", ", name });
806
- }
807
- try self.print(" }} from {s};\n", .{try self.importPath(group.origin)});
808
- }
809
- // The SDK effect vocabulary the codec spells.
810
- const needs_cmd = body.used_codec.contains(.cmd_encoder);
811
- const needs_sub = body.used_codec.contains(.sub_encoder);
812
- if (needs_cmd and needs_sub) {
813
- try self.raw("import type { Cmd as nscfCmd, Sub as nscfSub, DbText as nscfDbText } from \"./sdk/core.ts\";\n");
814
- } else if (needs_cmd) {
815
- try self.raw("import type { Cmd as nscfCmd, DbText as nscfDbText } from \"./sdk/core.ts\";\n");
816
- } else if (needs_sub) {
817
- try self.raw("import type { Sub as nscfSub, DbText as nscfDbText } from \"./sdk/core.ts\";\n");
818
- }
819
- // The pinch channel's SDK vocabulary (declared in the SDK's
820
- // events module, outside the contract tables).
821
- if (body.needs_pinch_phase) {
822
- try self.raw("import type { PinchPhase } from \"./sdk/events.ts\";\n");
823
- }
824
- if (self.sidecar.channels.drop_msg) {
825
- try self.raw("import type { FileDropPoint } from \"./sdk/events.ts\";\n");
826
- }
827
- self.needs_pinch_phase = body.needs_pinch_phase;
828
- }
829
-
830
- fn importPath(self: *FacadeEmitter, origin: []const u8) Error![]const u8 {
831
- return std.fmt.allocPrint(self.arena, "\"./{s}\"", .{try tsString(self.arena, origin)});
832
- }
833
-
834
- /// Type re-exports: the contract type designations the compiler's
835
- /// sidecar section names — every named (non-synthesized) table type,
836
- /// re-exported verbatim from its own declaring module.
837
- fn reexports(self: *FacadeEmitter) Error!void {
838
- var ordered: std.ArrayListUnmanaged([]const u8) = .empty;
839
- try ordered.append(self.arena, self.sidecar.model);
840
- try ordered.append(self.arena, self.sidecar.msg.name);
841
- for (self.sidecar.types.structs) |entry| {
842
- if (nameListed(self.inlined, entry.name)) continue;
843
- if (self.isGeneratedOnlyType(entry.name)) continue;
844
- if (!entry.exported) continue;
845
- if (!nameListed(ordered.items, entry.name)) try ordered.append(self.arena, entry.name);
846
- }
847
- for (self.sidecar.types.enums) |entry| {
848
- if (self.isGeneratedOnlyType(entry.name)) continue;
849
- if (!entry.exported) continue;
850
- if (!nameListed(ordered.items, entry.name)) try ordered.append(self.arena, entry.name);
851
- }
852
- for (self.sidecar.types.unions) |entry| {
853
- if (self.isGeneratedOnlyType(entry.name)) continue;
854
- if (!entry.exported) continue;
855
- if (!nameListed(ordered.items, entry.name)) try ordered.append(self.arena, entry.name);
856
- }
857
- var groups: std.ArrayListUnmanaged(struct { origin: []const u8, names: std.ArrayListUnmanaged([]const u8) }) = .empty;
858
- for (ordered.items) |name| {
859
- const origin = self.originOf(name);
860
- const group = for (groups.items) |*candidate| {
861
- if (std.mem.eql(u8, candidate.origin, origin)) break candidate;
862
- } else blk: {
863
- try groups.append(self.arena, .{ .origin = origin, .names = .empty });
864
- break :blk &groups.items[groups.items.len - 1];
865
- };
866
- try group.names.append(self.arena, name);
867
- }
868
- try self.raw(
869
- \\
870
- \\// The contract type designations the sidecar section names — the
871
- \\// author's exported declarations re-exported verbatim. Private
872
- \\// reachable declarations have structural twins below instead: their
873
- \\// authored modules expose no name this facade can import.
874
- \\
875
- );
876
- for (groups.items) |group| {
877
- try self.raw("export type { ");
878
- for (group.names.items, 0..) |name, index| {
879
- try self.print("{s}{s}", .{ if (index == 0) "" else ", ", name });
880
- }
881
- try self.print(" }} from {s};\n", .{try self.importPath(group.origin)});
882
- }
883
- }
884
-
885
- /// Structural twins for authored table types their declaring modules do
886
- /// not export. They stay module-private too: generated readers/writers can
887
- /// name the contract shape without inventing a public authoring surface.
888
- fn privateTypeDeclarations(self: *FacadeEmitter) Error!void {
889
- var any = false;
890
- for (self.sidecar.types.structs) |entry| if (!entry.exported) {
891
- any = true;
892
- break;
893
- };
894
- if (!any) for (self.sidecar.types.enums) |entry| if (!entry.exported) {
895
- any = true;
896
- break;
897
- };
898
- if (!any) for (self.sidecar.types.unions) |entry| if (!entry.exported) {
899
- any = true;
900
- break;
901
- };
902
- if (!any) return;
903
-
904
- try self.raw(
905
- \\
906
- \\// Private contract-table declarations, reconstructed structurally
907
- \\// because their authored modules expose no importable designation.
908
- \\
909
- );
910
- for (self.sidecar.types.structs) |entry| {
911
- if (entry.exported) continue;
912
- try self.print("type {s} = {{\n", .{entry.name});
913
- for (entry.fields) |field| {
914
- try self.print(" readonly {s}: {s};\n", .{ try tsProp(self.arena, field.name), try self.spellRef(field.type) });
915
- }
916
- try self.raw("};\n\n");
917
- }
918
- for (self.sidecar.types.enums) |entry| {
919
- if (entry.exported) continue;
920
- try self.print("type {s} = ", .{entry.name});
921
- for (entry.members, 0..) |member, index| {
922
- try self.print("{s}\"{s}\"", .{ if (index == 0) "" else " | ", try tsString(self.arena, member) });
923
- }
924
- try self.raw(";\n\n");
925
- }
926
- for (self.sidecar.types.unions) |entry| {
927
- if (entry.exported) continue;
928
- try self.print("type {s} =\n", .{entry.name});
929
- for (entry.arms) |arm| {
930
- try self.print(" | {{ readonly kind: \"{s}\"", .{try tsString(self.arena, arm.name)});
931
- if (arm.payload != .void) {
932
- if (self.synthesizedRecordOf(arm.payload, entry.name, arm.name)) |record| {
933
- for (record.fields) |field| {
934
- try self.print("; readonly {s}: {s}", .{ try tsProp(self.arena, field.name), try self.spellRef(field.type) });
935
- }
936
- } else {
937
- try self.print("; readonly {s}: {s}", .{ try tsProp(self.arena, self.memberOf(arm.member)), try self.spellRef(arm.payload) });
938
- }
939
- }
940
- try self.raw(" }\n");
941
- }
942
- try self.raw(";\n\n");
943
- }
944
- }
945
-
946
- // -------------------------------------- channel consts and unbound
947
-
948
- fn channelConsts(self: *FacadeEmitter) Error!void {
949
- if (self.sidecar.channels.appearance_msg == null and self.sidecar.channels.chrome_msg == null and self.sidecar.channels.env_msgs.len == 0) return;
950
- try self.raw(
951
- \\
952
- \\// The exported-const channel conventions must be DECLARED here (the
953
- \\// sidecar emitter reads the entry module's own declarations;
954
- \\// re-exports do not join its tables).
955
- \\
956
- );
957
- if (self.sidecar.channels.appearance_msg) |arm_name| {
958
- try self.print("\nexport const appearanceMsg = \"{s}\";\n", .{try tsString(self.arena, arm_name)});
959
- }
960
- if (self.sidecar.channels.chrome_msg) |arm_name| {
961
- try self.print("\nexport const chromeMsg = \"{s}\";\n", .{try tsString(self.arena, arm_name)});
962
- }
963
- if (self.sidecar.channels.env_msgs.len > 0) {
964
- try self.raw("\nexport const envMsgs = [\n");
965
- for (self.sidecar.channels.env_msgs) |entry| {
966
- try self.print(" {{ env: \"{s}\", msg: \"{s}\" }},\n", .{ try tsString(self.arena, entry.env), try tsString(self.arena, entry.msg) });
967
- }
968
- try self.raw("];\n");
969
- }
970
- }
971
-
972
- fn unboundDecl(self: *FacadeEmitter) Error!void {
973
- const model = sidecar_mod.findStruct(self.sidecar.types, self.sidecar.model).?;
974
- var field_unbound: std.ArrayListUnmanaged([]const u8) = .empty;
975
- for (self.sidecar.model_unbound) |name| {
976
- for (model.fields) |field| {
977
- if (std.mem.eql(u8, field.name, name)) {
978
- try field_unbound.append(self.arena, name);
979
- break;
980
- }
981
- }
982
- }
983
- // Helper entries stay sidecar facts resolved by the compiler's
984
- // own name resolution: a helper name in the authored list
985
- // resolves against this module's exported wrappers.
986
- var helper_unbound: std.ArrayListUnmanaged([]const u8) = .empty;
987
- for (self.sidecar.model_unbound) |name| {
988
- for (self.sidecar.model_helpers) |helper| {
989
- if (std.mem.eql(u8, helper.name, name)) {
990
- try helper_unbound.append(self.arena, name);
991
- break;
992
- }
993
- }
994
- }
995
- // The authoring surface is ONE list resolved with the compiler's
996
- // Model-first precedence: fields, then helpers, then message arms.
997
- // A model-side homonym therefore projects faithfully, but an
998
- // unbound message arm shadowed by either model binding cannot be
999
- // named by this list. Refuse that direction instead of silently
1000
- // marking the model binding and leaving the arm bound.
1001
- for (self.sidecar.msg.unbound) |name| {
1002
- const also_field = for (model.fields) |field| {
1003
- if (std.mem.eql(u8, field.name, name)) break true;
1004
- } else false;
1005
- const also_helper = for (self.sidecar.model_helpers) |helper| {
1006
- if (std.mem.eql(u8, helper.name, name)) break true;
1007
- } else false;
1008
- if (also_field or also_helper) {
1009
- self.diags.flag("msg.unbound", "\"{s}\" is an unbound message arm shadowed by a homonymous Model field or exported helper — the compiler resolves Model fields and helpers before message arms, so the projection's single unbound list cannot mark this arm; rename one side in the core source", .{name});
1010
- }
1011
- }
1012
- if (self.diags.hasErrors()) return;
1013
- if (field_unbound.items.len == 0 and helper_unbound.items.len == 0 and self.sidecar.msg.unbound.len == 0) return;
1014
- try self.raw(
1015
- \\
1016
- \\// The unbound-list declaration, carried by the generator from the
1017
- \\// author's own markings in the core module: message arms only the
1018
- \\// host fires, and model fields and helpers only update logic reads.
1019
- \\export const viewUnbound = [
1020
- \\
1021
- );
1022
- for (self.sidecar.msg.unbound) |name| {
1023
- try self.print(" \"{s}\",\n", .{try tsString(self.arena, name)});
1024
- }
1025
- for (field_unbound.items) |name| {
1026
- try self.print(" \"{s}\",\n", .{try tsString(self.arena, name)});
1027
- }
1028
- for (helper_unbound.items) |name| {
1029
- try self.print(" \"{s}\",\n", .{try tsString(self.arena, name)});
1030
- }
1031
- try self.raw("];\n");
1032
- }
1033
-
1034
- // ------------------------------------------------- helper wrappers
1035
-
1036
- fn helperWrappers(self: *FacadeEmitter) Error!void {
1037
- if (self.sidecar.model_helpers.len == 0) return;
1038
- try self.raw(
1039
- \\
1040
- \\// The model helpers must be DECLARED here too, in declaration order
1041
- \\// — the compiled contract's model_helpers table and helper_call's
1042
- \\// index space both derive from it. Classed helper returns prove at
1043
- \\// this boundary: bind the helper's value, range-guard it (an
1044
- \\// ordered comparison excludes NaN), and state wholeness with
1045
- \\// Math.trunc at the return.
1046
- \\
1047
- );
1048
- for (self.sidecar.model_helpers) |helper| {
1049
- const return_type = try self.spellRef(helper.returns);
1050
- const is_int = helper.returns == .i64;
1051
- const is_optional_int = helper.returns == .optional and helper.returns.optional.* == .i64;
1052
- if (is_int or is_optional_int) {
1053
- const class = self.nestedSlotClass("helpers", helper.name, "return") orelse .i64;
1054
- if (is_optional_int) {
1055
- try self.print(
1056
- \\
1057
- \\export function {s}(model: {s}): {s} {{
1058
- \\ const nscfValue = nscfH_{s}(model);
1059
- \\ if (nscfValue === null) return null;
1060
- \\ if (nscfValue >= {s} && nscfValue <= {s}) return Math.trunc(nscfValue);
1061
- \\ nscfTrap("a helper return is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");
1062
- \\}}
1063
- \\
1064
- , .{ helper.name, self.sidecar.model, return_type, helper.name, integerLowerBound(class), max_safe });
1065
- } else {
1066
- try self.print(
1067
- \\
1068
- \\export function {s}(model: {s}): number {{
1069
- \\ const nscfValue = nscfH_{s}(model);
1070
- \\ if (nscfValue >= {s} && nscfValue <= {s}) return Math.trunc(nscfValue);
1071
- \\ nscfTrap("a helper return is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");
1072
- \\}}
1073
- \\
1074
- , .{ helper.name, self.sidecar.model, helper.name, integerLowerBound(class), max_safe });
1075
- }
1076
- self.use(.trap);
1077
- } else if (helper.returns == .slice) {
1078
- try self.print(
1079
- \\
1080
- \\export function {s}(model: {s}): {s} {{
1081
- \\ return nscfH_{s}(model) as {s};
1082
- \\}}
1083
- \\
1084
- , .{ helper.name, self.sidecar.model, return_type, helper.name, return_type });
1085
- } else {
1086
- try self.print(
1087
- \\
1088
- \\export function {s}(model: {s}): {s} {{
1089
- \\ return nscfH_{s}(model);
1090
- \\}}
1091
- \\
1092
- , .{ helper.name, self.sidecar.model, return_type, helper.name });
1093
- }
1094
- }
1095
- }
1096
-
1097
- // ---------------------------------------------------- entry points
1098
-
1099
- fn entryPoints(self: *FacadeEmitter) Error!void {
1100
- try self.raw(
1101
- \\
1102
- \\// The designated shape-flag exports: the profile names init and
1103
- \\// coreUpdate, and their return shapes restate the contract's
1104
- \\// init_returns_cmd/update_returns_cmd flags.
1105
- \\
1106
- );
1107
- if (self.sidecar.init_returns_cmd and self.sidecar.init_returns_bare) {
1108
- self.use(.cmd_encoder);
1109
- // The mixed author shape (`Model | [Model, Cmd<Msg>]`, the
1110
- // documented idiom): the wrapper narrows — a tuple carries
1111
- // its command, a bare model the empty command buffer.
1112
- try self.print(
1113
- \\
1114
- \\export function init(): [{s}, Uint8Array] {{
1115
- \\ const out = nscfInitialModel();
1116
- \\ if (Array.isArray(out)) return [out[0], nscfCmdBytes(out[1])];
1117
- \\ return [out, new Uint8Array(0)];
1118
- \\}}
1119
- \\
1120
- , .{self.sidecar.model});
1121
- } else if (self.sidecar.init_returns_cmd) {
1122
- self.use(.cmd_encoder);
1123
- try self.print(
1124
- \\
1125
- \\export function init(): [{s}, Uint8Array] {{
1126
- \\ const pair = nscfInitialModel();
1127
- \\ return [pair[0], nscfCmdBytes(pair[1])];
1128
- \\}}
1129
- \\
1130
- , .{self.sidecar.model});
1131
- } else {
1132
- try self.print(
1133
- \\
1134
- \\export function init(): {s} {{
1135
- \\ return nscfInitialModel();
1136
- \\}}
1137
- \\
1138
- , .{self.sidecar.model});
1139
- }
1140
- }
1141
-
1142
- fn tagTable(self: *FacadeEmitter) Error!void {
1143
- try self.raw(
1144
- \\
1145
- \\// Declaration-order wire tags (the contract sidecar is the tag
1146
- \\// authority; a skewed table cannot survive the paired battery's
1147
- \\// byte comparison or the mirror's boot fence).
1148
- \\const nscfArmNames = [
1149
- \\
1150
- );
1151
- for (self.sidecar.msg.arms) |arm| {
1152
- try self.print(" \"{s}\",\n", .{try tsString(self.arena, arm.name)});
1153
- }
1154
- try self.raw("];\n\n");
1155
- for (self.sidecar.msg.arms, 0..) |arm, tag| {
1156
- try self.print("const nscfTag_{s} = {d};\n", .{ arm.name, tag });
1157
- }
1158
- self.use(.trap);
1159
- try self.raw(
1160
- \\
1161
- \\function nscfTagOf(kind: string): number {
1162
- \\ for (let i = 0; i < nscfArmNames.length; i++) {
1163
- \\ if (nscfArmNames[i] === kind) return i;
1164
- \\ }
1165
- \\ nscfTrap("a command routes the unknown arm " + kind + " — the author module and this generated module disagree");
1166
- \\}
1167
- \\
1168
- );
1169
- if (self.sidecar.update_returns_cmd and self.sidecar.update_returns_bare) {
1170
- self.use(.cmd_encoder);
1171
- // The mixed author shape (`Model | [Model, Cmd<Msg>]`, the
1172
- // documented idiom): the wrapper narrows — a tuple carries
1173
- // its command, a bare model the empty command buffer.
1174
- try self.print(
1175
- \\
1176
- \\export function coreUpdate(model: {s}, msg: {s}): [{s}, Uint8Array] {{
1177
- \\ const out = nscfUpdate(model, msg);
1178
- \\ if (Array.isArray(out)) return [out[0], nscfCmdBytes(out[1])];
1179
- \\ return [out, new Uint8Array(0)];
1180
- \\}}
1181
- \\
1182
- , .{ self.sidecar.model, self.sidecar.msg.name, self.sidecar.model });
1183
- } else if (self.sidecar.update_returns_cmd) {
1184
- self.use(.cmd_encoder);
1185
- try self.print(
1186
- \\
1187
- \\export function coreUpdate(model: {s}, msg: {s}): [{s}, Uint8Array] {{
1188
- \\ const pair = nscfUpdate(model, msg);
1189
- \\ return [pair[0], nscfCmdBytes(pair[1])];
1190
- \\}}
1191
- \\
1192
- , .{ self.sidecar.model, self.sidecar.msg.name, self.sidecar.model });
1193
- } else {
1194
- try self.print(
1195
- \\
1196
- \\export function coreUpdate(model: {s}, msg: {s}): {s} {{
1197
- \\ return nscfUpdate(model, msg);
1198
- \\}}
1199
- \\
1200
- , .{ self.sidecar.model, self.sidecar.msg.name, self.sidecar.model });
1201
- }
1202
- if (self.sidecar.has_subscriptions) {
1203
- self.use(.sub_encoder);
1204
- try self.print(
1205
- \\
1206
- \\export function coreSubscriptions(model: {s}): Uint8Array {{
1207
- \\ return nscfSubBytes(nscfSubscriptions(model));
1208
- \\}}
1209
- \\
1210
- , .{self.sidecar.model});
1211
- }
1212
- }
1213
-
1214
- // ------------------------------------------------ dispatch surface
1215
-
1216
- fn dispatchSurface(self: *FacadeEmitter) Error!void {
1217
- self.use(.trap);
1218
- try self.raw(
1219
- \\
1220
- \\// ------------------------------------------------ the dispatch surface
1221
- \\// One committed model in module state; every dispatch entry runs one
1222
- \\// update+commit and returns the cycle's command bytes.
1223
- \\
1224
- \\
1225
- );
1226
- if (self.sidecar.init_returns_cmd) {
1227
- // Boot through the normalized init wrapper: the boot pair's
1228
- // command already rides as bytes.
1229
- try self.print("const nscfBootPair = init();\nlet nscfCommitted: {s} = nscfBootPair[0];\n", .{self.sidecar.model});
1230
- } else {
1231
- try self.print("let nscfCommitted: {s} = nscfInitialModel();\n", .{self.sidecar.model});
1232
- }
1233
- if (self.sidecar.update_returns_cmd) {
1234
- try self.print(
1235
- \\
1236
- \\function nscfCommit(out: [{s}, Uint8Array]): Uint8Array {{
1237
- \\ nscfCommitted = out[0];
1238
- \\ return out[1];
1239
- \\}}
1240
- \\
1241
- , .{self.sidecar.model});
1242
- } else {
1243
- try self.print(
1244
- \\
1245
- \\function nscfCommit(out: {s}): Uint8Array {{
1246
- \\ nscfCommitted = out;
1247
- \\ return new Uint8Array(0);
1248
- \\}}
1249
- \\
1250
- , .{self.sidecar.model});
1251
- }
1252
- try self.raw(
1253
- \\
1254
- \\function nscfUnknownTag(entry: string, tag: number): never {
1255
- \\ nscfTrap("tag " + tag + " does not name a " + entry + " message arm of this core — the host and this core disagree about the contract");
1256
- \\}
1257
- \\
1258
- );
1259
- if (self.sidecar.init_returns_cmd) {
1260
- try self.raw(
1261
- \\
1262
- \\export function boot_cmd(): Uint8Array {
1263
- \\ return nscfBootPair[1];
1264
- \\}
1265
- \\
1266
- );
1267
- } else {
1268
- try self.raw(
1269
- \\
1270
- \\export function boot_cmd(): Uint8Array {
1271
- \\ // init_returns_cmd is false for this contract: no boot command.
1272
- \\ return new Uint8Array(0);
1273
- \\}
1274
- \\
1275
- );
1276
- }
1277
- try self.dispatchVoid();
1278
- try self.dispatchBytes();
1279
- try self.dispatchNumber();
1280
- try self.dispatchNumberBytes();
1281
- try self.dispatchBool();
1282
- try self.dispatchEnum();
1283
- try self.dispatchRecord();
1284
- try self.dispatchTextInput();
1285
- try self.dispatchScrollState();
1286
- }
1287
-
1288
- /// The dispatch expression committing one update cycle for a
1289
- /// constructed arm object.
1290
- fn commitLine(self: *FacadeEmitter, arm_object: []const u8) Error![]const u8 {
1291
- return std.fmt.allocPrint(self.arena, "return nscfCommit(coreUpdate(nscfCommitted, {s}));", .{arm_object});
1292
- }
1293
-
1294
- fn dispatchVoid(self: *FacadeEmitter) Error!void {
1295
- try self.raw("\nexport function dispatch_void(tag: number): Uint8Array {\n");
1296
- for (self.sidecar.msg.arms) |arm| {
1297
- if (arm.payload != .void) continue;
1298
- try self.print(" if (tag === nscfTag_{s}) {s}\n", .{ arm.name, try self.commitLine(try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\" }}", .{try tsString(self.arena, arm.name)})) });
1299
- }
1300
- try self.raw(" nscfUnknownTag(\"bare\", tag);\n}\n");
1301
- }
1302
-
1303
- fn dispatchBytes(self: *FacadeEmitter) Error!void {
1304
- try self.raw("\nexport function dispatch_bytes(tag: number, payload: Uint8Array): Uint8Array {\n");
1305
- for (self.sidecar.msg.arms) |arm| {
1306
- const carries_bytes = switch (arm.payload) {
1307
- .bytes => true,
1308
- .scalar => |ref| ref == .bytes,
1309
- else => false,
1310
- };
1311
- if (!carries_bytes) continue;
1312
- const object = try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: payload }}", .{ try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)) });
1313
- try self.print(" if (tag === nscfTag_{s}) {s}\n", .{ arm.name, try self.commitLine(object) });
1314
- }
1315
- try self.raw(" nscfUnknownTag(\"bytes\", tag);\n}\n");
1316
- }
1317
-
1318
- fn dispatchNumber(self: *FacadeEmitter) Error!void {
1319
- try self.raw("\nexport function dispatch_number(tag: number, value: number): Uint8Array {\n");
1320
- var f64_count: usize = 0;
1321
- for (self.sidecar.msg.arms) |arm| {
1322
- if (payloadNumberClass(arm.payload)) |class| {
1323
- if (class == .f64) f64_count += 1;
1324
- }
1325
- }
1326
- if (f64_count > 0) {
1327
- try self.raw(" // These arms remain f64-classed in the contract: preserve the value\n // exactly instead of routing it through the integer proof below.\n");
1328
- for (self.sidecar.msg.arms) |arm| {
1329
- if (payloadNumberClass(arm.payload) != .f64) continue;
1330
- const object = try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: value }}", .{ try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)) });
1331
- try self.print(" if (tag === nscfTag_{s}) {s}\n", .{ arm.name, try self.commitLine(object) });
1332
- }
1333
- }
1334
- for (self.sidecar.msg.arms) |arm| {
1335
- if (payloadNumberClass(arm.payload) != .i64) continue;
1336
- const class = self.slotClass(self.sidecar.msg.name, arm.name) orelse .i64;
1337
- const object = try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: whole }}", .{ try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)) });
1338
- try self.print(
1339
- \\ // This integer-classed arm proves in place: its attestation
1340
- \\ // selects the signed or unsigned lower bound, the ordered
1341
- \\ // comparisons exclude NaN, and Math.trunc states wholeness.
1342
- \\ if (tag === nscfTag_{s}) {{
1343
- \\ if (value >= {s} && value <= {s}) {{
1344
- \\ const whole = Math.trunc(value);
1345
- \\ return nscfCommit(coreUpdate(nscfCommitted, {s}));
1346
- \\ }}
1347
- \\ nscfTrap("a numeric dispatch value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");
1348
- \\ }}
1349
- \\
1350
- , .{ arm.name, integerLowerBound(class), max_safe, object });
1351
- }
1352
- try self.raw(" nscfUnknownTag(\"number\", tag);\n}\n");
1353
- }
1354
-
1355
- fn dispatchNumberBytes(self: *FacadeEmitter) Error!void {
1356
- try self.raw("\nexport function dispatch_number_bytes(tag: number, value: number, payload: Uint8Array): Uint8Array {\n");
1357
- for (self.sidecar.msg.arms) |arm| {
1358
- switch (arm.payload) {
1359
- .number_bytes => |desc| {
1360
- const kind = try tsString(self.arena, arm.name);
1361
- const number_prop = try tsProp(self.arena, desc.number_field);
1362
- const bytes_prop = try tsProp(self.arena, desc.bytes_field);
1363
- if (desc.number_class == .i64) {
1364
- const class = self.nestedSlotClass(self.sidecar.msg.name, arm.name, desc.number_field) orelse .i64;
1365
- try self.print(
1366
- \\ if (tag === nscfTag_{s}) {{
1367
- \\ // The number field is i64-classed: range-guard the raw f64 (an
1368
- \\ // ordered comparison excludes NaN) and state wholeness with
1369
- \\ // Math.trunc at the write.
1370
- \\ if (value >= {s} && value <= {s}) {{
1371
- \\ return nscfCommit(coreUpdate(nscfCommitted, {{ kind: "{s}", {s}: Math.trunc(value), {s}: payload }}));
1372
- \\ }}
1373
- \\ nscfTrap("a numeric dispatch value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");
1374
- \\ }}
1375
- \\
1376
- , .{ arm.name, integerLowerBound(class), max_safe, kind, number_prop, bytes_prop });
1377
- } else {
1378
- try self.print(" if (tag === nscfTag_{s}) return nscfCommit(coreUpdate(nscfCommitted, {{ kind: \"{s}\", {s}: value, {s}: payload }}));\n", .{ arm.name, kind, number_prop, bytes_prop });
1379
- }
1380
- },
1381
- else => {},
1382
- }
1383
- }
1384
- try self.raw(" nscfUnknownTag(\"number-with-bytes\", tag);\n}\n");
1385
- }
1386
-
1387
- fn dispatchBool(self: *FacadeEmitter) Error!void {
1388
- try self.raw("\nexport function dispatch_bool(tag: number, value: number): Uint8Array {\n");
1389
- for (self.sidecar.msg.arms) |arm| {
1390
- switch (arm.payload) {
1391
- .scalar => |ref| {
1392
- if (ref != .bool) continue;
1393
- const object = try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: value !== 0 }}", .{ try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)) });
1394
- try self.print(" if (tag === nscfTag_{s}) {s}\n", .{ arm.name, try self.commitLine(object) });
1395
- },
1396
- else => {},
1397
- }
1398
- }
1399
- try self.raw(" nscfUnknownTag(\"boolean\", tag);\n}\n");
1400
- }
1401
-
1402
- fn dispatchEnum(self: *FacadeEmitter) Error!void {
1403
- try self.raw("\nexport function dispatch_enum(tag: number, member: number): Uint8Array {\n");
1404
- for (self.sidecar.msg.arms) |arm| {
1405
- switch (arm.payload) {
1406
- .enum_ref => |name| {
1407
- try self.needEnumTable(name);
1408
- const object = try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: nscfMembers{s}[member]! }}", .{ try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)), name });
1409
- try self.print(
1410
- \\ if (tag === nscfTag_{s}) {{
1411
- \\ if (member >= nscfMembers{s}.length) nscfMember("{s}", member);
1412
- \\ {s}
1413
- \\ }}
1414
- \\
1415
- , .{ arm.name, name, try tsString(self.arena, name), try self.commitLine(object) });
1416
- self.needs_member_trap = true;
1417
- },
1418
- else => {},
1419
- }
1420
- }
1421
- try self.raw(" nscfUnknownTag(\"enum\", tag);\n}\n");
1422
- }
1423
-
1424
- fn dispatchRecord(self: *FacadeEmitter) Error!void {
1425
- try self.raw("\nexport function dispatch_record(tag: number, fields: Uint8Array): Uint8Array {\n");
1426
- for (self.sidecar.msg.arms) |arm| {
1427
- switch (arm.payload) {
1428
- .record => |name| {
1429
- const record = sidecar_mod.findStruct(self.sidecar.types, name) orelse continue;
1430
- try self.print(" if (tag === nscfTag_{s}) {{\n", .{arm.name});
1431
- if (self.synthesizedRecordOf(recordPayloadRef(arm.payload), self.sidecar.msg.name, arm.name) != null) {
1432
- try self.recordDecodeCommit(record, arm.name, null);
1433
- } else {
1434
- try self.recordDecodeCommit(record, arm.name, self.memberOf(arm.member));
1435
- }
1436
- try self.raw(" }\n");
1437
- },
1438
- .union_ref => |name| {
1439
- // The emitted contract may store this union's record
1440
- // payloads by reference, in which case the mirror
1441
- // routes the arm through the generic record entry;
1442
- // the canonical union encoding is the same either
1443
- // way.
1444
- try self.needUnionDecoder(name);
1445
- try self.print(" if (tag === nscfTag_{s}) return nscfCommit(coreUpdate(nscfCommitted, {{ kind: \"{s}\", {s}: nscfDecode{s}(fields) }}));\n", .{ arm.name, try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)), name });
1446
- },
1447
- else => {},
1448
- }
1449
- }
1450
- try self.raw(" nscfUnknownTag(\"record\", tag);\n}\n");
1451
- }
1452
-
1453
- fn dispatchTextInput(self: *FacadeEmitter) Error!void {
1454
- try self.raw("\nexport function dispatch_text_input(tag: number, event: Uint8Array): Uint8Array {\n");
1455
- for (self.sidecar.msg.arms) |arm| {
1456
- switch (arm.payload) {
1457
- .union_ref => |name| {
1458
- try self.needUnionDecoder(name);
1459
- try self.print(" if (tag === nscfTag_{s}) return nscfCommit(coreUpdate(nscfCommitted, {{ kind: \"{s}\", {s}: nscfDecode{s}(event) }}));\n", .{ arm.name, try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)), name });
1460
- },
1461
- else => {},
1462
- }
1463
- }
1464
- try self.raw(" nscfUnknownTag(\"text-input\", tag);\n}\n");
1465
- }
1466
-
1467
- fn dispatchScrollState(self: *FacadeEmitter) Error!void {
1468
- try self.raw(
1469
- \\
1470
- \\export function dispatch_scroll_state(
1471
- \\ tag: number,
1472
- \\ offsetX: number,
1473
- \\ offsetY: number,
1474
- \\ velocityX: number,
1475
- \\ velocityY: number,
1476
- \\ viewportExtentX: number,
1477
- \\ viewportExtentY: number,
1478
- \\ contentExtentX: number,
1479
- \\ contentExtentY: number,
1480
- \\): Uint8Array {
1481
- \\
1482
- );
1483
- for (self.sidecar.msg.arms) |arm| {
1484
- switch (arm.payload) {
1485
- .record => |name| {
1486
- const record = self.scrollShapedRecord(name) orelse continue;
1487
- // Construct the scroll record with the author's own
1488
- // field spellings, each fed by its axis parameter. An
1489
- // integer-attested axis proves against its own signed or
1490
- // unsigned range before Math.trunc states wholeness.
1491
- var fields_text: std.ArrayListUnmanaged(u8) = .empty;
1492
- var guards: std.ArrayListUnmanaged(u8) = .empty;
1493
- for (record.fields, 0..) |field, index| {
1494
- const param = scrollParamFor(field.name) orelse field.name;
1495
- const value = if (field.type == .i64) blk: {
1496
- const class = self.slotClass(record.name, field.name) orelse .i64;
1497
- if (guards.items.len > 0) try guards.appendSlice(self.arena, " && ");
1498
- try guards.appendSlice(self.arena, try std.fmt.allocPrint(self.arena, "{s} >= {s} && {s} <= {s}", .{ param, integerLowerBound(class), param, max_safe }));
1499
- break :blk try std.fmt.allocPrint(self.arena, "Math.trunc({s})", .{param});
1500
- } else param;
1501
- if (index > 0) try fields_text.appendSlice(self.arena, ", ");
1502
- try fields_text.appendSlice(self.arena, try std.fmt.allocPrint(self.arena, "{s}: {s}", .{ try tsProp(self.arena, field.name), value }));
1503
- }
1504
- const object = if (self.synthesizedRecordOf(recordPayloadRef(arm.payload), self.sidecar.msg.name, arm.name) != null)
1505
- // Inline message-arm records have no authored payload
1506
- // member: their fields sit beside `kind`, exactly as
1507
- // the generic record dispatch constructs them.
1508
- try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s} }}", .{ try tsString(self.arena, arm.name), fields_text.items })
1509
- else
1510
- try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: {{ {s} }} }}", .{ try tsString(self.arena, arm.name), try tsProp(self.arena, self.memberOf(arm.member)), fields_text.items });
1511
- if (guards.items.len == 0) {
1512
- try self.print(" if (tag === nscfTag_{s}) {s}\n", .{ arm.name, try self.commitLine(object) });
1513
- } else {
1514
- try self.print(
1515
- \\ if (tag === nscfTag_{s}) {{
1516
- \\ if ({s}) return nscfCommit(coreUpdate(nscfCommitted, {s}));
1517
- \\ nscfTrap("a scroll dispatch value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");
1518
- \\ }}
1519
- \\
1520
- , .{ arm.name, guards.items, object });
1521
- self.use(.trap);
1522
- }
1523
- },
1524
- else => {},
1525
- }
1526
- }
1527
- try self.raw(" nscfUnknownTag(\"scroll-state\", tag);\n}\n");
1528
- }
1529
-
1530
- /// The record behind a scroll-shaped arm payload: eight numeric
1531
- /// fields spelling the two-axis vocabulary (the mirror's routing
1532
- /// rule restated over sidecar data).
1533
- fn scrollShapedRecord(self: *FacadeEmitter, name: []const u8) ?*const sidecar_mod.Struct {
1534
- const entry = sidecar_mod.findStruct(self.sidecar.types, name) orelse return null;
1535
- if (entry.fields.len != 8) return null;
1536
- const spellings = [_][8][]const u8{ scroll_state_fields_ts, scroll_state_fields_canvas };
1537
- for (spellings) |names| {
1538
- var all_found = true;
1539
- for (names) |expected| {
1540
- for (entry.fields) |field| {
1541
- const numeric = field.type == .f64 or field.type == .i64;
1542
- if (std.mem.eql(u8, field.name, expected) and numeric) break;
1543
- } else {
1544
- all_found = false;
1545
- break;
1546
- }
1547
- }
1548
- if (all_found) return entry;
1549
- }
1550
- return null;
1551
- }
1552
-
1553
- // ------------------------------------------------- channel entries
1554
-
1555
- fn channelEntries(self: *FacadeEmitter) Error!void {
1556
- const chan = self.sidecar.channels;
1557
- if (!(chan.command_msg or chan.frame_msg or chan.key_msg or chan.pinch_msg or chan.drop_msg)) return;
1558
- self.use(.sink);
1559
- self.use(.trap);
1560
- try self.print(
1561
- \\
1562
- \\// --------------------------------------------- the ABI channel entries
1563
- \\// Each answers the channel bytes envelope: [produced u8][tag u8]
1564
- \\// [payload in the arm's canonical value encoding]. Byte 0 is 0
1565
- \\// (nothing produced; the envelope is exactly two bytes) or 1.
1566
- \\
1567
- \\function nscfPackMsg(produced: {s} | null): Uint8Array {{
1568
- \\ if (produced === null) return new Uint8Array(2);
1569
- \\ const sink = nscfNewSink();
1570
- \\ nscfMsgPayload(sink, produced);
1571
- \\ const payload = nscfFinish(sink);
1572
- \\ const out = new Uint8Array(2 + payload.length);
1573
- \\ out[0] = 1;
1574
- \\ out[1] = nscfTagOf(produced.kind);
1575
- \\ for (let i = 0; i < payload.length; i++) out[2 + i] = payload[i]!;
1576
- \\ return out;
1577
- \\}}
1578
- \\
1579
- , .{self.sidecar.msg.name});
1580
- try self.msgPayloadWriter();
1581
- if (chan.key_msg or chan.command_msg) {
1582
- self.use(.ascii_string);
1583
- }
1584
- if (chan.command_msg) {
1585
- try self.raw(
1586
- \\
1587
- \\export function abi_command_msg(name: Uint8Array): Uint8Array {
1588
- \\ return nscfPackMsg(nscfChanCommandMsg(nscfAsciiString(name)));
1589
- \\}
1590
- \\
1591
- );
1592
- }
1593
- if (chan.frame_msg) {
1594
- try self.raw(
1595
- \\
1596
- \\export function abi_frame_msg(width: number, height: number, timestampMs: number, intervalMs: number): Uint8Array {
1597
- \\ return nscfPackMsg(nscfChanFrameMsg(nscfCommitted, {
1598
- \\ width: width,
1599
- \\ height: height,
1600
- \\ timestampMs: timestampMs,
1601
- \\ intervalMs: intervalMs,
1602
- \\ }));
1603
- \\}
1604
- \\
1605
- );
1606
- }
1607
- if (chan.key_msg) {
1608
- try self.raw(
1609
- \\
1610
- \\export function abi_key_msg(
1611
- \\ key: Uint8Array,
1612
- \\ shift: number,
1613
- \\ control: number,
1614
- \\ alt: number,
1615
- \\ superMod: number,
1616
- \\): Uint8Array {
1617
- \\ return nscfPackMsg(nscfChanKeyMsg({
1618
- \\ key: nscfAsciiString(key),
1619
- \\ shift: shift !== 0,
1620
- \\ control: control !== 0,
1621
- \\ alt: alt !== 0,
1622
- \\ super: superMod !== 0,
1623
- \\ }));
1624
- \\}
1625
- \\
1626
- );
1627
- }
1628
- if (chan.pinch_msg) {
1629
- self.needs_pinch_phase = true;
1630
- self.use(.ascii_string);
1631
- try self.raw(
1632
- \\
1633
- \\// The pinch phase table the channel's u32 member index reads back
1634
- \\// through (the SDK's declared PinchPhase members, in order).
1635
- \\const nscfPinchPhases: PinchPhase[] = ["begin", "change", "end"];
1636
- \\
1637
- \\export function abi_pinch_msg(
1638
- \\ windowId: number,
1639
- \\ label: Uint8Array,
1640
- \\ phase: number,
1641
- \\ scale: number,
1642
- \\ x: number,
1643
- \\ y: number,
1644
- \\): Uint8Array {
1645
- \\ if (phase >= nscfPinchPhases.length) nscfMember("PinchPhase", phase);
1646
- \\ return nscfPackMsg(nscfChanPinchMsg({
1647
- \\ windowId: windowId,
1648
- \\ label: nscfAsciiString(label),
1649
- \\ phase: nscfPinchPhases[phase]!,
1650
- \\ scale: scale,
1651
- \\ x: x,
1652
- \\ y: y,
1653
- \\ }));
1654
- \\}
1655
- \\
1656
- );
1657
- self.needs_member_trap = true;
1658
- }
1659
- if (chan.drop_msg) {
1660
- self.use(.read_f64);
1661
- self.use(.read_u32);
1662
- self.use(.read_bool);
1663
- self.use(.read_bytes_body);
1664
- self.use(.assert_consumed);
1665
- self.use(.ascii_string);
1666
- try self.raw(
1667
- \\
1668
- \\export function abi_drop_msg(event: Uint8Array): Uint8Array {
1669
- \\ let at = 0;
1670
- \\ const windowId = nscfReadF64(event, at);
1671
- \\ at += 8;
1672
- \\ const viewLabelLen = nscfReadU32(event, at);
1673
- \\ at += 4;
1674
- \\ const viewLabel = nscfReadBytesBody(event, at, viewLabelLen);
1675
- \\ at += viewLabelLen;
1676
- \\ const pointPresent = nscfReadBool(event, at);
1677
- \\ at += 1;
1678
- \\ let point: FileDropPoint | null = null;
1679
- \\ if (pointPresent) {
1680
- \\ const x = nscfReadF64(event, at);
1681
- \\ at += 8;
1682
- \\ const y = nscfReadF64(event, at);
1683
- \\ at += 8;
1684
- \\ point = { x: x, y: y };
1685
- \\ }
1686
- \\ const pathCount = nscfReadU32(event, at);
1687
- \\ at += 4;
1688
- \\ const paths: Uint8Array[] = [];
1689
- \\ for (let i = 0; i < pathCount; i++) {
1690
- \\ const pathLen = nscfReadU32(event, at);
1691
- \\ at += 4;
1692
- \\ paths.push(nscfReadBytesBody(event, at, pathLen));
1693
- \\ at += pathLen;
1694
- \\ }
1695
- \\ nscfAssertConsumed(event, at);
1696
- \\ return nscfPackMsg(nscfChanDropMsg({
1697
- \\ windowId: windowId,
1698
- \\ viewLabel: nscfAsciiString(viewLabel),
1699
- \\ point: point,
1700
- \\ paths: paths,
1701
- \\ }));
1702
- \\}
1703
- \\
1704
- );
1705
- }
1706
- }
1707
-
1708
- /// The canonical payload encoding of any produced message, off the
1709
- /// narrowed arm value — the envelope's tail must decode against the
1710
- /// arm's mirror payload type, so field order and number classes
1711
- /// follow the sidecar exactly.
1712
- fn msgPayloadWriter(self: *FacadeEmitter) Error!void {
1713
- try self.print("\nfunction nscfMsgPayload(sink: nscfSink, value: {s}): void {{\n", .{self.sidecar.msg.name});
1714
- for (self.sidecar.msg.arms) |arm| {
1715
- try self.print(" if (value.kind === \"{s}\") {{\n", .{try tsString(self.arena, arm.name)});
1716
- const member = self.memberOf(arm.member);
1717
- switch (arm.payload) {
1718
- .void => {},
1719
- .bytes => {
1720
- self.use(.w_bytes);
1721
- try self.print(" nscfWBytes(sink, {s});\n", .{try tsAccess(self.arena, "value", member)});
1722
- },
1723
- .number => |class| {
1724
- const access = try tsAccess(self.arena, "value", member);
1725
- if (class == .i64) {
1726
- try self.print(" {s}(sink, {s});\n", .{ self.intWriter(self.sidecar.msg.name, arm.name), access });
1727
- } else {
1728
- self.use(.w_f64);
1729
- try self.print(" nscfWF64(sink, {s});\n", .{access});
1730
- }
1731
- },
1732
- .number_bytes => |desc| {
1733
- // The mirror declares the number field first, so the
1734
- // number's bytes lead.
1735
- const number_access = try tsAccess(self.arena, "value", desc.number_field);
1736
- if (desc.number_class == .i64) {
1737
- const slot_member = try std.fmt.allocPrint(self.arena, "{s}.{s}", .{ arm.name, desc.number_field });
1738
- try self.print(" {s}(sink, {s});\n", .{ self.intWriter(self.sidecar.msg.name, slot_member), number_access });
1739
- } else {
1740
- self.use(.w_f64);
1741
- try self.print(" nscfWF64(sink, {s});\n", .{number_access});
1742
- }
1743
- self.use(.w_bytes);
1744
- try self.print(" nscfWBytes(sink, {s});\n", .{try tsAccess(self.arena, "value", desc.bytes_field)});
1745
- },
1746
- .record => |name| {
1747
- const record = sidecar_mod.findStruct(self.sidecar.types, name).?;
1748
- if (self.synthesizedRecordOf(recordPayloadRef(arm.payload), self.sidecar.msg.name, arm.name) != null) {
1749
- // Flattened beside kind: encode the record's
1750
- // fields off the narrowed arm in declaration
1751
- // order.
1752
- for (record.fields) |field| {
1753
- try self.fieldWriteStatements(field.type, try tsAccess(self.arena, "value", field.name), name, field.name, 2);
1754
- }
1755
- } else {
1756
- try self.needRecordWriter(name);
1757
- try self.print(" nscfWrite{s}(sink, {s});\n", .{ name, try tsAccess(self.arena, "value", member) });
1758
- }
1759
- },
1760
- .union_ref => |name| {
1761
- try self.needUnionWriter(name);
1762
- try self.print(" nscfWrite{s}(sink, {s});\n", .{ name, try tsAccess(self.arena, "value", member) });
1763
- },
1764
- .enum_ref => |name| {
1765
- try self.needEnumIndex(name);
1766
- self.use(.w_u32);
1767
- try self.print(" nscfWU32(sink, nscfIndex{s}({s}));\n", .{ name, try tsAccess(self.arena, "value", member) });
1768
- },
1769
- .scalar => |ref| {
1770
- const access = try tsAccess(self.arena, "value", member);
1771
- switch (ref) {
1772
- .bool => {
1773
- self.use(.w_bool);
1774
- try self.print(" nscfWBool(sink, {s});\n", .{access});
1775
- },
1776
- .f64 => {
1777
- self.use(.w_f64);
1778
- try self.print(" nscfWF64(sink, {s});\n", .{access});
1779
- },
1780
- .i64 => try self.print(" {s}(sink, {s});\n", .{ self.intWriter(self.sidecar.msg.name, arm.name), access }),
1781
- .bytes => {
1782
- self.use(.w_bytes);
1783
- try self.print(" nscfWBytes(sink, {s});\n", .{access});
1784
- },
1785
- else => self.diags.flag("msg.arms", "arm \"{s}\" carries a scalar payload outside the generated channel encoding (only bool, number, and bytes scalars have ABI entries); extend the generator before wiring it", .{arm.name}),
1786
- }
1787
- },
1788
- }
1789
- try self.raw(" return;\n }\n");
1790
- }
1791
- try self.raw(" nscfTrap(\"a channel produced a message outside the declared union — the value and the contract disagree\");\n}\n");
1792
- }
1793
-
1794
- // ------------------------------------------------------ post-cycle
1795
-
1796
- fn postCycle(self: *FacadeEmitter) Error!void {
1797
- try self.raw("\n// --------------------------------------------------------- post-cycle\n");
1798
- if (self.sidecar.has_subscriptions) {
1799
- try self.raw(
1800
- \\
1801
- \\export function abi_subscriptions(): Uint8Array {
1802
- \\ return coreSubscriptions(nscfCommitted);
1803
- \\}
1804
- \\
1805
- );
1806
- } else {
1807
- try self.raw(
1808
- \\
1809
- \\export function abi_subscriptions(): Uint8Array {
1810
- \\ // has_subscriptions is false for this contract: always empty.
1811
- \\ return new Uint8Array(0);
1812
- \\}
1813
- \\
1814
- );
1815
- }
1816
- const model = sidecar_mod.findStruct(self.sidecar.types, self.sidecar.model) orelse {
1817
- self.diags.flag("model", "the model does not name a tabled record", .{});
1818
- return;
1819
- };
1820
- self.use(.sink);
1821
- self.use(.w_u32);
1822
- self.use(.w_bytes);
1823
- try self.needRecordWriter(self.sidecar.model);
1824
- try self.print(
1825
- \\
1826
- \\// The positional committed-model encoding used only by the
1827
- \\// core/shim mirror ABI. Keep this stable with shim_rt.decodeSnapshot;
1828
- \\// durable persistence has its own tagged export below.
1829
- \\export function model_snapshot(): Uint8Array {{
1830
- \\ const sink = nscfNewSink();
1831
- \\ nscfWrite{s}(sink, nscfCommitted);
1832
- \\ return nscfFinish(sink);
1833
- \\}}
1834
- \\
1835
- , .{self.sidecar.model});
1836
- try self.print(
1837
- \\
1838
- \\// The canonical committed-model encoding (snapshot format {d}): the
1839
- \\// root record is a u32 field count followed by tagged fields
1840
- \\// [u32 declaration-index][u32 payload-length][payload]. Each payload
1841
- \\// uses the command dialect's little-endian canonical value encoding.
1842
- \\function nscfSnapshot{s}(value: {s}): Uint8Array {{
1843
- \\ const sink = nscfNewSink();
1844
- \\ nscfWU32(sink, {d});
1845
- \\
1846
- , .{ self.sidecar.abi.snapshot_format, self.sidecar.model, self.sidecar.model, model.fields.len });
1847
- self.temp_counter = 0;
1848
- for (model.fields, 0..) |field, index| {
1849
- try self.print(" {{\n const nscfFieldSink{d} = nscfNewSink();\n {{\n const sink = nscfFieldSink{d};\n", .{ index, index });
1850
- try self.fieldWriteStatements(field.type, try tsAccess(self.arena, "value", field.name), model.name, field.name, 3);
1851
- try self.print(" }}\n nscfWU32(sink, {d});\n nscfWBytes(sink, nscfFinish(nscfFieldSink{d}));\n }}\n", .{ index, index });
1852
- }
1853
- try self.print(
1854
- \\
1855
- \\ return nscfFinish(sink);
1856
- \\}}
1857
- \\
1858
- \\export function persist_snapshot(): Uint8Array {{
1859
- \\ return nscfSnapshot{s}(nscfCommitted);
1860
- \\}}
1861
- \\
1862
- , .{self.sidecar.model});
1863
-
1864
- // The per-field lengths are authoritative: strip the tagged root into
1865
- // the existing positional dialect, then run one whole-Model decoder.
1866
- // Keeping the Model construction inside that decoder also preserves
1867
- // scriptc's exact-integer proofs for optional and nested integer slots.
1868
- try self.print("\nfunction nscfDecodeSnapshot{s}(bytes: Uint8Array): {s} {{\n", .{ self.sidecar.model, self.sidecar.model });
1869
- var model_decode = RecordDecode{ .emitter = self, .buf = "bytes", .indent = 1 };
1870
- try model_decode.run(model);
1871
- self.use(.assert_consumed);
1872
- try self.print(" nscfAssertConsumed(bytes, {s});\n", .{model_decode.offsetText()});
1873
- const construction = try model_decode.constructionText(model);
1874
- if (model_decode.guards.items.len > 0) {
1875
- try self.print(" if ({s}) return {s};\n nscfTrap(\"a restored integer value is NaN or outside its attested exact-integer range — the snapshot cannot represent this Model\");\n", .{ model_decode.guards.items, construction });
1876
- self.use(.trap);
1877
- } else {
1878
- try self.print(" return {s};\n", .{construction});
1879
- }
1880
- try self.raw("}\n");
1881
-
1882
- try self.raw(
1883
- \\
1884
- \\function nscfSnapshotPayloads(snapshot: Uint8Array): Uint8Array {
1885
- \\ let nscfAt = 0;
1886
- \\ const sink = nscfNewSink();
1887
- );
1888
- self.use(.read_u32);
1889
- self.use(.read_bytes_body);
1890
- self.use(.trap);
1891
- try self.print(" const nscfFieldCount = nscfReadU32(snapshot, nscfAt);\n nscfAt += 4;\n if (nscfFieldCount !== {d}) nscfTrap(\"a model snapshot carries the wrong field count for this Model\");\n", .{model.fields.len});
1892
- for (model.fields, 0..) |_, index| {
1893
- try self.print(" const nscfFieldTag{d} = nscfReadU32(snapshot, nscfAt);\n nscfAt += 4;\n if (nscfFieldTag{d} !== {d}) nscfTrap(\"a model snapshot field tag does not match this Model\");\n const nscfFieldLen{d} = nscfReadU32(snapshot, nscfAt);\n nscfAt += 4;\n const nscfFieldBytes{d} = nscfReadBytesBody(snapshot, nscfAt, nscfFieldLen{d});\n nscfAt += nscfFieldLen{d};\n for (let nscfFieldAt{d} = 0; nscfFieldAt{d} < nscfFieldBytes{d}.length; nscfFieldAt{d}++) sink.push(nscfFieldBytes{d}[nscfFieldAt{d}]!);\n", .{ index, index, index, index, index, index, index, index, index, index, index, index, index });
1894
- }
1895
- try self.raw(
1896
- \\ nscfAssertConsumed(snapshot, nscfAt);
1897
- \\ return nscfFinish(sink);
1898
- \\}
1899
- \\
1900
- \\// Replace the committed root from the same canonical encoding
1901
- \\// persist_snapshot emits. The ABI result is intentionally empty:
1902
- \\// restore is a boot mutation owned by the host, not an app Cmd.
1903
- \\
1904
- );
1905
- try self.print(
1906
- \\export function restore_model(snapshot: Uint8Array): Uint8Array {{
1907
- \\ nscfCommitted = nscfDecodeSnapshot{s}(nscfSnapshotPayloads(snapshot));
1908
- \\ return new Uint8Array(0);
1909
- \\}}
1910
- \\
1911
- , .{self.sidecar.model});
1912
-
1913
- if (self.sidecar.has_migrate) {
1914
- try self.print(
1915
- \\
1916
- \\// Pure schema migration. A one-byte status prefix keeps an
1917
- \\// empty Model snapshot distinguishable from failure.
1918
- \\export function migrate_model(snapshot: Uint8Array, fromVersion: number): Uint8Array {{
1919
- \\ try {{
1920
- \\ const migrated = nscfMigrate(snapshot, fromVersion);
1921
- \\ const body = nscfSnapshot{s}(migrated);
1922
- \\ const out = new Uint8Array(body.length + 1);
1923
- \\ out[0] = 1;
1924
- \\ for (let i = 0; i < body.length; i++) out[i + 1] = body[i]!;
1925
- \\ return out;
1926
- \\ }} catch {{
1927
- \\ return new Uint8Array(1);
1928
- \\ }}
1929
- \\}}
1930
- \\
1931
- , .{self.sidecar.model});
1932
- } else {
1933
- try self.raw(
1934
- \\
1935
- \\// This core declares no migration hook.
1936
- \\export function migrate_model(snapshot: Uint8Array, fromVersion: number): Uint8Array {
1937
- \\ return new Uint8Array(1);
1938
- \\}
1939
- \\
1940
- );
1941
- }
1942
- }
1943
-
1944
- fn helperCall(self: *FacadeEmitter) Error!void {
1945
- self.use(.trap);
1946
- if (self.sidecar.model_helpers.len == 0) {
1947
- self.use(.assert_consumed);
1948
- try self.raw(
1949
- \\
1950
- \\// This core declares no model helpers; the entry stays for the ABI's
1951
- \\// fixed export set.
1952
- \\export function helper_call(helper: number, args: Uint8Array): Uint8Array {
1953
- \\ nscfAssertConsumed(args, 0);
1954
- \\ nscfTrap("helper index " + helper + " does not name an exported model helper of this core — the host and this core disagree about the contract");
1955
- \\}
1956
- \\
1957
- );
1958
- return;
1959
- }
1960
- self.use(.assert_consumed);
1961
- self.use(.sink);
1962
- try self.raw(
1963
- \\
1964
- \\// ------------------------------------------------------- model helpers
1965
- \\// Indexed by the contract's model_helpers order; results ride the
1966
- \\// canonical value encoding of each helper's declared return type.
1967
- \\export function helper_call(helper: number, args: Uint8Array): Uint8Array {
1968
- \\ nscfAssertConsumed(args, 0);
1969
- \\
1970
- );
1971
- for (self.sidecar.model_helpers, 0..) |helper, index| {
1972
- try self.print(" if (helper === {d}) {{\n const sink = nscfNewSink();\n const nscfValue = {s}(nscfCommitted);\n", .{ index, helper.name });
1973
- const slot_member = try std.fmt.allocPrint(self.arena, "{s}.return", .{helper.name});
1974
- try self.fieldWriteStatements(helper.returns, "nscfValue", "helpers", slot_member, 2);
1975
- try self.raw(" return nscfFinish(sink);\n }\n");
1976
- }
1977
- try self.raw(" nscfTrap(\"helper index \" + helper + \" does not name an exported model helper of this core — the host and this core disagree about the contract\");\n}\n");
1978
- }
1979
-
1980
- // ------------------------------------- generated writers/decoders
1981
-
1982
- fn needEnumTable(self: *FacadeEmitter, name: []const u8) Error!void {
1983
- if (nameListed(self.needed_enum_tables.items, name)) return;
1984
- try self.needed_enum_tables.append(self.arena, name);
1985
- try self.reference(name);
1986
- }
1987
-
1988
- fn needEnumIndex(self: *FacadeEmitter, name: []const u8) Error!void {
1989
- try self.needEnumTable(name);
1990
- if (nameListed(self.needed_enum_indexes.items, name)) return;
1991
- try self.needed_enum_indexes.append(self.arena, name);
1992
- }
1993
-
1994
- fn needRecordWriter(self: *FacadeEmitter, name: []const u8) Error!void {
1995
- if (nameListed(self.needed_record_writers.items, name)) return;
1996
- try self.needed_record_writers.append(self.arena, name);
1997
- try self.reference(name);
1998
- }
1999
-
2000
- fn needUnionWriter(self: *FacadeEmitter, name: []const u8) Error!void {
2001
- if (nameListed(self.needed_union_writers.items, name)) return;
2002
- try self.needed_union_writers.append(self.arena, name);
2003
- try self.reference(name);
2004
- }
2005
-
2006
- fn needUnionDecoder(self: *FacadeEmitter, name: []const u8) Error!void {
2007
- if (nameListed(self.needed_union_decoders.items, name)) return;
2008
- try self.needed_union_decoders.append(self.arena, name);
2009
- try self.reference(name);
2010
- }
2011
-
2012
- fn generatedTables(self: *FacadeEmitter) Error!void {
2013
- var emitted_header = false;
2014
- // Draining loop: a writer may need another writer or table.
2015
- var enum_at: usize = 0;
2016
- var enum_index_at: usize = 0;
2017
- var record_at: usize = 0;
2018
- var union_w_at: usize = 0;
2019
- var union_d_at: usize = 0;
2020
- while (enum_at < self.needed_enum_tables.items.len or
2021
- enum_index_at < self.needed_enum_indexes.items.len or
2022
- record_at < self.needed_record_writers.items.len or
2023
- union_w_at < self.needed_union_writers.items.len or
2024
- union_d_at < self.needed_union_decoders.items.len)
2025
- {
2026
- if (!emitted_header) {
2027
- emitted_header = true;
2028
- try self.raw(
2029
- \\
2030
- \\// ----------------------------------- generated tables and codecs
2031
- \\// Enum member tables (u32 member indices read back through them),
2032
- \\// canonical record/union writers, and standalone union decoders.
2033
- \\
2034
- );
2035
- }
2036
- while (enum_at < self.needed_enum_tables.items.len) : (enum_at += 1) {
2037
- try self.enumTable(self.needed_enum_tables.items[enum_at]);
2038
- }
2039
- while (enum_index_at < self.needed_enum_indexes.items.len) : (enum_index_at += 1) {
2040
- try self.enumIndexFn(self.needed_enum_indexes.items[enum_index_at]);
2041
- }
2042
- while (record_at < self.needed_record_writers.items.len) : (record_at += 1) {
2043
- try self.recordWriter(self.needed_record_writers.items[record_at]);
2044
- }
2045
- while (union_w_at < self.needed_union_writers.items.len) : (union_w_at += 1) {
2046
- try self.unionWriter(self.needed_union_writers.items[union_w_at]);
2047
- }
2048
- while (union_d_at < self.needed_union_decoders.items.len) : (union_d_at += 1) {
2049
- try self.unionDecoder(self.needed_union_decoders.items[union_d_at]);
2050
- }
2051
- }
2052
- if (self.needs_member_trap) {
2053
- self.use(.trap);
2054
- try self.raw(
2055
- \\
2056
- \\function nscfMember(enumName: string, member: number): never {
2057
- \\ nscfTrap("member index " + member + " does not name a " + enumName + " member — the host and this core disagree about the contract");
2058
- \\}
2059
- \\
2060
- );
2061
- }
2062
- }
2063
-
2064
- fn enumTable(self: *FacadeEmitter, name: []const u8) Error!void {
2065
- const entry = sidecar_mod.findEnum(self.sidecar.types, name).?;
2066
- try self.print("\nconst nscfMembers{s}: {s}[] = [", .{ name, name });
2067
- for (entry.members, 0..) |member, index| {
2068
- try self.print("{s}\"{s}\"", .{ if (index == 0) "" else ", ", try tsString(self.arena, member) });
2069
- }
2070
- try self.raw("];\n");
2071
- }
2072
-
2073
- fn enumIndexFn(self: *FacadeEmitter, name: []const u8) Error!void {
2074
- self.use(.trap);
2075
- try self.print(
2076
- \\
2077
- \\function nscfIndex{s}(value: {s}): number {{
2078
- \\ for (let i = 0; i < nscfMembers{s}.length; i++) {{
2079
- \\ if (nscfMembers{s}[i] === value) return i;
2080
- \\ }}
2081
- \\ nscfTrap("an enum slot carries an undeclared member — the author module and this generated module disagree");
2082
- \\}}
2083
- \\
2084
- , .{ name, name, name, name });
2085
- }
2086
-
2087
- /// Statements appending one value's canonical encoding to `sink`.
2088
- /// `container`/`member` name the slot for the attested integer
2089
- /// class; depth controls indentation and temp naming.
2090
- fn fieldWriteStatements(self: *FacadeEmitter, ref: TypeRef, expr: []const u8, container: []const u8, member: []const u8, depth: usize) Error!void {
2091
- const pad = try self.indentText(depth);
2092
- switch (ref) {
2093
- .bool => {
2094
- self.use(.w_bool);
2095
- try self.print("{s}nscfWBool(sink, {s});\n", .{ pad, expr });
2096
- },
2097
- .i64 => try self.print("{s}{s}(sink, {s});\n", .{ pad, self.intWriter(container, member), expr }),
2098
- .f64 => {
2099
- self.use(.w_f64);
2100
- try self.print("{s}nscfWF64(sink, {s});\n", .{ pad, expr });
2101
- },
2102
- .bytes => {
2103
- self.use(.w_bytes);
2104
- if (self.isThemeStateAccent(container, member)) {
2105
- // ThemeState.accent is author-facing `string` (the
2106
- // ergonomic "#rrggbb" API) but the core ABI's one text
2107
- // representation is bytes. The contract intentionally
2108
- // reflects strings as bytes; bridge this one exact
2109
- // launcher record at the generated boundary.
2110
- self.use(.utf8_text);
2111
- try self.print("{s}nscfWBytes(sink, nscfUtf8TextBytes({s}));\n", .{ pad, expr });
2112
- } else {
2113
- try self.print("{s}nscfWBytes(sink, {s});\n", .{ pad, expr });
2114
- }
2115
- },
2116
- .void => {},
2117
- .optional => |inner| {
2118
- self.use(.w_bool);
2119
- const temp = try std.fmt.allocPrint(self.arena, "nscfOpt{d}", .{self.temp_counter});
2120
- self.temp_counter += 1;
2121
- try self.print("{s}const {s} = {s};\n{s}if ({s} === null || {s} === undefined) {{\n{s} nscfWBool(sink, false);\n{s}}} else {{\n{s} nscfWBool(sink, true);\n", .{ pad, temp, expr, pad, temp, temp, pad, pad, pad });
2122
- try self.fieldWriteStatements(inner.*, temp, container, member, depth + 1);
2123
- try self.print("{s}}}\n", .{pad});
2124
- },
2125
- .slice => |elem| {
2126
- self.use(.w_u32);
2127
- const index = try std.fmt.allocPrint(self.arena, "nscfIdx{d}", .{self.temp_counter});
2128
- self.temp_counter += 1;
2129
- try self.print("{s}nscfWU32(sink, {s}.length);\n{s}for (let {s} = 0; {s} < {s}.length; {s}++) {{\n", .{ pad, expr, pad, index, index, expr, index });
2130
- try self.fieldWriteStatements(elem.*, try std.fmt.allocPrint(self.arena, "{s}[{s}]!", .{ expr, index }), container, member, depth + 1);
2131
- try self.print("{s}}}\n", .{pad});
2132
- },
2133
- .node, .value => |name| {
2134
- if (nameListed(self.flattened, name)) {
2135
- // A synthesized single-use record has no importable
2136
- // declaration: inline its fields at the site.
2137
- const record = sidecar_mod.findStruct(self.sidecar.types, name).?;
2138
- for (record.fields) |field| {
2139
- try self.fieldWriteStatements(field.type, try std.fmt.allocPrint(self.arena, "{s}.{s}", .{ expr, field.name }), name, field.name, depth);
2140
- }
2141
- } else {
2142
- try self.needRecordWriter(name);
2143
- try self.print("{s}nscfWrite{s}(sink, {s});\n", .{ pad, name, expr });
2144
- }
2145
- },
2146
- .enum_ref => |name| {
2147
- try self.needEnumIndex(name);
2148
- self.use(.w_u32);
2149
- try self.print("{s}nscfWU32(sink, nscfIndex{s}({s}));\n", .{ pad, name, expr });
2150
- },
2151
- .union_ref => |name| {
2152
- try self.needUnionWriter(name);
2153
- try self.print("{s}nscfWrite{s}(sink, {s});\n", .{ pad, name, expr });
2154
- },
2155
- }
2156
- }
2157
-
2158
- fn isThemeStateAccent(self: *FacadeEmitter, container: []const u8, member: []const u8) bool {
2159
- if (!std.mem.eql(u8, member, "accent")) return false;
2160
- for (self.sidecar.model_helpers) |helper| {
2161
- if (!std.mem.eql(u8, helper.name, "themeState")) continue;
2162
- return switch (helper.returns) {
2163
- .node, .value => |name| std.mem.eql(u8, name, container),
2164
- else => false,
2165
- };
2166
- }
2167
- return false;
2168
- }
2169
-
2170
- fn recordWriter(self: *FacadeEmitter, name: []const u8) Error!void {
2171
- const entry = sidecar_mod.findStruct(self.sidecar.types, name).?;
2172
- self.use(.sink);
2173
- self.temp_counter = 0;
2174
- try self.print("\nfunction nscfWrite{s}(sink: nscfSink, value: {s}): void {{\n", .{ name, name });
2175
- for (entry.fields) |field| {
2176
- try self.fieldWriteStatements(field.type, try tsAccess(self.arena, "value", field.name), name, field.name, 1);
2177
- }
2178
- try self.raw("}\n");
2179
- }
2180
-
2181
- fn unionWriter(self: *FacadeEmitter, name: []const u8) Error!void {
2182
- const entry = sidecar_mod.findUnion(self.sidecar.types, name).?;
2183
- self.use(.sink);
2184
- self.use(.w_u8);
2185
- self.use(.trap);
2186
- self.temp_counter = 0;
2187
- try self.print("\nfunction nscfWrite{s}(sink: nscfSink, value: {s}): void {{\n", .{ name, name });
2188
- for (entry.arms, 0..) |arm, index| {
2189
- try self.print(" if (value.kind === \"{s}\") {{\n nscfWU8(sink, {d});\n", .{ try tsString(self.arena, arm.name), index });
2190
- if (arm.payload != .void) {
2191
- if (self.synthesizedRecordOf(arm.payload, entry.name, arm.name)) |record| {
2192
- for (record.fields) |field| {
2193
- try self.fieldWriteStatements(field.type, try tsAccess(self.arena, "value", field.name), record.name, field.name, 2);
2194
- }
2195
- } else {
2196
- try self.fieldWriteStatements(arm.payload, try tsAccess(self.arena, "value", self.memberOf(arm.member)), entry.name, arm.name, 2);
2197
- }
2198
- }
2199
- try self.raw(" return;\n }\n");
2200
- }
2201
- try self.print(" nscfTrap(\"{s} carries an arm outside its declared union — the value and the contract disagree\");\n}}\n", .{try tsString(self.arena, name)});
2202
- }
2203
-
2204
- // -------------------------------------------------------- decoding
2205
-
2206
- /// Locals-and-construction decode of one record from `bytes` at a
2207
- /// running offset, committed as an arm of the message union.
2208
- /// `member` is null for a flattened (synthesized) record whose
2209
- /// fields construct beside `kind`, and the authored member spelling
2210
- /// otherwise.
2211
- fn recordDecodeCommit(self: *FacadeEmitter, record: *const sidecar_mod.Struct, arm_name: []const u8, member: ?[]const u8) Error!void {
2212
- var decode = RecordDecode{ .emitter = self, .buf = "fields", .indent = 2 };
2213
- try decode.run(record);
2214
- self.use(.assert_consumed);
2215
- try self.print(" nscfAssertConsumed(fields, {s});\n", .{decode.offsetText()});
2216
- const construction = try decode.constructionText(record);
2217
- const object = if (member) |m|
2218
- try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: {s} }}", .{ try tsString(self.arena, arm_name), try tsProp(self.arena, m), construction })
2219
- else blk: {
2220
- // Flattened: splice the record's fields beside kind.
2221
- const inner = construction[1 .. construction.len - 1];
2222
- break :blk try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\",{s}}}", .{ try tsString(self.arena, arm_name), inner });
2223
- };
2224
- if (decode.guards.items.len > 0) {
2225
- try self.print(" if ({s}) {{\n return nscfCommit(coreUpdate(nscfCommitted, {s}));\n }}\n nscfTrap(\"a decoded integer value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it\");\n", .{ decode.guards.items, object });
2226
- self.use(.trap);
2227
- } else {
2228
- try self.print(" return nscfCommit(coreUpdate(nscfCommitted, {s}));\n", .{object});
2229
- }
2230
- }
2231
-
2232
- /// A standalone decoder for a union payload arriving whole on a
2233
- /// dispatch entry (`[arm u8][payload]`, fully consumed).
2234
- fn unionDecoder(self: *FacadeEmitter, name: []const u8) Error!void {
2235
- const entry = sidecar_mod.findUnion(self.sidecar.types, name).?;
2236
- self.use(.trap);
2237
- self.use(.assert_consumed);
2238
- try self.print(
2239
- \\
2240
- \\function nscfDecode{s}(bytes: Uint8Array): {s} {{
2241
- \\ if (bytes.length === 0) {{
2242
- \\ nscfTrap("a dispatched union payload carries no arm byte — the host and this core disagree about the contract");
2243
- \\ }}
2244
- \\ const arm = bytes[0]!;
2245
- \\
2246
- , .{ name, name });
2247
- for (entry.arms, 0..) |arm, index| {
2248
- const kind = try tsString(self.arena, arm.name);
2249
- try self.print(" if (arm === {d}) {{\n", .{index});
2250
- if (arm.payload == .void) {
2251
- try self.print(" nscfAssertConsumed(bytes, 1);\n return {{ kind: \"{s}\" }};\n", .{kind});
2252
- } else {
2253
- var decode = RecordDecode{
2254
- .emitter = self,
2255
- .buf = "bytes",
2256
- .indent = 2,
2257
- .start = "1",
2258
- // Selection is a role of the COMPLETE text-input
2259
- // protocol, not an arm-name convention. Ordinary unions
2260
- // with a homonymous arm retain the normal exact-integer
2261
- // refusal instead of silently clamping their payload.
2262
- .saturating_selection = emit_mod.isTextInputUnion(self.sidecar, name) and std.mem.eql(u8, arm.name, "set_selection"),
2263
- };
2264
- var construction: []const u8 = undefined;
2265
- if (self.synthesizedRecordOf(arm.payload, entry.name, arm.name)) |record| {
2266
- try decode.run(record);
2267
- const inner = try decode.constructionText(record);
2268
- construction = try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\",{s}}}", .{ kind, inner[1 .. inner.len - 1] });
2269
- } else {
2270
- const field = sidecar_mod.Field{ .name = self.memberOf(arm.member), .type = arm.payload };
2271
- try decode.fieldLocal(field, entry.name, arm.name);
2272
- construction = try std.fmt.allocPrint(self.arena, "{{ kind: \"{s}\", {s}: {s} }}", .{ kind, try tsProp(self.arena, self.memberOf(arm.member)), decode.exprs.items[0].text });
2273
- }
2274
- try self.print(" nscfAssertConsumed(bytes, {s});\n", .{decode.offsetText()});
2275
- if (decode.guards.items.len > 0) {
2276
- try self.print(" if ({s}) {{\n return {s};\n }}\n nscfTrap(\"a decoded integer value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it\");\n", .{ decode.guards.items, construction });
2277
- } else {
2278
- try self.print(" return {s};\n", .{construction});
2279
- }
2280
- }
2281
- try self.raw(" }\n");
2282
- }
2283
- try self.raw(" nscfTrap(\"a dispatched union payload carries a union arm index past the declared arms — the host and this core disagree about the contract\");\n}\n");
2284
- }
2285
-
2286
- // -------------------------------------------------- codec section
2287
-
2288
- fn codecSection(self: *FacadeEmitter) Error!void {
2289
- // Emitted in fixed dependency order; each snippet appears only
2290
- // when generated code above reaches it.
2291
- if (self.used_codec.count() == 0) return;
2292
- try self.raw(
2293
- \\
2294
- \\// -------------------------------------------------- the wire codec
2295
- \\// The canonical value encoding (little-endian, headerless,
2296
- \\// schema-driven) plus the v3 command/subscription wire format the
2297
- \\// host consumes — byte-identical to what the transpiler lane emits,
2298
- \\// proven by the paired e2e batteries.
2299
- \\
2300
- );
2301
- if (self.used_codec.contains(.trap)) {
2302
- try self.raw(
2303
- \\
2304
- \\function nscfTrap(teaching: string): never {
2305
- \\ throw new Error(teaching);
2306
- \\}
2307
- \\
2308
- );
2309
- }
2310
- if (self.used_codec.contains(.read_u8)) {
2311
- try self.raw(
2312
- \\
2313
- \\function nscfReadU8(bytes: Uint8Array, at: number): number {
2314
- \\ if (at >= bytes.length) {
2315
- \\ nscfTrap("a dispatch payload ended mid-value — the host and this core disagree about a type's layout");
2316
- \\ }
2317
- \\ return bytes[at]!;
2318
- \\}
2319
- \\
2320
- );
2321
- }
2322
- if (self.used_codec.contains(.read_u32)) {
2323
- try self.raw(
2324
- \\
2325
- \\function nscfReadU32(bytes: Uint8Array, at: number): number {
2326
- \\ if (at + 4 > bytes.length) {
2327
- \\ nscfTrap("a dispatch payload ended mid-value — the host and this core disagree about a type's layout");
2328
- \\ }
2329
- \\ return bytes[at]! + bytes[at + 1]! * 256 + bytes[at + 2]! * 65536 + bytes[at + 3]! * 16777216;
2330
- \\}
2331
- \\
2332
- );
2333
- }
2334
- if (self.used_codec.contains(.read_f64)) {
2335
- try self.raw(
2336
- \\
2337
- \\function nscfReadF64(bytes: Uint8Array, at: number): number {
2338
- \\ if (at + 8 > bytes.length) {
2339
- \\ nscfTrap("a dispatch payload ended mid-value — the host and this core disagree about a type's layout");
2340
- \\ }
2341
- \\ const buf = Buffer.alloc(8);
2342
- \\ for (let i = 0; i < 8; i++) {
2343
- \\ buf[i] = bytes[at + i]!;
2344
- \\ }
2345
- \\ return buf.readDoubleLE(0);
2346
- \\}
2347
- \\
2348
- );
2349
- }
2350
- if (self.used_codec.contains(.read_i64)) {
2351
- try self.raw(
2352
- \\
2353
- \\function nscfReadI64(bytes: Uint8Array, at: number): number {
2354
- \\ const lo = nscfReadU32(bytes, at);
2355
- \\ const hi = nscfReadU32(bytes, at + 4);
2356
- \\ const hiSigned = hi >= 2147483648 ? hi - 4294967296 : hi;
2357
- \\ const value = hiSigned * 4294967296 + lo;
2358
- \\ if (value > 9007199254740991 || value < -9007199254740991) {
2359
- \\ nscfTrap("an integer payload is at or past 2^53 — the f64 number model has no honest value for it");
2360
- \\ }
2361
- \\ return value;
2362
- \\}
2363
- \\
2364
- );
2365
- }
2366
- if (self.used_codec.contains(.read_i64_saturating)) {
2367
- try self.raw(
2368
- \\
2369
- \\// An i64 payload saturated into the f64-exact window: values at or
2370
- \\// past +-2^53 clamp to +-(2^53 - 1). Selection offsets ride this
2371
- \\// reader because the host's select-all synthesizes the maxInt "to
2372
- \\// the end" sentinel, which every consumer snaps to the text's
2373
- \\// length.
2374
- \\function nscfReadI64Saturating(bytes: Uint8Array, at: number): number {
2375
- \\ const lo = nscfReadU32(bytes, at);
2376
- \\ const hi = nscfReadU32(bytes, at + 4);
2377
- \\ const hiSigned = hi >= 2147483648 ? hi - 4294967296 : hi;
2378
- \\ const value = hiSigned * 4294967296 + lo;
2379
- \\ if (value > 9007199254740991) return 9007199254740991;
2380
- \\ if (value < -9007199254740991) return -9007199254740991;
2381
- \\ return value;
2382
- \\}
2383
- \\
2384
- );
2385
- }
2386
- if (self.used_codec.contains(.read_u64_saturating)) {
2387
- try self.raw(
2388
- \\
2389
- \\// A u64 payload saturated into the nonnegative f64-exact window.
2390
- \\// Selection offsets use this twin when their sidecar slot is
2391
- \\// unsigned: maxInt(usize) is all-one bits, not signed -1.
2392
- \\function nscfReadU64Saturating(bytes: Uint8Array, at: number): number {
2393
- \\ const lo = nscfReadU32(bytes, at);
2394
- \\ const hi = nscfReadU32(bytes, at + 4);
2395
- \\ if (hi > 2097151) return 9007199254740991;
2396
- \\ return hi * 4294967296 + lo;
2397
- \\}
2398
- \\
2399
- );
2400
- }
2401
- if (self.used_codec.contains(.read_bool)) {
2402
- try self.raw(
2403
- \\
2404
- \\function nscfReadBool(bytes: Uint8Array, at: number): boolean {
2405
- \\ if (at >= bytes.length) {
2406
- \\ nscfTrap("a dispatch payload ended mid-value — the host and this core disagree about a type's layout");
2407
- \\ }
2408
- \\ const raw = bytes[at]!;
2409
- \\ if (raw > 1) {
2410
- \\ nscfTrap("a dispatch payload carries a boolean discriminant past 1 — the host and this core disagree about a type's layout");
2411
- \\ }
2412
- \\ return raw === 1;
2413
- \\}
2414
- \\
2415
- );
2416
- }
2417
- if (self.used_codec.contains(.read_bytes_body)) {
2418
- try self.raw(
2419
- \\
2420
- \\function nscfReadBytesBody(bytes: Uint8Array, at: number, len: number): Uint8Array {
2421
- \\ if (at + len > bytes.length) {
2422
- \\ nscfTrap("a dispatch payload ended mid-value — the host and this core disagree about a type's layout");
2423
- \\ }
2424
- \\ const out = new Uint8Array(len);
2425
- \\ for (let i = 0; i < len; i++) {
2426
- \\ out[i] = bytes[at + i]!;
2427
- \\ }
2428
- \\ return out;
2429
- \\}
2430
- \\
2431
- );
2432
- }
2433
- if (self.used_codec.contains(.assert_consumed)) {
2434
- try self.raw(
2435
- \\
2436
- \\function nscfAssertConsumed(bytes: Uint8Array, at: number): void {
2437
- \\ if (at !== bytes.length) {
2438
- \\ nscfTrap("a dispatch payload carries bytes past the decoded value — the host and this core disagree about a type's layout");
2439
- \\ }
2440
- \\}
2441
- \\
2442
- );
2443
- }
2444
- if (self.used_codec.contains(.trunc_toward_zero)) {
2445
- try self.raw(
2446
- \\
2447
- \\// An i64-classed slot narrows core-side by truncation toward zero
2448
- \\// (producers guarantee integer-classed values are exact below 2^53).
2449
- \\function nscfTruncTowardZero(value: number): number {
2450
- \\ return value < 0 ? -Math.floor(-value) : Math.floor(value);
2451
- \\}
2452
- \\
2453
- );
2454
- }
2455
- if (self.used_codec.contains(.sink)) {
2456
- try self.raw(
2457
- \\
2458
- \\// A sink is a plain byte accumulator; nscfFinish snapshots it.
2459
- \\type nscfSink = number[];
2460
- \\
2461
- \\function nscfNewSink(): nscfSink {
2462
- \\ return [];
2463
- \\}
2464
- \\
2465
- \\function nscfFinish(sink: nscfSink): Uint8Array {
2466
- \\ const out = new Uint8Array(sink.length);
2467
- \\ for (let i = 0; i < sink.length; i++) {
2468
- \\ out[i] = sink[i]!;
2469
- \\ }
2470
- \\ return out;
2471
- \\}
2472
- \\
2473
- );
2474
- }
2475
- if (self.used_codec.contains(.w_u8)) {
2476
- try self.raw(
2477
- \\
2478
- \\function nscfWU8(sink: nscfSink, value: number): void {
2479
- \\ sink.push(value);
2480
- \\}
2481
- \\
2482
- );
2483
- }
2484
- if (self.used_codec.contains(.w_u32)) {
2485
- try self.raw(
2486
- \\
2487
- \\function nscfWU32(sink: nscfSink, value: number): void {
2488
- \\ sink.push(value % 256);
2489
- \\ sink.push(Math.floor(value / 256) % 256);
2490
- \\ sink.push(Math.floor(value / 65536) % 256);
2491
- \\ sink.push(Math.floor(value / 16777216) % 256);
2492
- \\}
2493
- \\
2494
- );
2495
- }
2496
- if (self.used_codec.contains(.w_f64)) {
2497
- try self.raw(
2498
- \\
2499
- \\function nscfWF64(sink: nscfSink, value: number): void {
2500
- \\ const buf = Buffer.alloc(8);
2501
- \\ buf.writeDoubleLE(value, 0);
2502
- \\ for (let i = 0; i < 8; i++) {
2503
- \\ sink.push(buf[i]!);
2504
- \\ }
2505
- \\}
2506
- \\
2507
- );
2508
- }
2509
- if (self.used_codec.contains(.w_i64)) {
2510
- try self.raw(
2511
- \\
2512
- \\// Two's-complement i64, exact for every integer within +-(2^53 - 1).
2513
- \\function nscfWI64(sink: nscfSink, value: number): void {
2514
- \\ if (value > 9007199254740991 || value < -9007199254740991 || value !== nscfTruncTowardZero(value)) {
2515
- \\ nscfTrap("an integer slot carries a non-integer or out-of-range value — the i64 encoding has no honest bytes for it");
2516
- \\ }
2517
- \\ const hi = Math.floor(value / 4294967296);
2518
- \\ const lo = value - hi * 4294967296;
2519
- \\ const hiWire = hi < 0 ? hi + 4294967296 : hi;
2520
- \\ nscfWU32(sink, lo);
2521
- \\ nscfWU32(sink, hiWire);
2522
- \\}
2523
- \\
2524
- );
2525
- }
2526
- if (self.used_codec.contains(.w_u64)) {
2527
- try self.raw(
2528
- \\
2529
- \\// The unsigned twin for u64-attested slots: 8-byte unsigned LE,
2530
- \\// refusing negatives (a negative value has no honest unsigned
2531
- \\// bytes).
2532
- \\function nscfWU64(sink: nscfSink, value: number): void {
2533
- \\ if (value > 9007199254740991 || value < 0 || value !== nscfTruncTowardZero(value)) {
2534
- \\ nscfTrap("an unsigned integer slot carries a non-integer, negative, or out-of-range value — the u64 encoding has no honest bytes for it");
2535
- \\ }
2536
- \\ const hi = Math.floor(value / 4294967296);
2537
- \\ const lo = value - hi * 4294967296;
2538
- \\ nscfWU32(sink, lo);
2539
- \\ nscfWU32(sink, hi);
2540
- \\}
2541
- \\
2542
- );
2543
- }
2544
- if (self.used_codec.contains(.w_bool)) {
2545
- try self.raw(
2546
- \\
2547
- \\function nscfWBool(sink: nscfSink, value: boolean): void {
2548
- \\ sink.push(value ? 1 : 0);
2549
- \\}
2550
- \\
2551
- );
2552
- }
2553
- if (self.used_codec.contains(.w_bytes)) {
2554
- try self.raw(
2555
- \\
2556
- \\// A u32-length-prefixed bytes value (the canonical bytes encoding,
2557
- \\// and the wire format's long-bytes field).
2558
- \\function nscfWBytes(sink: nscfSink, bytes: Uint8Array): void {
2559
- \\ nscfWU32(sink, bytes.length);
2560
- \\ for (let i = 0; i < bytes.length; i++) {
2561
- \\ sink.push(bytes[i]!);
2562
- \\ }
2563
- \\}
2564
- \\
2565
- );
2566
- }
2567
- if (self.used_codec.contains(.short_text)) {
2568
- try self.raw(
2569
- \\
2570
- \\function nscfTextBytes(text: string): Uint8Array {
2571
- \\ const out = new Uint8Array(text.length);
2572
- \\ for (let i = 0; i < text.length; i++) {
2573
- \\ out[i] = text.charCodeAt(i);
2574
- \\ }
2575
- \\ return out;
2576
- \\}
2577
- \\
2578
- \\// A u8-length-prefixed short text field (names, keys, labels).
2579
- \\function nscfWShortText(sink: nscfSink, text: string): void {
2580
- \\ const bytes = nscfTextBytes(text);
2581
- \\ if (bytes.length > 255) {
2582
- \\ nscfTrap("a command name or key is over 255 bytes — the wire's short-text fields cannot carry it");
2583
- \\ }
2584
- \\ sink.push(bytes.length);
2585
- \\ for (let i = 0; i < bytes.length; i++) {
2586
- \\ sink.push(bytes[i]!);
2587
- \\ }
2588
- \\}
2589
- \\
2590
- );
2591
- }
2592
- if (self.used_codec.contains(.utf8_text)) {
2593
- try self.raw(
2594
- \\
2595
- \\// Store keys are ordinary UTF-8 text, not the ASCII-only
2596
- \\// short names used by command routing. This mirrors the SDK's
2597
- \\// utf8Bytes intrinsic, including U+FFFD for lone surrogates.
2598
- \\function nscfUtf8TextBytes(text: string): Uint8Array {
2599
- \\ let byteLength = 0;
2600
- \\ for (let i = 0; i < text.length; i++) {
2601
- \\ const code = text.charCodeAt(i);
2602
- \\ if (code <= 0x7f) byteLength += 1;
2603
- \\ else if (code <= 0x7ff) byteLength += 2;
2604
- \\ else if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {
2605
- \\ const next = text.charCodeAt(i + 1);
2606
- \\ if (next >= 0xdc00 && next <= 0xdfff) {
2607
- \\ byteLength += 4;
2608
- \\ i += 1;
2609
- \\ } else byteLength += 3;
2610
- \\ } else byteLength += 3;
2611
- \\ }
2612
- \\ const out = new Uint8Array(byteLength);
2613
- \\ let at = 0;
2614
- \\ for (let i = 0; i < text.length; i++) {
2615
- \\ let code = text.charCodeAt(i);
2616
- \\ if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {
2617
- \\ const next = text.charCodeAt(i + 1);
2618
- \\ if (next >= 0xdc00 && next <= 0xdfff) {
2619
- \\ code = 0x10000 + ((code - 0xd800) << 10) + (next - 0xdc00);
2620
- \\ i += 1;
2621
- \\ } else code = 0xfffd;
2622
- \\ } else if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd;
2623
- \\ if (code <= 0x7f) {
2624
- \\ out[at] = code;
2625
- \\ at += 1;
2626
- \\ } else if (code <= 0x7ff) {
2627
- \\ out[at] = 0xc0 | (code >> 6);
2628
- \\ out[at + 1] = 0x80 | (code & 0x3f);
2629
- \\ at += 2;
2630
- \\ } else if (code <= 0xffff) {
2631
- \\ out[at] = 0xe0 | (code >> 12);
2632
- \\ out[at + 1] = 0x80 | ((code >> 6) & 0x3f);
2633
- \\ out[at + 2] = 0x80 | (code & 0x3f);
2634
- \\ at += 3;
2635
- \\ } else {
2636
- \\ out[at] = 0xf0 | (code >> 18);
2637
- \\ out[at + 1] = 0x80 | ((code >> 12) & 0x3f);
2638
- \\ out[at + 2] = 0x80 | ((code >> 6) & 0x3f);
2639
- \\ out[at + 3] = 0x80 | (code & 0x3f);
2640
- \\ at += 4;
2641
- \\ }
2642
- \\ }
2643
- \\ return out;
2644
- \\}
2645
- \\
2646
- );
2647
- }
2648
- if (self.used_codec.contains(.ascii_string)) {
2649
- try self.raw(
2650
- \\
2651
- \\function nscfAsciiString(bytes: Uint8Array): string {
2652
- \\ let out = "";
2653
- \\ for (let i = 0; i < bytes.length; i++) out = out + String.fromCharCode(bytes[i]!);
2654
- \\ return out;
2655
- \\}
2656
- \\
2657
- );
2658
- }
2659
- if (self.used_codec.contains(.enum_index)) {
2660
- try self.raw(
2661
- \\
2662
- \\function nscfMemberIndex(members: string[], value: string, what: string): number {
2663
- \\ for (let i = 0; i < members.length; i++) {
2664
- \\ if (members[i] === value) return i;
2665
- \\ }
2666
- \\ nscfTrap("a command carries an unknown " + what + " member — the SDK and this generated module disagree");
2667
- \\}
2668
- \\
2669
- );
2670
- }
2671
- if (self.used_codec.contains(.cmd_encoder)) {
2672
- try self.cmdEncoder();
2673
- }
2674
- if (self.used_codec.contains(.sub_encoder)) {
2675
- try self.subEncoder();
2676
- }
2677
- }
2678
-
2679
- /// The v3 command wire encoder — byte-for-byte the layouts the
2680
- /// host's rt builds (wire.ts's encodeCmd, per-module).
2681
- fn cmdEncoder(self: *FacadeEmitter) Error!void {
2682
- const msg = self.sidecar.msg.name;
2683
- try self.print(
2684
- \\
2685
- \\// ---------------------------------------------------- the cmd wire
2686
- \\// Encoder for the inert Cmd data the author's update returns —
2687
- \\// byte-for-byte the layouts the host's command decoder expects
2688
- \\// (cmd_format_version 7). nscfTagOf maps a Msg arm name onto its
2689
- \\// declaration-order wire tag.
2690
- \\
2691
- \\const nscfFetchMethods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
2692
- \\const nscfAudioVerbs = ["pause", "resume", "stop", "seek", "volume"];
2693
- \\const nscfAudioCaptureSources = ["microphone", "system"];
2694
- \\const nscfVideoVerbs = ["play", "pause", "stop", "seek", "volume", "muted", "loop"];
2695
- \\
2696
- \\// Preserve the store err route for dynamic invalid limits. Writing a
2697
- \\// fractional or out-of-u32 number directly into the byte sink would
2698
- \\// truncate/wrap it into a different, potentially valid request. 257
2699
- \\// is the host's stable over-bound sentinel (the public maximum is 256).
2700
- \\function nscfStoreScanLimit(value: number): number {{
2701
- \\ return Number.isInteger(value) && value >= 0 && value <= 256 ? value : 257;
2702
- \\}}
2703
- \\
2704
- \\function nscfWDbValue(sink: nscfSink, value: unknown): void {{
2705
- \\ if (value === null) {{
2706
- \\ nscfWU8(sink, 0);
2707
- \\ }} else if (typeof value === "number") {{
2708
- \\ nscfWU8(sink, 1);
2709
- \\ nscfWF64(sink, value);
2710
- \\ }} else if (typeof value === "string") {{
2711
- \\ nscfWU8(sink, 2);
2712
- \\ nscfWBytes(sink, nscfUtf8TextBytes(value));
2713
- \\ }} else if (typeof value === "boolean") {{
2714
- \\ nscfWU8(sink, 4);
2715
- \\ nscfWU8(sink, value ? 1 : 0);
2716
- \\ }} else if (value instanceof Uint8Array) {{
2717
- \\ nscfWU8(sink, 3);
2718
- \\ nscfWBytes(sink, value);
2719
- \\ }} else {{
2720
- \\ nscfWU8(sink, 2);
2721
- \\ const bytes = (value as nscfDbText).bytes;
2722
- \\ nscfWU32(sink, bytes.length);
2723
- \\ for (let i = 0; i < bytes.length; i++) sink.push(bytes[i]!);
2724
- \\ }}
2725
- \\}}
2726
- \\
2727
- \\function nscfEncodeCmd(sink: nscfSink, cmd: nscfCmd<{s}>): void {{
2728
- \\
2729
- , .{msg});
2730
- try self.raw(
2731
- \\ switch (cmd.op) {
2732
- \\ case "none":
2733
- \\ return;
2734
- \\ case "persist":
2735
- \\ nscfWU8(sink, 0x01);
2736
- \\ return;
2737
- \\ case "now":
2738
- \\ nscfWU8(sink, 0x02);
2739
- \\ nscfWU8(sink, nscfTagOf(cmd.msgKind));
2740
- \\ return;
2741
- \\ case "host": {
2742
- \\ nscfWU8(sink, 0x03);
2743
- \\ nscfWShortText(sink, cmd.name);
2744
- \\ if (cmd.args.length > 255) {
2745
- \\ nscfTrap("a host command carries over 255 scalar args — the wire's arg block cannot carry it");
2746
- \\ }
2747
- \\ nscfWU8(sink, cmd.args.length);
2748
- \\ for (let i = 0; i < cmd.args.length; i++) {
2749
- \\ nscfWF64(sink, cmd.args[i]!);
2750
- \\ }
2751
- \\ return;
2752
- \\ }
2753
- \\ case "host_bytes":
2754
- \\ nscfWU8(sink, 0x04);
2755
- \\ nscfWShortText(sink, cmd.name);
2756
- \\ nscfWBytes(sink, cmd.payload);
2757
- \\ return;
2758
- \\ case "request":
2759
- \\ nscfWU8(sink, 0x05);
2760
- \\ nscfWShortText(sink, cmd.name);
2761
- \\ nscfWShortText(sink, cmd.key);
2762
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2763
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2764
- \\ nscfWU8(sink, cmd.typedService ? 1 : 0);
2765
- \\ nscfWBytes(sink, cmd.payload);
2766
- \\ return;
2767
- \\ case "service_stream_request":
2768
- \\ nscfWU8(sink, 0x28);
2769
- \\ nscfWF64(sink, cmd.channelKey);
2770
- \\ nscfWU8(sink, nscfTagOf(cmd.eventKind));
2771
- \\ nscfWU8(sink, cmd.maxPending);
2772
- \\ nscfWShortText(sink, cmd.name);
2773
- \\ nscfWShortText(sink, cmd.key);
2774
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2775
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2776
- \\ nscfWBytes(sink, cmd.payload);
2777
- \\ return;
2778
- \\ case "cancel":
2779
- \\ nscfWU8(sink, 0x06);
2780
- \\ nscfWShortText(sink, cmd.key);
2781
- \\ return;
2782
- \\ case "read_file":
2783
- \\ nscfWU8(sink, 0x07);
2784
- \\ nscfWShortText(sink, cmd.key);
2785
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2786
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2787
- \\ nscfWBytes(sink, cmd.path);
2788
- \\ return;
2789
- \\ case "write_file":
2790
- \\ nscfWU8(sink, 0x08);
2791
- \\ nscfWShortText(sink, cmd.key);
2792
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2793
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2794
- \\ nscfWBytes(sink, cmd.path);
2795
- \\ nscfWBytes(sink, cmd.bytes);
2796
- \\ return;
2797
- \\ case "append_file":
2798
- \\ nscfWU8(sink, 0x2b);
2799
- \\ nscfWShortText(sink, cmd.key);
2800
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2801
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2802
- \\ nscfWBytes(sink, cmd.path);
2803
- \\ nscfWBytes(sink, cmd.bytes);
2804
- \\ return;
2805
- \\ case "stat_file":
2806
- \\ nscfWU8(sink, 0x2c);
2807
- \\ nscfWShortText(sink, cmd.key);
2808
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2809
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2810
- \\ nscfWBytes(sink, cmd.path);
2811
- \\ return;
2812
- \\ case "delete_file":
2813
- \\ nscfWU8(sink, 0x32);
2814
- \\ nscfWShortText(sink, cmd.key);
2815
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2816
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2817
- \\ nscfWBytes(sink, cmd.path);
2818
- \\ return;
2819
- \\ case "read_file_stream":
2820
- \\ nscfWU8(sink, 0x2d);
2821
- \\ nscfWShortText(sink, cmd.key);
2822
- \\ nscfWU8(sink, nscfTagOf(cmd.chunkKind));
2823
- \\ nscfWU8(sink, nscfTagOf(cmd.doneKind));
2824
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2825
- \\ nscfWBytes(sink, cmd.path);
2826
- \\ return;
2827
- \\ case "write_file_stream":
2828
- \\ nscfWU8(sink, 0x2e);
2829
- \\ nscfWShortText(sink, cmd.key);
2830
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2831
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2832
- \\ nscfWBytes(sink, cmd.path);
2833
- \\ return;
2834
- \\ case "write_file_chunk":
2835
- \\ nscfWU8(sink, 0x2f);
2836
- \\ nscfWShortText(sink, cmd.key);
2837
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2838
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2839
- \\ nscfWBytes(sink, cmd.bytes);
2840
- \\ return;
2841
- \\ case "write_file_close":
2842
- \\ nscfWU8(sink, 0x30);
2843
- \\ nscfWShortText(sink, cmd.key);
2844
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2845
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2846
- \\ return;
2847
- \\ case "fetch": {
2848
- \\ nscfWU8(sink, 0x09);
2849
- \\ nscfWShortText(sink, cmd.key);
2850
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2851
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2852
- \\ nscfWU8(sink, nscfMemberIndex(nscfFetchMethods, cmd.method, "fetch method"));
2853
- \\ nscfWU32(sink, cmd.timeoutMs);
2854
- \\ nscfWBytes(sink, cmd.url);
2855
- \\ if (cmd.headers.length > 255) {
2856
- \\ nscfTrap("a fetch carries over 255 headers — the wire's header block cannot carry it");
2857
- \\ }
2858
- \\ nscfWU8(sink, cmd.headers.length);
2859
- \\ for (let i = 0; i < cmd.headers.length; i++) {
2860
- \\ const header = cmd.headers[i]!;
2861
- \\ nscfWShortText(sink, header.name);
2862
- \\ const value = header.value;
2863
- \\ nscfWBytes(sink, typeof value === "string" ? nscfTextBytes(value) : value);
2864
- \\ }
2865
- \\ nscfWBytes(sink, cmd.body);
2866
- \\ return;
2867
- \\ }
2868
- \\ case "clip_write":
2869
- \\ nscfWU8(sink, 0x0a);
2870
- \\ nscfWBytes(sink, cmd.bytes);
2871
- \\ return;
2872
- \\ case "clip_read":
2873
- \\ nscfWU8(sink, 0x0b);
2874
- \\ nscfWShortText(sink, cmd.key);
2875
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2876
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2877
- \\ return;
2878
- \\ case "delay":
2879
- \\ nscfWU8(sink, 0x0c);
2880
- \\ nscfWShortText(sink, cmd.key);
2881
- \\ nscfWF64(sink, cmd.afterMs);
2882
- \\ nscfWU8(sink, nscfTagOf(cmd.msgKind));
2883
- \\ return;
2884
- \\ case "spawn": {
2885
- \\ nscfWU8(sink, 0x0d);
2886
- \\ nscfWShortText(sink, cmd.key);
2887
- \\ nscfWU8(sink, cmd.lineKind === "" ? 0xff : nscfTagOf(cmd.lineKind));
2888
- \\ nscfWU8(sink, nscfTagOf(cmd.exitKind));
2889
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2890
- \\ nscfWU8(sink, cmd.collect ? 1 : 0);
2891
- \\ if (cmd.argv.length === 0 || cmd.argv.length > 255) {
2892
- \\ nscfTrap("a spawn carries no argv or over 255 argv entries — the wire's argv block cannot carry it");
2893
- \\ }
2894
- \\ nscfWU8(sink, cmd.argv.length);
2895
- \\ for (let i = 0; i < cmd.argv.length; i++) {
2896
- \\ nscfWBytes(sink, cmd.argv[i]!);
2897
- \\ }
2898
- \\ nscfWBytes(sink, cmd.stdin);
2899
- \\ return;
2900
- \\ }
2901
- \\ case "audio_play":
2902
- \\ nscfWU8(sink, 0x0e);
2903
- \\ nscfWShortText(sink, cmd.key);
2904
- \\ nscfWU8(sink, nscfTagOf(cmd.eventKind));
2905
- \\ nscfWBytes(sink, cmd.path);
2906
- \\ nscfWBytes(sink, cmd.url);
2907
- \\ nscfWBytes(sink, cmd.cachePath);
2908
- \\ nscfWF64(sink, cmd.expectedBytes);
2909
- \\ return;
2910
- \\ case "audio_ctl":
2911
- \\ nscfWU8(sink, 0x0f);
2912
- \\ nscfWShortText(sink, cmd.key);
2913
- \\ nscfWU8(sink, nscfMemberIndex(nscfAudioVerbs, cmd.verb, "audio verb"));
2914
- \\ nscfWF64(sink, cmd.value);
2915
- \\ return;
2916
- \\ case "window_show":
2917
- \\ nscfWU8(sink, 0x10);
2918
- \\ nscfWShortText(sink, cmd.label);
2919
- \\ return;
2920
- \\ case "window_hide":
2921
- \\ nscfWU8(sink, 0x21);
2922
- \\ nscfWShortText(sink, cmd.label);
2923
- \\ return;
2924
- \\ case "dock_presence":
2925
- \\ nscfWU8(sink, 0x22);
2926
- \\ nscfWU8(sink, cmd.visible ? 1 : 0);
2927
- \\ return;
2928
- \\ case "store_set":
2929
- \\ nscfWU8(sink, 0x23);
2930
- \\ nscfWShortText(sink, cmd.key);
2931
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2932
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2933
- \\ nscfWU32(sink, 0);
2934
- \\ nscfWBytes(sink, nscfUtf8TextBytes(cmd.storeKey));
2935
- \\ nscfWBytes(sink, cmd.bytes);
2936
- \\ return;
2937
- \\ case "store_get":
2938
- \\ case "store_delete":
2939
- \\ nscfWU8(sink, cmd.op === "store_get" ? 0x24 : 0x25);
2940
- \\ nscfWShortText(sink, cmd.key);
2941
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2942
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2943
- \\ nscfWU32(sink, 0);
2944
- \\ nscfWBytes(sink, nscfUtf8TextBytes(cmd.storeKey));
2945
- \\ return;
2946
- \\ case "store_scan":
2947
- \\ nscfWU8(sink, 0x26);
2948
- \\ nscfWShortText(sink, cmd.key);
2949
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2950
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2951
- \\ nscfWU32(sink, 0);
2952
- \\ nscfWBytes(sink, nscfUtf8TextBytes(cmd.prefix));
2953
- \\ nscfWU32(sink, nscfStoreScanLimit(cmd.limit));
2954
- \\ nscfWBytes(sink, typeof cmd.after === "string" ? nscfUtf8TextBytes(cmd.after) : cmd.after);
2955
- \\ return;
2956
- \\ case "store_set_many":
2957
- \\ nscfWU8(sink, 0x27);
2958
- \\ nscfWShortText(sink, cmd.key);
2959
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2960
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2961
- \\ nscfWU32(sink, 0);
2962
- \\ nscfWU32(sink, cmd.entries.length);
2963
- \\ for (let i = 0; i < cmd.entries.length; i++) {
2964
- \\ nscfWBytes(sink, nscfUtf8TextBytes(cmd.entries[i]![0]));
2965
- \\ nscfWBytes(sink, cmd.entries[i]![1]);
2966
- \\ }
2967
- \\ return;
2968
- \\ case "db_query":
2969
- \\ nscfWU8(sink, 0x29);
2970
- \\ nscfWShortText(sink, cmd.key);
2971
- \\ nscfWU8(sink, nscfTagOf(cmd.pageKind));
2972
- \\ nscfWU8(sink, nscfTagOf(cmd.doneKind));
2973
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2974
- \\ nscfWBytes(sink, nscfUtf8TextBytes(cmd.sql));
2975
- \\ nscfWU32(sink, cmd.params.length);
2976
- \\ for (let i = 0; i < cmd.params.length; i++) nscfWDbValue(sink, cmd.params[i]!);
2977
- \\ return;
2978
- \\ case "db_exec":
2979
- \\ nscfWU8(sink, 0x2a);
2980
- \\ nscfWShortText(sink, cmd.key);
2981
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
2982
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
2983
- \\ nscfWU32(sink, cmd.statements.length);
2984
- \\ for (let i = 0; i < cmd.statements.length; i++) {
2985
- \\ const statement = cmd.statements[i]!;
2986
- \\ nscfWBytes(sink, nscfUtf8TextBytes(statement[0]));
2987
- \\ nscfWU32(sink, statement[1].length);
2988
- \\ for (let j = 0; j < statement[1].length; j++) nscfWDbValue(sink, statement[1][j]!);
2989
- \\ }
2990
- \\ return;
2991
- \\ case "quit_app":
2992
- \\ nscfWU8(sink, 0x11);
2993
- \\ return;
2994
- \\ case "image_load":
2995
- \\ nscfWU8(sink, 0x12);
2996
- \\ nscfWF64(sink, cmd.id);
2997
- \\ nscfWU8(sink, nscfTagOf(cmd.eventKind));
2998
- \\ nscfWBytes(sink, cmd.path);
2999
- \\ nscfWBytes(sink, cmd.url);
3000
- \\ nscfWBytes(sink, cmd.cachePath);
3001
- \\ nscfWF64(sink, cmd.expectedBytes);
3002
- \\ return;
3003
- \\ case "image_cancel":
3004
- \\ nscfWU8(sink, 0x13);
3005
- \\ nscfWF64(sink, cmd.id);
3006
- \\ return;
3007
- \\ case "image_unregister":
3008
- \\ nscfWU8(sink, 0x14);
3009
- \\ nscfWF64(sink, cmd.id);
3010
- \\ return;
3011
- \\ case "channel_open":
3012
- \\ nscfWU8(sink, 0x15);
3013
- \\ nscfWF64(sink, cmd.key);
3014
- \\ nscfWU8(sink, nscfTagOf(cmd.eventKind));
3015
- \\ nscfWU8(sink, cmd.maxPending);
3016
- \\ return;
3017
- \\ case "channel_close":
3018
- \\ nscfWU8(sink, 0x16);
3019
- \\ nscfWF64(sink, cmd.key);
3020
- \\ return;
3021
- \\ case "video_load": {
3022
- \\ nscfWU8(sink, 0x17);
3023
- \\ nscfWShortText(sink, cmd.key);
3024
- \\ nscfWU8(sink, nscfTagOf(cmd.eventKind));
3025
- \\ nscfWF64(sink, cmd.surface);
3026
- \\ nscfWBytes(sink, cmd.path);
3027
- \\ nscfWBytes(sink, cmd.url);
3028
- \\ // Wire flags: bit0 = autoplay, bit1 = loop, bit2 = muted.
3029
- \\ let flags = 0;
3030
- \\ if (cmd.autoplay) flags = flags + 1;
3031
- \\ if (cmd.loop) flags = flags + 2;
3032
- \\ if (cmd.muted) flags = flags + 4;
3033
- \\ nscfWU8(sink, flags);
3034
- \\ return;
3035
- \\ }
3036
- \\ case "video_ctl":
3037
- \\ nscfWU8(sink, 0x18);
3038
- \\ nscfWShortText(sink, cmd.key);
3039
- \\ nscfWU8(sink, nscfMemberIndex(nscfVideoVerbs, cmd.verb, "video verb"));
3040
- \\ nscfWF64(sink, cmd.value);
3041
- \\ return;
3042
- \\ case "pty_spawn": {
3043
- \\ nscfWU8(sink, 0x19);
3044
- \\ nscfWShortText(sink, cmd.key);
3045
- \\ nscfWU8(sink, nscfTagOf(cmd.eventKind));
3046
- \\ nscfWF64(sink, cmd.cols);
3047
- \\ nscfWF64(sink, cmd.rows);
3048
- \\ nscfWShortText(sink, cmd.term);
3049
- \\ if (cmd.argv.length === 0 || cmd.argv.length > 255) {
3050
- \\ nscfTrap("a pty spawn carries no argv or over 255 argv entries — the wire's argv block cannot carry it");
3051
- \\ }
3052
- \\ nscfWU8(sink, cmd.argv.length);
3053
- \\ for (let i = 0; i < cmd.argv.length; i++) {
3054
- \\ nscfWBytes(sink, cmd.argv[i]!);
3055
- \\ }
3056
- \\ return;
3057
- \\ }
3058
- \\ case "pty_write":
3059
- \\ nscfWU8(sink, 0x1a);
3060
- \\ nscfWShortText(sink, cmd.key);
3061
- \\ nscfWBytes(sink, cmd.bytes);
3062
- \\ return;
3063
- \\ case "pty_resize":
3064
- \\ nscfWU8(sink, 0x1b);
3065
- \\ nscfWShortText(sink, cmd.key);
3066
- \\ nscfWF64(sink, cmd.cols);
3067
- \\ nscfWF64(sink, cmd.rows);
3068
- \\ return;
3069
- \\ case "pty_kill":
3070
- \\ nscfWU8(sink, 0x1c);
3071
- \\ nscfWShortText(sink, cmd.key);
3072
- \\ return;
3073
- \\ case "show_notification":
3074
- \\ if (cmd.id.length === 0 && cmd.actionLabel.length === 0 && cmd.actionCommand.length === 0) {
3075
- \\ nscfWU8(sink, 0x1d);
3076
- \\ nscfWBytes(sink, cmd.title);
3077
- \\ nscfWBytes(sink, cmd.subtitle);
3078
- \\ nscfWBytes(sink, cmd.body);
3079
- \\ } else {
3080
- \\ nscfWU8(sink, 0x31);
3081
- \\ nscfWBytes(sink, cmd.id);
3082
- \\ nscfWBytes(sink, cmd.title);
3083
- \\ nscfWBytes(sink, cmd.subtitle);
3084
- \\ nscfWBytes(sink, cmd.body);
3085
- \\ nscfWBytes(sink, cmd.actionLabel);
3086
- \\ nscfWBytes(sink, cmd.actionCommand);
3087
- \\ }
3088
- \\ return;
3089
- \\ case "audio_capture_start":
3090
- \\ nscfWU8(sink, 0x1e);
3091
- \\ nscfWF64(sink, cmd.key);
3092
- \\ nscfWU8(sink, nscfMemberIndex(nscfAudioCaptureSources, cmd.source, "audio capture source"));
3093
- \\ nscfWU32(sink, cmd.sampleRate);
3094
- \\ nscfWU8(sink, cmd.channels);
3095
- \\ nscfWU8(sink, nscfTagOf(cmd.eventKind));
3096
- \\ return;
3097
- \\ case "audio_capture_stop":
3098
- \\ nscfWU8(sink, 0x1f);
3099
- \\ nscfWF64(sink, cmd.key);
3100
- \\ return;
3101
- \\ case "fetch_stream": {
3102
- \\ nscfWU8(sink, 0x20);
3103
- \\ nscfWShortText(sink, cmd.key);
3104
- \\ nscfWU8(sink, nscfTagOf(cmd.lineKind));
3105
- \\ nscfWU8(sink, nscfTagOf(cmd.okKind));
3106
- \\ nscfWU8(sink, nscfTagOf(cmd.errKind));
3107
- \\ nscfWU8(sink, nscfMemberIndex(nscfFetchMethods, cmd.method, "fetch method"));
3108
- \\ nscfWU32(sink, cmd.timeoutMs);
3109
- \\ nscfWU32(sink, cmd.maxLineBytes);
3110
- \\ nscfWBytes(sink, cmd.url);
3111
- \\ if (cmd.headers.length > 255) {
3112
- \\ nscfTrap("a fetch carries over 255 headers — the wire's header block cannot carry it");
3113
- \\ }
3114
- \\ nscfWU8(sink, cmd.headers.length);
3115
- \\ for (let i = 0; i < cmd.headers.length; i++) {
3116
- \\ const header = cmd.headers[i]!;
3117
- \\ nscfWShortText(sink, header.name);
3118
- \\ const value = header.value;
3119
- \\ nscfWBytes(sink, typeof value === "string" ? nscfTextBytes(value) : value);
3120
- \\ }
3121
- \\ nscfWBytes(sink, cmd.body);
3122
- \\ return;
3123
- \\ }
3124
- \\ case "batch":
3125
- \\ for (let i = 0; i < cmd.cmds.length; i++) {
3126
- \\ nscfEncodeCmd(sink, cmd.cmds[i]!);
3127
- \\ }
3128
- \\ return;
3129
- \\ }
3130
- \\}
3131
- \\
3132
- );
3133
- try self.print(
3134
- \\
3135
- \\function nscfCmdBytes(cmd: nscfCmd<{s}>): Uint8Array {{
3136
- \\ const sink = nscfNewSink();
3137
- \\ nscfEncodeCmd(sink, cmd);
3138
- \\ return nscfFinish(sink);
3139
- \\}}
3140
- \\
3141
- , .{msg});
3142
- }
3143
-
3144
- fn subEncoder(self: *FacadeEmitter) Error!void {
3145
- const msg = self.sidecar.msg.name;
3146
- try self.print(
3147
- \\
3148
- \\// The v3 subscription wire: repeating timers and build-time
3149
- \\// checked live relational queries.
3150
- \\function nscfWSubDbValue(sink: nscfSink, value: unknown): void {{
3151
- \\ if (value === null) {{
3152
- \\ nscfWU8(sink, 0);
3153
- \\ }} else if (typeof value === "number") {{
3154
- \\ nscfWU8(sink, 1);
3155
- \\ nscfWF64(sink, value);
3156
- \\ }} else if (typeof value === "string") {{
3157
- \\ nscfWU8(sink, 2);
3158
- \\ nscfWBytes(sink, nscfUtf8TextBytes(value));
3159
- \\ }} else if (typeof value === "boolean") {{
3160
- \\ nscfWU8(sink, 4);
3161
- \\ nscfWU8(sink, value ? 1 : 0);
3162
- \\ }} else if (value instanceof Uint8Array) {{
3163
- \\ nscfWU8(sink, 3);
3164
- \\ nscfWBytes(sink, value);
3165
- \\ }} else {{
3166
- \\ nscfWU8(sink, 2);
3167
- \\ const bytes = (value as nscfDbText).bytes;
3168
- \\ nscfWU32(sink, bytes.length);
3169
- \\ for (let i = 0; i < bytes.length; i++) sink.push(bytes[i]!);
3170
- \\ }}
3171
- \\}}
3172
- \\
3173
- \\function nscfEncodeSub(sink: nscfSink, sub: nscfSub<{s}>): void {{
3174
- \\ switch (sub.op) {{
3175
- \\ case "none":
3176
- \\ return;
3177
- \\ case "timer":
3178
- \\ nscfWU8(sink, 0x01);
3179
- \\ nscfWShortText(sink, sub.key);
3180
- \\ nscfWF64(sink, sub.everyMs);
3181
- \\ nscfWU8(sink, nscfTagOf(sub.msgKind));
3182
- \\ return;
3183
- \\ case "db_live":
3184
- \\ nscfWU8(sink, 0x02);
3185
- \\ nscfWShortText(sink, sub.key);
3186
- \\ nscfWU8(sink, nscfTagOf(sub.pageKind));
3187
- \\ nscfWU8(sink, nscfTagOf(sub.doneKind));
3188
- \\ nscfWU8(sink, nscfTagOf(sub.errKind));
3189
- \\ nscfWBytes(sink, nscfUtf8TextBytes(sub.sql));
3190
- \\ nscfWU32(sink, sub.params.length);
3191
- \\ for (let i = 0; i < sub.params.length; i++) nscfWSubDbValue(sink, sub.params[i]!);
3192
- \\ nscfWU32(sink, sub.tables.length);
3193
- \\ for (let i = 0; i < sub.tables.length; i++) nscfWShortText(sink, sub.tables[i]!);
3194
- \\ return;
3195
- \\ case "batch":
3196
- \\ for (let i = 0; i < sub.subs.length; i++) {{
3197
- \\ nscfEncodeSub(sink, sub.subs[i]!);
3198
- \\ }}
3199
- \\ return;
3200
- \\ }}
3201
- \\}}
3202
- \\
3203
- \\function nscfSubBytes(sub: nscfSub<{s}>): Uint8Array {{
3204
- \\ const sink = nscfNewSink();
3205
- \\ nscfEncodeSub(sink, sub);
3206
- \\ return nscfFinish(sink);
3207
- \\}}
3208
- \\
3209
- , .{ msg, msg });
3210
- }
3211
-
3212
- // ---------------------------------------------------- spellings
3213
-
3214
- /// The one TypeRef-to-TypeScript-spelling authority.
3215
- fn spellRef(self: *FacadeEmitter, ref: TypeRef) Error![]const u8 {
3216
- return switch (ref) {
3217
- .bool => "boolean",
3218
- .f64, .i64 => "number",
3219
- .bytes => "Uint8Array",
3220
- .void => "void",
3221
- .optional => |inner| try std.fmt.allocPrint(self.arena, "{s} | null", .{try self.spellRef(inner.*)}),
3222
- .slice => |elem| blk: {
3223
- // Composite element spellings parenthesize: `number |
3224
- // null[]` would type the null as the array.
3225
- const spelled = try self.spellRef(elem.*);
3226
- if (std.mem.indexOfAny(u8, spelled, " |") != null) {
3227
- break :blk try std.fmt.allocPrint(self.arena, "({s})[]", .{spelled});
3228
- }
3229
- break :blk try std.fmt.allocPrint(self.arena, "{s}[]", .{spelled});
3230
- },
3231
- // Reference storage is a layout fact of the host mirror;
3232
- // TypeScript sees the record value either way.
3233
- .node, .value, .enum_ref, .union_ref => |name| blk: {
3234
- try self.reference(name);
3235
- break :blk name;
3236
- },
3237
- };
3238
- }
3239
-
3240
- fn indentText(self: *FacadeEmitter, depth: usize) Error![]const u8 {
3241
- const text = try self.arena.alloc(u8, depth * 2);
3242
- @memset(text, ' ');
3243
- return text;
3244
- }
3245
-
3246
- /// The struct behind a synthesized, inlined record reference at
3247
- /// this site — the shape that flattens beside `kind`. VALUE
3248
- /// references only: flattening is a by-value layout, so a
3249
- /// node-stored payload keeps its named declaration however its
3250
- /// name is spelled.
3251
- fn synthesizedRecordOf(self: *FacadeEmitter, ref: TypeRef, container: []const u8, member: []const u8) ?*const sidecar_mod.Struct {
3252
- const name = switch (ref) {
3253
- .value => |n| n,
3254
- else => return null,
3255
- };
3256
- if (!emit_mod.isSynthesizedRef(container, member, name) or !nameListed(self.inlined, name)) return null;
3257
- const record = sidecar_mod.findStruct(self.sidecar.types, name) orelse return null;
3258
- if (record.origin != null) return null;
3259
- return record;
3260
- }
3261
-
3262
- /// The synthesized single-use records this projection flattens into
3263
- /// their one arm literal: neither a re-export nor a named writer
3264
- /// ever spells them (the compiler re-derives the same names from
3265
- /// the inline arms).
3266
- fn flattenedTableNames(self: *FacadeEmitter) Error![]const []const u8 {
3267
- var names: std.ArrayListUnmanaged([]const u8) = .empty;
3268
- for (self.sidecar.msg.arms) |arm| {
3269
- switch (arm.payload) {
3270
- .record => {
3271
- if (self.synthesizedRecordOf(recordPayloadRef(arm.payload), self.sidecar.msg.name, arm.name)) |record| {
3272
- try names.append(self.arena, record.name);
3273
- }
3274
- },
3275
- else => {},
3276
- }
3277
- }
3278
- for (self.sidecar.types.unions) |entry| {
3279
- for (entry.arms) |arm| {
3280
- if (arm.payload == .void) continue;
3281
- if (self.synthesizedRecordOf(arm.payload, entry.name, arm.name)) |record| {
3282
- try names.append(self.arena, record.name);
3283
- }
3284
- }
3285
- }
3286
- return names.items;
3287
- }
3288
-
3289
- /// The record names the contract stores BY REFERENCE anywhere.
3290
- fn nodeStoredTableNames(self: *FacadeEmitter) Error![]const []const u8 {
3291
- var names: std.ArrayListUnmanaged([]const u8) = .empty;
3292
- // The model root is reference-stored by contract (no explicit
3293
- // reference spells it), so it seeds the set: a `value`
3294
- // reference to the root elsewhere is the mixed-storage case and
3295
- // refuses like any other.
3296
- try names.append(self.arena, self.sidecar.model);
3297
- for (self.sidecar.types.structs) |entry| {
3298
- for (entry.fields) |field| {
3299
- try noteNodeRefs(&names, self.arena, field.type);
3300
- }
3301
- }
3302
- for (self.sidecar.types.unions) |entry| {
3303
- for (entry.arms) |arm| {
3304
- try noteNodeRefs(&names, self.arena, arm.payload);
3305
- }
3306
- }
3307
- for (self.sidecar.model_helpers) |helper| {
3308
- try noteNodeRefs(&names, self.arena, helper.returns);
3309
- for (helper.params) |param| try noteNodeRefs(&names, self.arena, param);
3310
- }
3311
- for (self.sidecar.msg.arms) |arm| {
3312
- switch (arm.payload) {
3313
- .scalar => |ref| try noteNodeRefs(&names, self.arena, ref),
3314
- else => {},
3315
- }
3316
- }
3317
- return names.items;
3318
- }
3319
- };
3320
-
3321
- /// Locals-then-construction decode of canonical bytes. The emitted mutable
3322
- /// cursor advances in the lexical branch that consumes each value, so
3323
- /// nonterminal optionals and variable-width composites compose naturally.
3324
- /// Integer locals join the nearest construction guard and state wholeness
3325
- /// with Math.trunc at the guarded write.
3326
- const RecordDecode = struct {
3327
- emitter: *FacadeEmitter,
3328
- buf: []const u8,
3329
- indent: usize,
3330
- start: []const u8 = "0",
3331
- saturating_selection: bool = false,
3332
- local_count: usize = 0,
3333
- cursor_started: bool = false,
3334
- guards: std.ArrayListUnmanaged(u8) = .empty,
3335
- exprs: std.ArrayListUnmanaged(struct { name: []const u8, text: []const u8 }) = .empty,
3336
-
3337
- const Self = @This();
3338
-
3339
- fn arena(self: *Self) std.mem.Allocator {
3340
- return self.emitter.arena;
3341
- }
3342
-
3343
- fn offsetText(_: *Self) []const u8 {
3344
- return "nscfAt";
3345
- }
3346
-
3347
- fn nextLocal(self: *Self) Error![]const u8 {
3348
- const name = try std.fmt.allocPrint(self.arena(), "nscfV{d}", .{self.local_count});
3349
- self.local_count += 1;
3350
- return name;
3351
- }
3352
-
3353
- fn line(self: *Self, comptime fmt: []const u8, args: anytype) Error!void {
3354
- const pad = try self.emitter.indentText(self.indent);
3355
- try self.emitter.print("{s}", .{pad});
3356
- try self.emitter.print(fmt, args);
3357
- }
3358
-
3359
- fn ensureCursor(self: *Self) Error!void {
3360
- if (self.cursor_started) return;
3361
- self.cursor_started = true;
3362
- try self.line("let nscfAt = {s};\n", .{self.start});
3363
- }
3364
-
3365
- fn advance(self: *Self, amount: []const u8) Error!void {
3366
- try self.line("nscfAt += {s};\n", .{amount});
3367
- }
3368
-
3369
- fn advanceFixed(self: *Self, amount: usize) Error!void {
3370
- try self.advance(try std.fmt.allocPrint(self.arena(), "{d}", .{amount}));
3371
- }
3372
-
3373
- fn addGuard(self: *Self, guards: *std.ArrayListUnmanaged(u8), local: []const u8, class: IntegerClass) Error!void {
3374
- if (guards.items.len > 0) try guards.appendSlice(self.arena(), " && ");
3375
- try guards.appendSlice(self.arena(), try std.fmt.allocPrint(self.arena(), "{s} >= {s} && {s} <= {s}", .{ local, integerLowerBound(class), local, max_safe }));
3376
- }
3377
-
3378
- fn guardedStatement(self: *Self, guards: []const u8, statement: []const u8) Error!void {
3379
- if (guards.len == 0) {
3380
- try self.line("{s}\n", .{statement});
3381
- return;
3382
- }
3383
- try self.line("if ({s}) {{\n", .{guards});
3384
- self.indent += 1;
3385
- try self.line("{s}\n", .{statement});
3386
- self.indent -= 1;
3387
- try self.line("}} else {{\n", .{});
3388
- self.indent += 1;
3389
- try self.line("nscfTrap(\"a decoded integer value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it\");\n", .{});
3390
- self.indent -= 1;
3391
- try self.line("}}\n", .{});
3392
- self.emitter.use(.trap);
3393
- }
3394
-
3395
- fn run(self: *Self, record: *const sidecar_mod.Struct) Error!void {
3396
- try self.ensureCursor();
3397
- for (record.fields) |field| try self.fieldLocal(field, record.name, field.name);
3398
- }
3399
-
3400
- fn fieldLocal(self: *Self, field: sidecar_mod.Field, container: []const u8, member: []const u8) Error!void {
3401
- try self.ensureCursor();
3402
- const text = try self.decodeRef(field.type, field.name, container, member, &self.guards);
3403
- try self.exprs.append(self.arena(), .{ .name = field.name, .text = text });
3404
- }
3405
-
3406
- fn decodeRecord(self: *Self, record: *const sidecar_mod.Struct, guards: *std.ArrayListUnmanaged(u8)) Error![]const u8 {
3407
- var parts: std.ArrayListUnmanaged(u8) = .empty;
3408
- for (record.fields, 0..) |field, index| {
3409
- const text = try self.decodeRef(field.type, field.name, record.name, field.name, guards);
3410
- if (index > 0) try parts.appendSlice(self.arena(), ", ");
3411
- try parts.appendSlice(self.arena(), try std.fmt.allocPrint(self.arena(), "{s}: {s}", .{ try tsProp(self.arena(), field.name), text }));
3412
- }
3413
- return try std.fmt.allocPrint(self.arena(), "{{ {s} }}", .{parts.items});
3414
- }
3415
-
3416
- fn decodeUnion(self: *Self, name: []const u8) Error![]const u8 {
3417
- const em = self.emitter;
3418
- const entry = sidecar_mod.findUnion(em.sidecar.types, name) orelse {
3419
- em.diags.flag("types", "\"{s}\" names no tabled union", .{name});
3420
- return "undefined";
3421
- };
3422
- em.use(.read_u8);
3423
- const tag = try self.nextLocal();
3424
- try self.line("const {s} = nscfReadU8({s}, nscfAt);\n", .{ tag, self.buf });
3425
- try self.advanceFixed(1);
3426
- const local = try self.nextLocal();
3427
- try self.line("let {s}: {s};\n", .{ local, name });
3428
- for (entry.arms, 0..) |arm, index| {
3429
- try self.line("{s}if ({s} === {d}) {{\n", .{ if (index == 0) "" else "else ", tag, index });
3430
- self.indent += 1;
3431
- var arm_guards: std.ArrayListUnmanaged(u8) = .empty;
3432
- const object = if (arm.payload == .void)
3433
- try std.fmt.allocPrint(self.arena(), "{{ kind: \"{s}\" }}", .{try tsString(self.arena(), arm.name)})
3434
- else if (em.synthesizedRecordOf(arm.payload, entry.name, arm.name)) |record| blk: {
3435
- const inner = try self.decodeRecord(record, &arm_guards);
3436
- break :blk try std.fmt.allocPrint(self.arena(), "{{ kind: \"{s}\",{s}}}", .{ try tsString(self.arena(), arm.name), inner[1 .. inner.len - 1] });
3437
- } else blk: {
3438
- const value = try self.decodeRef(arm.payload, em.memberOf(arm.member), entry.name, arm.name, &arm_guards);
3439
- break :blk try std.fmt.allocPrint(self.arena(), "{{ kind: \"{s}\", {s}: {s} }}", .{ try tsString(self.arena(), arm.name), try tsProp(self.arena(), em.memberOf(arm.member)), value });
3440
- };
3441
- try self.guardedStatement(arm_guards.items, try std.fmt.allocPrint(self.arena(), "{s} = {s};", .{ local, object }));
3442
- self.indent -= 1;
3443
- try self.line("}}\n", .{});
3444
- }
3445
- try self.line("else {{\n", .{});
3446
- self.indent += 1;
3447
- try self.line("nscfTrap(\"a dispatched union payload carries a union arm index past the declared arms — the host and this core disagree about the contract\");\n", .{});
3448
- self.indent -= 1;
3449
- try self.line("}}\n", .{});
3450
- em.use(.trap);
3451
- return local;
3452
- }
3453
-
3454
- fn decodeRef(self: *Self, ref: TypeRef, field_name: []const u8, container: []const u8, member: []const u8, guards: *std.ArrayListUnmanaged(u8)) Error![]const u8 {
3455
- const em = self.emitter;
3456
- return switch (ref) {
3457
- .f64 => blk: {
3458
- em.use(.read_f64);
3459
- const local = try self.nextLocal();
3460
- try self.line("const {s} = nscfReadF64({s}, nscfAt);\n", .{ local, self.buf });
3461
- try self.advanceFixed(8);
3462
- break :blk local;
3463
- },
3464
- .i64 => blk: {
3465
- const class = em.slotClass(container, member) orelse .i64;
3466
- const selection_field = std.mem.eql(u8, field_name, "anchor") or std.mem.eql(u8, field_name, "focus");
3467
- const reader: Codec = if (self.saturating_selection and selection_field)
3468
- if (class == .u64) .read_u64_saturating else .read_i64_saturating
3469
- else
3470
- .read_i64;
3471
- em.use(reader);
3472
- const local = try self.nextLocal();
3473
- const reader_name = switch (reader) {
3474
- .read_i64 => "nscfReadI64",
3475
- .read_i64_saturating => "nscfReadI64Saturating",
3476
- .read_u64_saturating => "nscfReadU64Saturating",
3477
- else => unreachable,
3478
- };
3479
- try self.line("const {s} = {s}({s}, nscfAt);\n", .{ local, reader_name, self.buf });
3480
- try self.advanceFixed(8);
3481
- try self.addGuard(guards, local, class);
3482
- break :blk try std.fmt.allocPrint(self.arena(), "Math.trunc({s})", .{local});
3483
- },
3484
- .bool => blk: {
3485
- em.use(.read_bool);
3486
- const local = try self.nextLocal();
3487
- try self.line("const {s} = nscfReadBool({s}, nscfAt);\n", .{ local, self.buf });
3488
- try self.advanceFixed(1);
3489
- break :blk local;
3490
- },
3491
- .bytes => blk: {
3492
- em.use(.read_u32);
3493
- em.use(.read_bytes_body);
3494
- const len_local = try self.nextLocal();
3495
- try self.line("const {s} = nscfReadU32({s}, nscfAt);\n", .{ len_local, self.buf });
3496
- try self.advanceFixed(4);
3497
- const local = try self.nextLocal();
3498
- try self.line("const {s} = nscfReadBytesBody({s}, nscfAt, {s});\n", .{ local, self.buf, len_local });
3499
- try self.advance(len_local);
3500
- break :blk local;
3501
- },
3502
- .enum_ref => |name| blk: {
3503
- em.use(.read_u32);
3504
- try em.needEnumTable(name);
3505
- em.needs_member_trap = true;
3506
- const local = try self.nextLocal();
3507
- try self.line("const {s} = nscfReadU32({s}, nscfAt);\n", .{ local, self.buf });
3508
- try self.line("if ({s} >= nscfMembers{s}.length) nscfMember(\"{s}\", {s});\n", .{ local, name, try tsString(self.arena(), name), local });
3509
- try self.advanceFixed(4);
3510
- break :blk try std.fmt.allocPrint(self.arena(), "nscfMembers{s}[{s}]!", .{ name, local });
3511
- },
3512
- .node, .value => |name| blk: {
3513
- const nested = sidecar_mod.findStruct(em.sidecar.types, name) orelse {
3514
- em.diags.flag("types", "\"{s}\" names no tabled record", .{name});
3515
- break :blk "undefined";
3516
- };
3517
- break :blk try self.decodeRecord(nested, guards);
3518
- },
3519
- .optional => |inner| blk: {
3520
- em.use(.read_bool);
3521
- const present = try self.nextLocal();
3522
- try self.line("const {s} = nscfReadBool({s}, nscfAt);\n", .{ present, self.buf });
3523
- try self.advanceFixed(1);
3524
- const local = try self.nextLocal();
3525
- try self.line("let {s}: {s} | null = null;\n", .{ local, try em.spellRef(inner.*) });
3526
- try self.line("if ({s}) {{\n", .{present});
3527
- self.indent += 1;
3528
- var inner_guards: std.ArrayListUnmanaged(u8) = .empty;
3529
- const value = try self.decodeRef(inner.*, field_name, container, member, &inner_guards);
3530
- try self.guardedStatement(inner_guards.items, try std.fmt.allocPrint(self.arena(), "{s} = {s};", .{ local, value }));
3531
- self.indent -= 1;
3532
- try self.line("}}\n", .{});
3533
- break :blk local;
3534
- },
3535
- .slice => |elem| blk: {
3536
- em.use(.read_u32);
3537
- const len_local = try self.nextLocal();
3538
- try self.line("const {s} = nscfReadU32({s}, nscfAt);\n", .{ len_local, self.buf });
3539
- try self.advanceFixed(4);
3540
- const local = try self.nextLocal();
3541
- try self.line("const {s}: {s} = [];\n", .{ local, try em.spellRef(ref) });
3542
- const index = try self.nextLocal();
3543
- try self.line("for (let {s} = 0; {s} < {s}; {s}++) {{\n", .{ index, index, len_local, index });
3544
- self.indent += 1;
3545
- var elem_guards: std.ArrayListUnmanaged(u8) = .empty;
3546
- const value = try self.decodeRef(elem.*, field_name, container, member, &elem_guards);
3547
- try self.guardedStatement(elem_guards.items, try std.fmt.allocPrint(self.arena(), "{s}.push({s});", .{ local, value }));
3548
- self.indent -= 1;
3549
- try self.line("}}\n", .{});
3550
- break :blk local;
3551
- },
3552
- .union_ref => |name| try self.decodeUnion(name),
3553
- .void => blk: {
3554
- em.diags.flag("types", "a record field cannot carry void", .{});
3555
- break :blk "undefined";
3556
- },
3557
- };
3558
- }
3559
-
3560
- fn constructionText(self: *Self, record: *const sidecar_mod.Struct) Error![]const u8 {
3561
- _ = record;
3562
- var out: std.ArrayListUnmanaged(u8) = .empty;
3563
- try out.appendSlice(self.arena(), "{ ");
3564
- for (self.exprs.items, 0..) |entry, index| {
3565
- if (index > 0) try out.appendSlice(self.arena(), ", ");
3566
- try out.appendSlice(self.arena(), try std.fmt.allocPrint(self.arena(), "{s}: {s}", .{ try tsProp(self.arena(), entry.name), entry.text }));
3567
- }
3568
- try out.appendSlice(self.arena(), " }");
3569
- return out.items;
3570
- }
3571
- };
3572
-
3573
- /// The scroll entry's parameter feeding an authored scroll field.
3574
- fn scrollParamFor(field_name: []const u8) ?[]const u8 {
3575
- for (scroll_state_fields_ts, 0..) |candidate, index| {
3576
- if (std.mem.eql(u8, candidate, field_name) or std.mem.eql(u8, scroll_state_fields_canvas[index], field_name)) return candidate;
3577
- }
3578
- return null;
3579
- }
3580
-
3581
- /// Collect the record names `ref` reaches through NODE references,
3582
- /// walking the optional/slice wrappers (a node behind an optional or a
3583
- /// sequence is node storage all the same).
3584
- fn noteNodeRefs(names: *std.ArrayListUnmanaged([]const u8), arena: std.mem.Allocator, ref: TypeRef) error{OutOfMemory}!void {
3585
- switch (ref) {
3586
- .node => |name| {
3587
- if (!nameListed(names.items, name)) try names.append(arena, name);
3588
- },
3589
- .optional => |inner| try noteNodeRefs(names, arena, inner.*),
3590
- .slice => |elem| try noteNodeRefs(names, arena, elem.*),
3591
- else => {},
3592
- }
3593
- }
3594
-
3595
- /// The VALUE-reference twin of noteNodeRefs.
3596
- fn noteValueRefs(names: *std.ArrayListUnmanaged([]const u8), arena: std.mem.Allocator, ref: TypeRef) error{OutOfMemory}!void {
3597
- switch (ref) {
3598
- .value => |name| {
3599
- if (!nameListed(names.items, name)) try names.append(arena, name);
3600
- },
3601
- .optional => |inner| try noteValueRefs(names, arena, inner.*),
3602
- .slice => |elem| try noteValueRefs(names, arena, elem.*),
3603
- else => {},
3604
- }
3605
- }
3606
-
3607
- /// A msg record payload as the TypeRef shape synthesizedRecordOf reads.
3608
- fn recordPayloadRef(payload: sidecar_mod.Payload) TypeRef {
3609
- return switch (payload) {
3610
- .record => |name| .{ .value = name },
3611
- else => unreachable,
3612
- };
3613
- }
3614
-
3615
- /// The numeric ABI class of either spelling the sidecar accepts for a
3616
- /// one-number message payload. Dedicated descriptors are what current
3617
- /// extractors emit; scalar descriptors remain a valid format-1 alias and
3618
- /// must reach the same facade entry as the generated mirror.
3619
- fn payloadNumberClass(payload: sidecar_mod.Payload) ?sidecar_mod.NumberClass {
3620
- return switch (payload) {
3621
- .number => |class| class,
3622
- .scalar => |ref| switch (ref) {
3623
- .f64 => .f64,
3624
- .i64 => .i64,
3625
- else => null,
3626
- },
3627
- else => null,
3628
- };
3629
- }
3630
-
3631
- fn pathText(arena: std.mem.Allocator, comptime fmt: []const u8, args: anytype) []const u8 {
3632
- return std.fmt.allocPrint(arena, fmt, args) catch "";
3633
- }
3634
-
3635
- fn nameListed(names: []const []const u8, name: []const u8) bool {
3636
- for (names) |candidate| {
3637
- if (std.mem.eql(u8, candidate, name)) return true;
3638
- }
3639
- return false;
3640
- }
3641
-
3642
- fn commentText(arena: std.mem.Allocator, text: []const u8) error{OutOfMemory}![]const u8 {
3643
- const out = try arena.dupe(u8, text);
3644
- for (out) |*char| {
3645
- if (char.* < 0x20 or char.* == 0x7f) char.* = ' ';
3646
- }
3647
- // U+2028/U+2029 are line terminators to a TypeScript scanner: blank
3648
- // their UTF-8 bytes so provenance text cannot end the comment early.
3649
- var index: usize = 0;
3650
- while (index + 2 < out.len) : (index += 1) {
3651
- if (out[index] == 0xe2 and out[index + 1] == 0x80 and (out[index + 2] == 0xa8 or out[index + 2] == 0xa9)) {
3652
- out[index] = ' ';
3653
- out[index + 1] = ' ';
3654
- out[index + 2] = ' ';
3655
- }
3656
- }
3657
- return out;
3658
- }
3659
-
3660
- /// Escape a name into a TS double-quoted string literal (arm names ride
3661
- /// string literals in the kind-tagged union). The scanner's line
3662
- /// terminators are LF, CR, LS (U+2028), and PS (U+2029) — all escaped
3663
- /// here (NEL U+0085 is ordinary text to the scanner); quotes and
3664
- /// backslashes escape byte-for-byte.
3665
- fn tsString(arena: std.mem.Allocator, text: []const u8) error{OutOfMemory}![]const u8 {
3666
- var out: std.ArrayListUnmanaged(u8) = .empty;
3667
- var index: usize = 0;
3668
- while (index < text.len) {
3669
- const char = text[index];
3670
- if (char == 0xe2 and index + 2 < text.len and text[index + 1] == 0x80 and
3671
- (text[index + 2] == 0xa8 or text[index + 2] == 0xa9))
3672
- {
3673
- const escape: []const u8 = if (text[index + 2] == 0xa8) "\\u2028" else "\\u2029";
3674
- try out.appendSlice(arena, escape);
3675
- index += 3;
3676
- continue;
3677
- }
3678
- switch (char) {
3679
- '"' => try out.appendSlice(arena, "\\\""),
3680
- '\\' => try out.appendSlice(arena, "\\\\"),
3681
- '\n' => try out.appendSlice(arena, "\\n"),
3682
- '\r' => try out.appendSlice(arena, "\\r"),
3683
- '\t' => try out.appendSlice(arena, "\\t"),
3684
- else => try out.append(arena, char),
3685
- }
3686
- index += 1;
3687
- }
3688
- return out.items;
3689
- }
3690
-
3691
- /// A property spelling: plain identifiers stay bare (reserved words
3692
- /// are legal property names); anything else quotes.
3693
- fn tsProp(arena: std.mem.Allocator, name: []const u8) error{OutOfMemory}![]const u8 {
3694
- if (isIdentifierFragment(name) and name.len > 0 and !(name[0] >= '0' and name[0] <= '9')) {
3695
- return name;
3696
- }
3697
- return std.fmt.allocPrint(arena, "\"{s}\"", .{try tsString(arena, name)});
3698
- }
3699
-
3700
- /// A property ACCESS: dot for plain spellings, brackets otherwise.
3701
- fn tsAccess(arena: std.mem.Allocator, base: []const u8, name: []const u8) error{OutOfMemory}![]const u8 {
3702
- if (isIdentifierFragment(name) and name.len > 0 and !(name[0] >= '0' and name[0] <= '9')) {
3703
- return std.fmt.allocPrint(arena, "{s}.{s}", .{ base, name });
3704
- }
3705
- return std.fmt.allocPrint(arena, "{s}[\"{s}\"]", .{ base, try tsString(arena, name) });
3706
- }
3707
-
3708
- /// Why a name cannot survive the WHOLE pipeline, or null when it can:
3709
- /// the shared identifier charset (letters, digits, underscore), a
3710
- /// non-digit start, not the discard spelling, and no keyword or
3711
- /// primitive-type name of either language.
3712
- const NameRole = enum {
3713
- declaration,
3714
- member,
3715
- };
3716
-
3717
- fn pipelineIdentifierIssue(name: []const u8, role: NameRole) ?[]const u8 {
3718
- if (name.len == 0) return "is empty";
3719
- if (std.mem.eql(u8, name, "_")) return "is the discard spelling in the compiled module";
3720
- if (name[0] >= '0' and name[0] <= '9') return "starts with a digit";
3721
- for (name) |char| {
3722
- const ok = (char >= 'a' and char <= 'z') or (char >= 'A' and char <= 'Z') or
3723
- (char >= '0' and char <= '9') or char == '_';
3724
- if (!ok) return "uses characters outside the compiled module's identifier set (letters, digits, underscore)";
3725
- }
3726
- if (std.zig.Token.keywords.has(name)) return "is a keyword in the compiled module";
3727
- if (std.zig.isPrimitive(name)) return "is a primitive type name in the compiled module";
3728
- if (role == .declaration) {
3729
- for (ts_reserved_words) |word| {
3730
- if (std.mem.eql(u8, name, word)) return "is a reserved word in TypeScript";
3731
- }
3732
- }
3733
- return null;
3734
- }
3735
-
3736
- fn isIdentifierFragment(name: []const u8) bool {
3737
- if (name.len == 0) return false;
3738
- for (name) |char| {
3739
- const ok = (char >= 'a' and char <= 'z') or (char >= 'A' and char <= 'Z') or
3740
- (char >= '0' and char <= '9') or char == '_' or char == '$';
3741
- if (!ok) return false;
3742
- }
3743
- return true;
3744
- }
3745
-
3746
- fn isTsIdentifier(name: []const u8) bool {
3747
- if (name.len == 0) return false;
3748
- if (name[0] >= '0' and name[0] <= '9') return false;
3749
- for (name) |char| {
3750
- const ok = (char >= 'a' and char <= 'z') or (char >= 'A' and char <= 'Z') or
3751
- (char >= '0' and char <= '9') or char == '_' or char == '$';
3752
- if (!ok) return false;
3753
- }
3754
- for (ts_reserved_words) |word| {
3755
- if (std.mem.eql(u8, name, word)) return false;
3756
- }
3757
- return true;
3758
- }
3759
-
3760
- // --------------------------------------------------------------- tests
3761
-
3762
- const testing = std.testing;
3763
-
3764
22
  /// Most facade tests perturb sidecar_mod's deliberately LEGACY minimal
3765
23
  /// fixture. Upgrade its two authored facts here so unrelated refusal tests
3766
24
  /// exercise the current facade boundary; the dedicated legacy test below
@@ -3862,7 +120,7 @@ test "facade emission is deterministic and carries the adapter surface" {
3862
120
  try testing.expect(std.mem.indexOf(u8, first, "export const viewUnbound = [\n \"label_set\",\n];") != null);
3863
121
  // Unwired channels stay out of the module.
3864
122
  try testing.expect(std.mem.indexOf(u8, first, "abi_frame_msg") == null);
3865
- try testing.expect(std.mem.indexOf(u8, first, "nscfPackMsg") == null);
123
+ try testing.expect(std.mem.indexOf(u8, first, "function nscfPackMsg") != null);
3866
124
  // Facade-only types, tag constants, and SDK effect imports all live in
3867
125
  // the lowercase reserved namespace, so authored capitalized names cannot
3868
126
  // collide with them.