@momo-kits/native-kits 0.169.13-beta.3 → 0.169.13-beta.3-debug

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 (164) hide show
  1. package/build.gradle.kts +11 -0
  2. package/compose/build.gradle.kts +202 -0
  3. package/compose/compose.podspec +47 -0
  4. package/compose/src/androidMain/kotlin/vn/momo/kits/const/HostFont.android.kt +19 -0
  5. package/compose/src/androidMain/kotlin/vn/momo/kits/navigation/ScrollToTop.android.kt +6 -0
  6. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/BackGesture.android.kt +12 -0
  7. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/OsFontScale.android.kt +7 -0
  8. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/Platform.android.kt +154 -0
  9. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/ReduceMotion.android.kt +17 -0
  10. package/compose/src/androidMain/kotlin/vn/momo/kits/platform/ReservedRegions.android.kt +6 -0
  11. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiActionsTest.kt +647 -0
  12. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiExprTest.kt +1411 -0
  13. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiHostTest.kt +130 -0
  14. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiKitArgsTest.kt +524 -0
  15. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiKitNodesTest.kt +559 -0
  16. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRenderPlanTest.kt +741 -0
  17. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRenderReuseTest.kt +221 -0
  18. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRendererPropsTest.kt +270 -0
  19. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiStylePlanTest.kt +849 -0
  20. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiStyleTest.kt +212 -0
  21. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiTrackingTest.kt +239 -0
  22. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiViewTest.kt +252 -0
  23. package/compose/src/commonMain/kotlin/vn/momo/kits/application/Context.kt +110 -0
  24. package/compose/src/commonMain/kotlin/vn/momo/kits/application/DesignSystemKits.kt +61 -0
  25. package/compose/src/commonMain/kotlin/vn/momo/kits/application/LiteScreen.kt +1067 -0
  26. package/compose/src/commonMain/kotlin/vn/momo/kits/application/Localize.kt +268 -0
  27. package/compose/src/commonMain/kotlin/vn/momo/kits/application/WidgetContainer.kt +56 -0
  28. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Avatar.kt +157 -0
  29. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Badge.kt +81 -0
  30. package/compose/src/commonMain/kotlin/vn/momo/kits/components/BadgeDot.kt +32 -0
  31. package/compose/src/commonMain/kotlin/vn/momo/kits/components/BadgeRibbon.kt +338 -0
  32. package/compose/src/commonMain/kotlin/vn/momo/kits/components/BaselineView.kt +175 -0
  33. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Button.kt +354 -0
  34. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Carousel.kt +115 -0
  35. package/compose/src/commonMain/kotlin/vn/momo/kits/components/CheckBox.kt +89 -0
  36. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Chip.kt +130 -0
  37. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Collapse.kt +209 -0
  38. package/compose/src/commonMain/kotlin/vn/momo/kits/components/CupertinoOverscroll.kt +482 -0
  39. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Divider.kt +49 -0
  40. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Icon.kt +86 -0
  41. package/compose/src/commonMain/kotlin/vn/momo/kits/components/IconButton.kt +125 -0
  42. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Image.kt +224 -0
  43. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Information.kt +137 -0
  44. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Input.kt +473 -0
  45. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputDropDown.kt +113 -0
  46. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputMoney.kt +262 -0
  47. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputOTP.kt +237 -0
  48. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputPhoneNumber.kt +228 -0
  49. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputSearch.kt +280 -0
  50. package/compose/src/commonMain/kotlin/vn/momo/kits/components/InputTextArea.kt +183 -0
  51. package/compose/src/commonMain/kotlin/vn/momo/kits/components/LazyColumnWithBouncing.kt +342 -0
  52. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Loader.kt +108 -0
  53. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationDot.kt +56 -0
  54. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationNumber.kt +40 -0
  55. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationScroll.kt +82 -0
  56. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PaginationWhiteDot.kt +39 -0
  57. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PopupNotify.kt +362 -0
  58. package/compose/src/commonMain/kotlin/vn/momo/kits/components/PopupPromotion.kt +108 -0
  59. package/compose/src/commonMain/kotlin/vn/momo/kits/components/ProgressInfo.kt +304 -0
  60. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Radio.kt +59 -0
  61. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Rating.kt +87 -0
  62. package/compose/src/commonMain/kotlin/vn/momo/kits/components/ScaleSizeScope.kt +21 -0
  63. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Skeleton.kt +88 -0
  64. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Slider.kt +308 -0
  65. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Stepper.kt +218 -0
  66. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Steps.kt +456 -0
  67. package/compose/src/commonMain/kotlin/vn/momo/kits/components/SuggestAction.kt +122 -0
  68. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Swipe.kt +205 -0
  69. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Switch.kt +89 -0
  70. package/compose/src/commonMain/kotlin/vn/momo/kits/components/TabView.kt +542 -0
  71. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Tag.kt +86 -0
  72. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Text.kt +175 -0
  73. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Title.kt +201 -0
  74. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Tooltip.kt +498 -0
  75. package/compose/src/commonMain/kotlin/vn/momo/kits/components/TrustBanner.kt +176 -0
  76. package/compose/src/commonMain/kotlin/vn/momo/kits/components/Uploader.kt +182 -0
  77. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/DateTimePicker.kt +193 -0
  78. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/DateTimePickerTypes.kt +29 -0
  79. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/DateTimePickerUtils.kt +208 -0
  80. package/compose/src/commonMain/kotlin/vn/momo/kits/components/datetimepicker/WheelPicker.kt +180 -0
  81. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Colors.kt +325 -0
  82. package/compose/src/commonMain/kotlin/vn/momo/kits/const/HostFont.kt +12 -0
  83. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Radius.kt +12 -0
  84. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Spacing.kt +16 -0
  85. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Theme.kt +194 -0
  86. package/compose/src/commonMain/kotlin/vn/momo/kits/const/Typography.kt +291 -0
  87. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/Card.kt +54 -0
  88. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/HeaderLayout.kt +71 -0
  89. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/Item.kt +50 -0
  90. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/ModalLayout.kt +184 -0
  91. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/ScreenLayout.kt +315 -0
  92. package/compose/src/commonMain/kotlin/vn/momo/kits/layout/Section.kt +41 -0
  93. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/AutomationId.kt +54 -0
  94. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Clickable.kt +66 -0
  95. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Conditional.kt +11 -0
  96. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/DeprecatedModifier.kt +104 -0
  97. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Shadow.kt +48 -0
  98. package/compose/src/commonMain/kotlin/vn/momo/kits/modifier/Size.kt +51 -0
  99. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/BottomSheet.kt +397 -0
  100. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/HostBackGestureBridge.kt +58 -0
  101. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/ModalScreen.kt +153 -0
  102. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/Navigation.kt +118 -0
  103. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/NavigationContainer.kt +206 -0
  104. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/Navigator.kt +421 -0
  105. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/ScrollToTop.kt +8 -0
  106. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/StackScreen.kt +750 -0
  107. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/StackTransition.kt +152 -0
  108. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/SwipeBackHaptic.kt +35 -0
  109. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/BottomTab.kt +242 -0
  110. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/BottomTabBar.kt +398 -0
  111. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/CurvedContainer.kt +103 -0
  112. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/DuoBarCompression.kt +93 -0
  113. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/DuoTabBar.kt +208 -0
  114. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/TabBarMetrics.kt +133 -0
  115. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/FloatingButton.kt +167 -0
  116. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/Header.kt +446 -0
  117. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderBackground.kt +105 -0
  118. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderJourney.kt +106 -0
  119. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderLocation.kt +74 -0
  120. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderRight.kt +400 -0
  121. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderTitle.kt +39 -0
  122. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/HeaderUser.kt +363 -0
  123. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/SideBar.kt +197 -0
  124. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/component/SnackBar.kt +133 -0
  125. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/tracking/ScreenTracker.kt +127 -0
  126. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/BackGesture.kt +12 -0
  127. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/ComposeLottieAnimation.kt +114 -0
  128. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/OsFontScale.kt +7 -0
  129. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/Platform.kt +76 -0
  130. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/ReduceMotion.kt +7 -0
  131. package/compose/src/commonMain/kotlin/vn/momo/kits/platform/ReservedRegions.kt +21 -0
  132. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiActions.kt +154 -0
  133. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiExpr.kt +1038 -0
  134. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiKitNodes.kt +848 -0
  135. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiLog.kt +47 -0
  136. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiModel.kt +39 -0
  137. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiPropsRenderer.kt +463 -0
  138. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiRenderer.kt +1146 -0
  139. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiStyle.kt +667 -0
  140. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiTracking.kt +240 -0
  141. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiValidate.kt +185 -0
  142. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiView.kt +200 -0
  143. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Icons.kt +1329 -0
  144. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Resources.kt +55 -0
  145. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Tracking.kt +15 -0
  146. package/compose/src/commonMain/kotlin/vn/momo/kits/utils/Utils.kt +117 -0
  147. package/compose/src/iosMain/kotlin/vn/momo/kits/const/HostFont.ios.kt +42 -0
  148. package/compose/src/iosMain/kotlin/vn/momo/kits/navigation/HostBackGesture.ios.kt +45 -0
  149. package/compose/src/iosMain/kotlin/vn/momo/kits/navigation/ScrollToTop.ios.kt +32 -0
  150. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/BackGesture.ios.kt +38 -0
  151. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/OsFontScale.ios.kt +65 -0
  152. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/Platform.ios.kt +217 -0
  153. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/ReduceMotion.ios.kt +48 -0
  154. package/compose/src/iosMain/kotlin/vn/momo/kits/platform/ReservedRegions.ios.kt +143 -0
  155. package/gradle/libs.versions.toml +69 -0
  156. package/gradle/wrapper/gradle-wrapper.jar +0 -0
  157. package/gradle/wrapper/gradle-wrapper.properties +8 -0
  158. package/gradle.properties +24 -0
  159. package/gradlew +252 -0
  160. package/gradlew.bat +94 -0
  161. package/ios-demo/README.md +120 -0
  162. package/package.json +1 -1
  163. package/scripts/sdui-visual/README.md +64 -0
  164. package/settings.gradle.kts +64 -0
@@ -0,0 +1,240 @@
1
+ // File: compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiTracking.kt
2
+ // Created At: 2026-10-27 18:00:00 +07:00
3
+ // Created By: AI
4
+ // AI Agent: Claude Code
5
+ // Model: claude-sonnet-5-5
6
+
7
+ package vn.momo.kits.sdui
8
+
9
+ import kotlin.random.Random
10
+
11
+ // AI-GENERATED START: SDUI own events (tracker, envelope, session, sampler, sanitizer, sinks)
12
+
13
+ /** The one event name every SDUI event is emitted under; the kind of event is the `step` field. */
14
+ internal const val OPS_INFO_CHECKED = "ops_info_checked"
15
+
16
+ /** One event: always named [OPS_INFO_CHECKED]; [fields] carries `step` (the kind) plus raw fields (the sanitizer allowlist decides what survives). */
17
+ internal data class TrackEvent(val fields: Map<String, Any?> = emptyMap()) {
18
+ val name: String get() = OPS_INFO_CHECKED
19
+ val step: String? get() = fields["step"] as? String
20
+ }
21
+
22
+ /** Fields every event carries. Order = envelope order. */
23
+ internal data class TrackEnvelope(
24
+ val renderId: String,
25
+ val sessionId: String,
26
+ val screenId: String,
27
+ val renderVersion: Int,
28
+ val sduiVersion: String,
29
+ val os: String?,
30
+ val t: Long,
31
+ ) {
32
+ fun toMap(): Map<String, Any?> = linkedMapOf(
33
+ "renderId" to renderId, "sessionId" to sessionId, "screenId" to screenId,
34
+ "renderVersion" to renderVersion, "sduiVersion" to sduiVersion, "os" to os, "t" to t,
35
+ )
36
+ }
37
+
38
+ internal data class TrackRecord(val event: TrackEvent, val envelope: Map<String, Any?>)
39
+
40
+ internal interface TrackSink {
41
+ val id: String
42
+ fun write(record: TrackRecord)
43
+ }
44
+
45
+ internal data class SessionCtx(val screenId: String, val renderVersion: Int = RENDER_VERSION)
46
+
47
+ internal interface RenderSession {
48
+ val renderId: String
49
+ /** Start of a step - mark(step) later closes it and emits ops_info_checked. */
50
+ fun start(step: String)
51
+ /** [durationMs] given = the step's measured duration (used instead of the start/mark diff). */
52
+ fun mark(step: String, extra: Map<String, Any?>? = null, durationMs: Long? = null)
53
+ fun error(err: SduiError, nodePath: String? = null)
54
+ /** An error on a child node (`sdui_node_error`). Identical reports (nodePath, code, reason) count once per render; never capped; still sent after [end]. */
55
+ fun nodeError(code: String, reason: String, nodePath: String, nodeType: String? = null, nodeId: String? = null)
56
+ fun end(result: String)
57
+
58
+ companion object {
59
+ /** Used where no tracker is wired (tests / error screens). */
60
+ val NOOP: RenderSession = object : RenderSession {
61
+ override val renderId = "noop"
62
+ override fun start(step: String) {}
63
+ override fun mark(step: String, extra: Map<String, Any?>?, durationMs: Long?) {}
64
+ override fun error(err: SduiError, nodePath: String?) {}
65
+ override fun nodeError(code: String, reason: String, nodePath: String, nodeType: String?, nodeId: String?) {}
66
+ override fun end(result: String) {}
67
+ }
68
+ }
69
+ }
70
+
71
+ /** Mutable per-render context behind the common envelope. */
72
+ internal class EnvelopeState(val renderId: String, val ctx: SessionCtx, val base: EnvelopeBase)
73
+
74
+ internal data class EnvelopeBase(val sessionId: String, val os: String? = null)
75
+
76
+ internal fun buildEnvelope(s: EnvelopeState, now: Long): TrackEnvelope = TrackEnvelope(
77
+ renderId = s.renderId, sessionId = s.base.sessionId, screenId = s.ctx.screenId,
78
+ renderVersion = s.ctx.renderVersion, sduiVersion = SduiView.VERSION, os = s.base.os, t = now,
79
+ )
80
+
81
+ private const val BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz"
82
+ private fun rand6(random: Random) = buildString { repeat(6) { append(BASE36[random.nextInt(36)]) } }
83
+
84
+ /** No crypto needed: base36 clock + two random chunks (>= 12 chars), like newRenderId. */
85
+ internal fun newRenderId(now: Long = SduiClock.epochMs(), random: Random = Random.Default): String =
86
+ now.toString(36) + rand6(random) + rand6(random)
87
+
88
+ // ---- sampler ---------------------------------------------------------------------------------------------------------
89
+ /** Errors and diagnostics (by `step`) are never sampled out. */
90
+ private val ALWAYS = setOf("sdui_error", "sdui_node_error")
91
+
92
+ /** FNV-1a -> [0,1). Deterministic per sessionId, so a session is wholly in or out. */
93
+ internal fun sampleBucket(sessionId: String): Double {
94
+ var h = 0x811c9dc5L
95
+ for (c in sessionId) {
96
+ h = h xor c.code.toLong()
97
+ h = (h * 0x01000193L) and 0xFFFFFFFFL
98
+ }
99
+ return h / 4294967296.0
100
+ }
101
+
102
+ internal fun createSampler(rate: Double): (String, String) -> Boolean {
103
+ val decided = HashMap<String, Boolean>()
104
+ return { sessionId, step ->
105
+ if (step in ALWAYS) true
106
+ else decided.getOrPut(sessionId) { if (rate >= 1) true else if (rate <= 0) false else sampleBucket(sessionId) < rate }
107
+ }
108
+ }
109
+
110
+ // ---- sanitizer -------------------------------------------------------------------------------------------------------
111
+ internal const val MAX_STRING = 120
112
+
113
+ /** Allowlist per `step` (`step` itself is always kept): anything not listed is dropped. This is the privacy gate. */
114
+ private val STEP_FIELDS: Map<String, List<String>> = mapOf(
115
+ "sdui_parse" to listOf("duration", "extra"),
116
+ "sdui_validate" to listOf("duration", "extra"),
117
+ "first_paint" to listOf("duration", "extra"),
118
+ "render_done" to listOf("duration", "extra"),
119
+ "sdui_error" to listOf("stage", "code", "retryable", "nodePath"),
120
+ "sdui_node_error" to listOf("code", "reason", "nodePath", "nodeId", "nodeType"),
121
+ )
122
+ private val EXTRA_KEYS = setOf("ok", "bytesRaw")
123
+ private val ENVELOPE_FIELDS = listOf("renderId", "sessionId", "screenId", "renderVersion", "sduiVersion", "os", "t")
124
+
125
+ private fun prim(v: Any?): Any? = when (v) {
126
+ is String -> if (v.length > MAX_STRING) v.substring(0, MAX_STRING) else v
127
+ is Number -> if (v.toDouble().isFinite()) v else null
128
+ is Boolean -> v
129
+ else -> null
130
+ }
131
+
132
+ private fun pick(src: Map<String, Any?>, keys: List<String>): Map<String, Any?> {
133
+ val out = LinkedHashMap<String, Any?>()
134
+ for (k in keys) {
135
+ if (k == "extra") {
136
+ val ex = src["extra"].asMap()
137
+ if (ex != null) {
138
+ val clean = LinkedHashMap<String, Any?>()
139
+ ex.forEach { (ek, ev) -> if (ek in EXTRA_KEYS) prim(ev)?.let { clean[ek] = it } }
140
+ if (clean.isNotEmpty()) out["extra"] = clean
141
+ }
142
+ continue
143
+ }
144
+ prim(src[k])?.let { out[k] = it }
145
+ }
146
+ return out
147
+ }
148
+
149
+ /** Returns null for a `step` outside the catalogue. */
150
+ internal fun sanitizeRecord(record: TrackRecord): TrackRecord? {
151
+ val step = record.event.step ?: return null
152
+ val fields = STEP_FIELDS[step] ?: return null
153
+ return TrackRecord(TrackEvent(pick(record.event.fields, listOf("step") + fields)), pick(record.envelope, ENVELOPE_FIELDS))
154
+ }
155
+
156
+ // ---- tracker ---------------------------------------------------------------------------------------------------------
157
+ internal class Tracker(
158
+ private val sinks: List<TrackSink>,
159
+ sessionId: String,
160
+ os: String? = null,
161
+ sampleRate: Double = 1.0,
162
+ private val clock: () -> Long = { SduiClock.epochMs() },
163
+ ) {
164
+ private val sampler = createSampler(sampleRate)
165
+ private val base = EnvelopeBase(sessionId, os)
166
+
167
+ /** A throwing sink must never break the app - each call is isolated. */
168
+ private fun each(fn: (TrackSink) -> Unit) = sinks.forEach { runCatching { fn(it) } }
169
+
170
+ private fun dispatch(event: TrackEvent, state: EnvelopeState, t: Long) {
171
+ val record = sanitizeRecord(TrackRecord(event, buildEnvelope(state, t).toMap())) ?: return
172
+ if (!sampler(base.sessionId, record.event.step ?: return)) return
173
+ each { it.write(record) }
174
+ }
175
+
176
+ fun begin(ctx: SessionCtx): RenderSession {
177
+ val state = EnvelopeState(newRenderId(clock()), ctx, base)
178
+ return createRenderSession(state, clock, ::dispatch)
179
+ }
180
+ }
181
+
182
+ private fun createRenderSession(
183
+ state: EnvelopeState,
184
+ clock: () -> Long,
185
+ emit: (TrackEvent, EnvelopeState, Long) -> Unit,
186
+ ): RenderSession {
187
+ val t0 = clock()
188
+ val starts = HashMap<String, Long>()
189
+ var ended = false
190
+ val nodeErrors = HashSet<String>()
191
+ fun send(step: String, vararg f: Pair<String, Any?>) = emit(TrackEvent(linkedMapOf("step" to step, *f)), state, clock())
192
+ // A late render step after end() (a late callback) would land in a closed session: drop it.
193
+ fun e(step: String, vararg f: Pair<String, Any?>) { if (!ended) send(step, *f) }
194
+ return object : RenderSession {
195
+ override val renderId = state.renderId
196
+ override fun start(step: String) { starts[step] = clock() }
197
+ override fun mark(step: String, extra: Map<String, Any?>?, durationMs: Long?) {
198
+ // A step never started is measured from the session start, so the timeline never loses a mark.
199
+ val from = starts.remove(step) ?: t0
200
+ e(step, "duration" to (durationMs?.let { maxOf(0L, it) } ?: maxOf(0L, clock() - from)), "extra" to extra)
201
+ }
202
+ override fun error(err: SduiError, nodePath: String?) =
203
+ e("sdui_error", "stage" to err.stage, "code" to err.code, "retryable" to err.retryable, "nodePath" to nodePath)
204
+ // Node errors outlive render_done/end(): a lazily composed node can fail late. One event per (node path, code, reason):
205
+ // re-evaluating a node (recomposition) does not repeat it, and repeat copies of one spec node share a path.
206
+ override fun nodeError(code: String, reason: String, nodePath: String, nodeType: String?, nodeId: String?) {
207
+ if (!nodeErrors.add("$nodePath|$code|$reason")) return
208
+ send("sdui_node_error", "code" to code, "reason" to reason, "nodePath" to nodePath, "nodeId" to nodeId, "nodeType" to nodeType)
209
+ }
210
+ override fun end(result: String) { ended = true }
211
+ }
212
+ }
213
+
214
+ // ---- sinks -----------------------------------------------------------------------------------------------------------
215
+ /** Trackify wants flat params: nested `extra` becomes extra_<key>. */
216
+ internal fun flattenRecord(record: TrackRecord): Map<String, Any> {
217
+ val out = LinkedHashMap<String, Any>()
218
+ record.envelope.forEach { (k, v) -> if (v != null) out[k] = v }
219
+ record.event.fields.forEach { (k, v) ->
220
+ if (k == "extra" && v is Map<*, *>) v.forEach { (ek, ev) -> if (ev != null) out["extra_$ek"] = ev }
221
+ else if (v != null) out[k] = v
222
+ }
223
+ return out
224
+ }
225
+
226
+ /** Reports every event to Trackify through IMaxApi.track (wired by default, see [SduiTracking.createDefault]). */
227
+ internal class TrackifySink(private val track: (String, Map<String, Any>) -> Unit) : TrackSink {
228
+ override val id = "trackify"
229
+ override fun write(record: TrackRecord) = track(record.event.name, flattenRecord(record))
230
+ }
231
+
232
+ internal object SduiTracking {
233
+ /** One tracker (and sessionId) per SduiView; its events go through that view's [maxApi]. */
234
+ fun createDefault(maxApi: SduiMaxApi): Tracker {
235
+ val sinks = ArrayList<TrackSink>()
236
+ sinks += TrackifySink { name, params -> maxApi.track(name, params) }
237
+ return Tracker(sinks, sessionId = SduiClock.epochMs().toString(36) + rand6(Random.Default), os = vn.momo.kits.platform.getPlatformName().lowercase())
238
+ }
239
+ }
240
+ // AI-GENERATED END: SDUI own events
@@ -0,0 +1,185 @@
1
+ // File: compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiValidate.kt
2
+ // Created At: 2026-10-27 17:00:00 +07:00
3
+ // Created By: AI
4
+ // AI Agent: Claude Code
5
+ // Model: claude-sonnet-5-5
6
+
7
+ package vn.momo.kits.sdui
8
+
9
+ // AI-GENERATED START: spec structure validation
10
+ /** What SduiView reads (meta / body / data / state) plus editor metadata it ignores (`\$schema`, `__od`). */
11
+ private val TOP_LEVEL = setOf("\$schema", "meta", "body", "data", "state", "__od")
12
+ /** Screen-level spec keys: valid in a full-screen spec, but SduiView only draws a section, so they would be silently lost. */
13
+ private val SCREEN_ONLY = setOf(
14
+ "components", "overlays", "header", "footer", "tabs", "tracking", "localization", "actions", "onMount",
15
+ )
16
+ private val NODE_FIELDS = setOf(
17
+ "type", "props", "styles", "children", "text", "repeat", "visible", "visibleWhen", "linearGradient", "gradientBorder",
18
+ "actions", "name", "id", "key", "figma", "__od",
19
+ )
20
+ /** SduiView draws `body` once, directly (it never goes through `expand`), so these node keys would be silently ignored on it. */
21
+ private val BODY_UNSUPPORTED = setOf("repeat", "visible", "visibleWhen")
22
+ /** Styles live in `styles` only (body and nodes alike); a singular `style` (or `scrollable`, which nothing reads on body) is an unknown field. */
23
+ private val BODY_FIELDS = NODE_FIELDS - BODY_UNSUPPORTED
24
+ /** The renderer names the item by `as` only. */
25
+ private val REPEAT_FIELDS = setOf("source", "from", "as", "index")
26
+ /** Deeper specs are rejected: drawing (and validating) them recursively could overflow the native stack. */
27
+ private const val MAX_NODE_DEPTH = 100
28
+ private val ACTION_FIELDS = setOf("name", "description", "args", "when", "params", "type")
29
+ /** `root` (editor entry-screen marker), `version` and `description` are accepted and ignored by the renderer. */
30
+ private val META_FIELDS = setOf("screenName", "version", "description", "root", "mode", "minRenderVersion")
31
+ /**
32
+ * Style keys with no meaning at all on native: the renderer never reads them, so a spec relying on them would silently
33
+ * look different. Only this explicit list is rejected; any other style key is still accepted (see [IGNORED_STYLES]).
34
+ */
35
+ internal val UNSUPPORTED_STYLES = setOf(
36
+ "transform", "elevation", "shadowColor", "shadowOffset", "shadowOpacity", "shadowRadius", "backgroundImage",
37
+ "columnGap", "display",
38
+ )
39
+
40
+ private const val USE_TEXT_PROPS = "use props.typography/props.color"
41
+
42
+ /**
43
+ * Style keys that are accepted (real specs use them) but ignored when drawing, each with the hint written to the log.
44
+ * A node whose resolved styles carry one reports `sdui_node_error` code [NODE_ERR_UNSUPPORTED_STYLE], reason = the key
45
+ * name, once per node path ([reportIgnoredStyles]).
46
+ */
47
+ internal val IGNORED_STYLES: Map<String, String> = linkedMapOf(
48
+ "fontSize" to USE_TEXT_PROPS, "fontWeight" to USE_TEXT_PROPS, "lineHeight" to USE_TEXT_PROPS,
49
+ "letterSpacing" to USE_TEXT_PROPS, "color" to USE_TEXT_PROPS,
50
+ "alignSelf" to "use the parent's alignItems",
51
+ )
52
+
53
+ internal const val NODE_ERR_UNSUPPORTED_STYLE = "unsupported_style"
54
+
55
+ private fun checkKeys(obj: Any?, allowed: Set<String>, path: String, out: MutableList<String>) {
56
+ val m = obj.asMap() ?: return
57
+ m.keys.forEach { if (it !in allowed) out += "unknown field \"$it\" at $path" }
58
+ }
59
+
60
+ internal data class Validation(val errors: List<String>)
61
+
62
+ /** Structure errors make the screen undrawable (SPEC_SHAPE). */
63
+ internal fun validateStructure(spec: Any?): Validation {
64
+ val errors = ArrayList<String>()
65
+ val s = spec.asMap() ?: return Validation(listOf("spec must be an object"))
66
+ // screenName is optional for a block: it is only a tracking label
67
+ s.keys.forEach {
68
+ when (it) {
69
+ in TOP_LEVEL -> Unit
70
+ in SCREEN_ONLY -> errors += "top-level \"$it\" is not supported in a section"
71
+ else -> errors += "unknown top-level key \"$it\""
72
+ }
73
+ }
74
+ s["meta"].asMap()?.let { checkKeys(it, META_FIELDS, "meta", errors) }
75
+ val body = s["body"]
76
+ // SduiView draws `body` itself as one node, so it must be a node (object with a string type)
77
+ if (body.asMap() == null) errors += "body must be an object"
78
+ else if ((body.asMap()?.get("type") as? String).isNullOrEmpty()) errors += "body is an object without a \"type\" (string)"
79
+ body.asMap()?.let { b ->
80
+ BODY_UNSUPPORTED.forEach { if (it in b) errors += "body.$it is not supported: the block body is always drawn once" }
81
+ b.keys.forEach { if (it !in BODY_FIELDS && it !in BODY_UNSUPPORTED) errors += "unknown field \"$it\" at body" }
82
+ }
83
+ if (body.asMap()?.get("props").asMap()?.containsKey("inputSearchProps") == true) {
84
+ errors += "body.props.inputSearchProps is header config, which a section does not have"
85
+ }
86
+
87
+ /** `when` / `visible` / `visibleWhen`: a boolean or a string with a `{binding}`; a plain string would always be truthy. */
88
+ fun checkCondition(m: Map<*, *>, key: String, path: String) {
89
+ if (!m.containsKey(key)) return
90
+ val v = m[key]
91
+ if (v == null || v is Boolean || (v is String && INTERP_RE.containsMatchIn(v))) return
92
+ errors += "$path.$key must be a boolean or a {binding}"
93
+ }
94
+
95
+ fun validateAction(a: Any?, path: String) {
96
+ val m = a.asMap()
97
+ if (m == null) { errors += "$path must be an action object"; return }
98
+ checkKeys(m, ACTION_FIELDS, path, errors)
99
+ checkCondition(m, "when", path)
100
+ if (m["type"] !is String) errors += "$path.type is required"
101
+ }
102
+
103
+ /**
104
+ * Actions that live inside props (the callback-shaped `onXxx`, TrustBanner `trackEvent`, button `primary`/`secondary`, Swipe `leftActions`/`rightActions`):
105
+ * the same action checks as node.actions; their `name` is optional (a button action defaults to "onPress").
106
+ */
107
+ fun validatePropActions(node: Map<*, *>, path: String) {
108
+ val props = node["props"].asMap() ?: return
109
+ fun list(v: Any?, at: String) {
110
+ when (v) {
111
+ is Map<*, *> -> validateAction(v, at)
112
+ is List<*> -> v.forEachIndexed { i, a -> validateAction(a, "$at[$i]") }
113
+ else -> Unit
114
+ }
115
+ }
116
+ props.forEach { (k, v) ->
117
+ if (k.length > 2 && k.startsWith("on") && k[2].isUpperCase()) list(v, "$path.props.$k")
118
+ }
119
+ // TrustBanner dispatches its `trackEvent` prop as actions (a map or a list), the only non-`onXxx` callback prop
120
+ props["trackEvent"]?.let { list(it, "$path.props.trackEvent") }
121
+ // button-style props: the runtime reads `actions` as a list (or a binding string resolving to one)
122
+ fun buttonActions(v: Any?, at: String) {
123
+ if (v is Map<*, *>) errors += "$at must be a list of actions"
124
+ else list(v, at)
125
+ }
126
+ listOf("primary", "secondary").forEach { k ->
127
+ props[k].asMap()?.get("actions")?.let { buttonActions(it, "$path.props.$k.actions") }
128
+ }
129
+ listOf("leftActions", "rightActions").forEach { k ->
130
+ props[k].asList()?.forEachIndexed { i, item ->
131
+ item.asMap()?.get("actions")?.let { buttonActions(it, "$path.props.$k[$i].actions") }
132
+ }
133
+ }
134
+ }
135
+
136
+ /** Node-level `actions`: the renderer reads a list of named actions, anything else is silently ignored. */
137
+ fun nodeActions(m: Map<*, *>, path: String) {
138
+ val v = m["actions"] ?: return
139
+ val l = v.asList()
140
+ if (l == null) { errors += "$path.actions must be a list of actions"; return }
141
+ l.forEachIndexed { i, a ->
142
+ if (a.asMap()?.get("name") !is String) errors += "$path.actions[$i] needs a \"name\""
143
+ validateAction(a, "$path.actions[$i]")
144
+ }
145
+ }
146
+
147
+ /** A node's `children` as a list, or null after reporting a non-list (text belongs in props.children). */
148
+ fun childList(m: Map<*, *>, path: String): List<Any?>? {
149
+ val v = m["children"] ?: return null
150
+ return v.asList() ?: null.also { errors += "$path.children must be a list of nodes; put text in props.children" }
151
+ }
152
+
153
+ /** A literal `styles` map must not use [UNSUPPORTED_STYLES]; a whole-binding string is only known at render time. */
154
+ fun checkStyles(m: Map<*, *>, path: String) {
155
+ val st = m["styles"].asMap() ?: return
156
+ st.keys.forEach { k -> if (k in UNSUPPORTED_STYLES) errors += "$path.styles.$k is not supported" }
157
+ }
158
+
159
+ var tooDeep = false
160
+
161
+ fun walk(node: Any?, path: String, depth: Int) {
162
+ if (node == null || tooDeep) return
163
+ if (depth > MAX_NODE_DEPTH) { tooDeep = true; errors += "spec nested too deeply (over $MAX_NODE_DEPTH levels) at $path"; return }
164
+ node.asList()?.let { l -> l.forEachIndexed { i, c -> walk(c, "$path[$i]", depth + 1) }; return }
165
+ val m = node.asMap() ?: return
166
+ val type = m["type"]
167
+ if (type !is String || type.isEmpty()) { errors += "$path is an object without a \"type\" (string)"; return }
168
+ checkKeys(m, NODE_FIELDS, "$path (type=$type)", errors)
169
+ m["repeat"]?.let { checkKeys(it, REPEAT_FIELDS, "$path.repeat", errors) }
170
+ checkCondition(m, "visible", path)
171
+ checkCondition(m, "visibleWhen", path)
172
+ checkStyles(m, path)
173
+ nodeActions(m, path)
174
+ validatePropActions(m, path)
175
+ childList(m, path)?.forEachIndexed { i, c -> walk(c, "$path.children[$i]", depth + 1) }
176
+ }
177
+ body.asMap()?.let { b ->
178
+ validatePropActions(b, "body")
179
+ checkStyles(b, "body")
180
+ childList(b, "body")?.forEachIndexed { i, c -> walk(c, "body.children[$i]", 1) }
181
+ nodeActions(b, "body")
182
+ }
183
+ return Validation(errors)
184
+ }
185
+ // AI-GENERATED END: spec structure validation
@@ -0,0 +1,200 @@
1
+ // File: compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiView.kt
2
+ // Created At: 2026-10-29 10:00:00 +07:00
3
+ // Created By: AI
4
+ // AI Agent: Claude Code
5
+ // Model: claude-sonnet-5-5
6
+
7
+ package vn.momo.kits.sdui
8
+
9
+ import androidx.compose.runtime.Composable
10
+ import androidx.compose.runtime.LaunchedEffect
11
+ import androidx.compose.runtime.mutableStateMapOf
12
+ import androidx.compose.runtime.remember
13
+ import androidx.compose.runtime.rememberUpdatedState
14
+ import androidx.compose.runtime.withFrameNanos
15
+ import androidx.compose.ui.Modifier
16
+ import kotlinx.serialization.json.Json
17
+ import vn.momo.kits.const.AppTheme
18
+ import vn.momo.kits.navigation.LocalMaxApi
19
+ import vn.momo.maxapi.IMaxApi
20
+
21
+ // AI-GENERATED START: SduiView - the embeddable SDUI block (replaces the full-screen SduiHost)
22
+ object SduiView {
23
+ /** Highest spec feature level this renderer draws; a spec with a larger `meta.minRenderVersion` is refused. */
24
+ const val RENDER_VERSION: Int = 1
25
+
26
+ /**
27
+ * This renderer's own version, sent as `sduiVersion` on every tracking event. Set by hand (semver): bump PATCH for a
28
+ * renderer fix, MINOR for a new node / prop / action, MAJOR when a spec that used to work no longer does.
29
+ */
30
+ const val VERSION: String = "1.0.0"
31
+ }
32
+
33
+ /** A spec that passed every gate and is ready to draw. */
34
+ internal class PreparedView(
35
+ val body: Map<String, Any?>,
36
+ val data: Map<String, Any?>,
37
+ val initialState: Map<String, Any?>,
38
+ val screenName: String?,
39
+ val session: RenderSession,
40
+ )
41
+
42
+ /** One logFile line for a parse/validation failure; detail is spec-level text (sizes, field names, paths). */
43
+ internal fun errorLogLine(error: SduiError): String =
44
+ "[SDUI] block: ${error.code} ${error.stage}" + (error.detail?.let { " - $it" } ?: "")
45
+
46
+ /** UTF-8 byte length of [s] without encoding it: surrogate pair = 4, BMP 1/2/3, an unpaired surrogate 3 (as its U+FFFD replacement). */
47
+ /** Deepest `[` / `{` nesting of [json], ignoring brackets inside string literals. One linear pass, no recursion. */
48
+ internal fun jsonNestingDepth(json: String): Int {
49
+ var depth = 0
50
+ var max = 0
51
+ var inString = false
52
+ var escaped = false
53
+ for (c in json) {
54
+ if (inString) {
55
+ when {
56
+ escaped -> escaped = false
57
+ c == '\\' -> escaped = true
58
+ c == '"' -> inString = false
59
+ }
60
+ continue
61
+ }
62
+ when (c) {
63
+ '"' -> inString = true
64
+ '[', '{' -> { depth++; if (depth > max) max = depth }
65
+ ']', '}' -> if (depth > 0) depth--
66
+ }
67
+ }
68
+ return max
69
+ }
70
+
71
+ internal fun utf8Length(s: String): Int {
72
+ var n = 0
73
+ var i = 0
74
+ while (i < s.length) {
75
+ val c = s[i]
76
+ when {
77
+ c.code < 0x80 -> n += 1
78
+ c.code < 0x800 -> n += 2
79
+ c.isHighSurrogate() && i + 1 < s.length && s[i + 1].isLowSurrogate() -> { n += 4; i++ }
80
+ else -> n += 3
81
+ }
82
+ i++
83
+ }
84
+ return n
85
+ }
86
+
87
+ private fun err(stage: String, code: String, detail: String? = null) =
88
+ SduiResult.Err(SduiError(stage, code, retryable = false, detail = detail))
89
+
90
+ /**
91
+ * All the non-UI work of [SduiView], kept out of the composable so it is unit-testable. Accepts a bare spec only.
92
+ * [beginSession] is called once, as soon as the block's tracking label is known (`null` = parse failed before it was).
93
+ * Never throws: every failure is a [SduiResult.Err] already reported to the session (sdui_error + end("fail")).
94
+ */
95
+ internal fun prepareSduiView(
96
+ json: String,
97
+ renderVersion: Int,
98
+ nowMs: () -> Long = SduiClock::nowMs,
99
+ beginSession: (screenName: String?) -> RenderSession = { RenderSession.NOOP },
100
+ ): SduiResult<PreparedView> {
101
+ var session: RenderSession? = null
102
+ fun session(screenName: String?) = session ?: beginSession(screenName).also { session = it }
103
+ fun fail(e: SduiResult.Err): SduiResult.Err {
104
+ session(null).also { it.error(e.error); it.end("fail") }
105
+ return e
106
+ }
107
+
108
+ // size gate BEFORE parsing: a hostile payload must not cost a parse
109
+ val bytes = utf8Length(json)
110
+ if (bytes > MAX_PAYLOAD_BYTES) return fail(err("parse", ErrorCode.PAYLOAD_TOO_LARGE, "$bytes bytes"))
111
+ // nesting gate BEFORE parsing: the JSON parser and every tree walk recurse, and a stack overflow cannot be caught on iOS
112
+ if (jsonNestingDepth(json) > MAX_JSON_NESTING) return fail(err("parse", ErrorCode.PARSE, "JSON nested deeper than $MAX_JSON_NESTING levels"))
113
+ val parseStart = nowMs()
114
+ val parsed = runCatching { Json.parseToJsonElement(json).toPlain() }.getOrNull()
115
+ val parseMs = nowMs() - parseStart
116
+ val spec = parsed.asMap()
117
+ ?: return fail(err("parse", ErrorCode.PARSE, "spec is not a JSON object"))
118
+
119
+ val meta = spec["meta"].asMap().orEmpty()
120
+ val screenName = (meta["screenName"] as? String)?.takeIf { it.isNotBlank() }
121
+ val s = session(screenName)
122
+ s.mark("sdui_parse", mapOf("ok" to true, "bytesRaw" to bytes), durationMs = parseMs)
123
+
124
+ (meta["minRenderVersion"] as? Number)?.let { min ->
125
+ if (min.toInt() > renderVersion) return fail(err("validate", ErrorCode.UNSUPPORTED_VERSION, "needs render v${min.toInt()}"))
126
+ }
127
+ when (val mode = meta["mode"]) {
128
+ null, "section" -> Unit
129
+ "screen" -> return fail(err("validate", ErrorCode.UNSUPPORTED_MODE, "mode \"screen\" is not supported by SduiView"))
130
+ else -> return fail(err("validate", ErrorCode.SPEC_SHAPE, "unknown meta.mode \"$mode\""))
131
+ }
132
+
133
+ s.start("sdui_validate")
134
+ val structure = validateStructure(spec)
135
+ s.mark("sdui_validate", mapOf("ok" to structure.errors.isEmpty()))
136
+ if (structure.errors.isNotEmpty()) return fail(err("validate", ErrorCode.SPEC_SHAPE, structure.errors.take(3).joinToString("; ")))
137
+
138
+ s.start("first_paint"); s.start("render_done")
139
+ return SduiResult.Ok(
140
+ PreparedView(
141
+ body = spec["body"].asMap().orEmpty(),
142
+ data = spec["data"].asMap().orEmpty(),
143
+ initialState = spec["state"].asMap().orEmpty(),
144
+ screenName = screenName,
145
+ session = s,
146
+ ),
147
+ )
148
+ }
149
+
150
+ /**
151
+ * Draws one SDUI block (`{meta, data, body, state}`). Wrap-content height and no scrolling of its
152
+ * own, so it can be a row of a host LazyColumn. On any error it draws nothing and calls [onError] once per [spec] with the code
153
+ * (PAYLOAD_TOO_LARGE, PARSE, UNSUPPORTED_VERSION, UNSUPPORTED_MODE, SPEC_SHAPE).
154
+ * Actions go through [maxApi], else `LocalMaxApi`; tracking events go to `maxApi.track` and errors to `maxApi.logFile`. The api and the log belong to this view alone (nothing is process-wide).
155
+ */
156
+ @Composable
157
+ fun SduiView(spec: String, modifier: Modifier = Modifier, onError: ((code: String) -> Unit)? = null, maxApi: IMaxApi? = null) {
158
+ // Per-view host bindings: handed to everything below through the view's own objects, never through a global.
159
+ val apiNow = rememberUpdatedState(pickMaxApi(maxApi, LocalMaxApi.current))
160
+ val api = remember { SduiMaxApi({ apiNow.value }) }
161
+ val tracker = remember(api) { SduiTracking.createDefault(api) }
162
+ val result = remember(spec, tracker) {
163
+ prepareSduiView(spec, SduiView.RENDER_VERSION) { name -> tracker.begin(SessionCtx(screenId = "sdui:view:" + (name ?: "block"))) }
164
+ }
165
+ val onErrorNow = rememberUpdatedState(onError)
166
+ val prepared = when (result) {
167
+ is SduiResult.Err -> {
168
+ LaunchedEffect(spec) {
169
+ runCatching { api.logFile(errorLogLine(result.error)) }
170
+ onErrorNow.value?.invoke(result.error.code)
171
+ }
172
+ return
173
+ }
174
+ is SduiResult.Ok -> result.value
175
+ }
176
+
177
+ val log = remember(spec, api) { SduiLog(api, prepared.screenName ?: "block") }
178
+ val theme = AppTheme.current
179
+ val themeNow = rememberUpdatedState(theme)
180
+ val state = remember(spec) { mutableStateMapOf<String, Any?>().apply { putAll(prepared.initialState) } }
181
+ val scope = remember(spec, log) { SduiScope(prepared.data, state, log = log, nodeErrors = NodeErrorSink { prepared.session }) }
182
+ val runner = remember(spec, api) {
183
+ SduiActionRunner(state, { themeNow.value }, { prepared.session }, api, log, prepared.initialState.keys.toSet())
184
+ }
185
+ val ctx = remember(spec, theme, log) {
186
+ SduiCtx(theme, state, { actions, name, sc, args, path, id, type -> runner.run(actions, name, sc, args, path, id, type) }, prepared.session, log = log)
187
+ }
188
+
189
+ // render events: first_paint after the first frame of the body, render_done once it settled
190
+ LaunchedEffect(spec) {
191
+ withFrameNanos { }
192
+ prepared.session.mark("first_paint")
193
+ withFrameNanos { }
194
+ prepared.session.mark("render_done")
195
+ prepared.session.end("success")
196
+ }
197
+ RenderNode(prepared.body, scope, ctx, Parent(stretch = true), modifier, path = "body")
198
+ }
199
+
200
+ // AI-GENERATED END: SduiView