@momo-kits/native-kits 0.169.13-beta.4-debug → 0.169.13-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 (40) hide show
  1. package/CLAUDE.md +1 -4
  2. package/compose/build.gradle.kts +1 -5
  3. package/compose/compose.podspec +1 -1
  4. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/BottomTabBar.kt +12 -4
  5. package/compose/src/commonMain/kotlin/vn/momo/kits/navigation/bottomtab/CurvedContainer.kt +11 -3
  6. package/gradle/libs.versions.toml +0 -2
  7. package/gradle.properties +1 -1
  8. package/ios/Navigation/BottomTab/BottomTabBar.swift +14 -4
  9. package/ios/native-kits.podspec +1 -1
  10. package/ios-demo/MoMoUIKitsDemo.podspec +1 -1
  11. package/ios-demo/Sources/MoMoUIKitsDemo/SampleDemos/BottomTabDemo.swift +16 -3
  12. package/package.json +1 -1
  13. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiActionsTest.kt +0 -647
  14. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiExprTest.kt +0 -1411
  15. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiHostTest.kt +0 -130
  16. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiKitArgsTest.kt +0 -524
  17. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiKitNodesTest.kt +0 -559
  18. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRenderPlanTest.kt +0 -741
  19. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRenderReuseTest.kt +0 -221
  20. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiRendererPropsTest.kt +0 -270
  21. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiStylePlanTest.kt +0 -849
  22. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiStyleTest.kt +0 -212
  23. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiTrackingTest.kt +0 -239
  24. package/compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiViewTest.kt +0 -252
  25. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiActions.kt +0 -154
  26. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiExpr.kt +0 -1038
  27. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiKitNodes.kt +0 -848
  28. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiLog.kt +0 -47
  29. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiModel.kt +0 -39
  30. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiPropsRenderer.kt +0 -463
  31. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiRenderer.kt +0 -1146
  32. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiStyle.kt +0 -667
  33. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiTracking.kt +0 -240
  34. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiValidate.kt +0 -185
  35. package/compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiView.kt +0 -200
  36. package/scripts/sdui-visual/README.md +0 -64
  37. package/scripts/sdui-visual/diff.py +0 -65
  38. package/scripts/sdui-visual/drive.py +0 -234
  39. package/scripts/sdui-visual/plan.json +0 -713
  40. package/scripts/sdui-visual/run.sh +0 -92
@@ -1,252 +0,0 @@
1
- // File: compose/src/androidUnitTest/kotlin/vn/momo/kits/sdui/SduiViewTest.kt
2
- // Created At: 2026-10-29 10:30: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 org.junit.Assert.assertEquals
10
- import org.junit.Assert.assertNull
11
- import org.junit.Assert.assertTrue
12
- import org.junit.Test
13
- import java.io.File
14
-
15
- // AI-GENERATED START: unit tests for SduiView's pure part (prepareSduiView) and structure validation
16
- class SduiViewTest {
17
- @Test fun errorLogLineCarriesCodeStageAndDetail() {
18
- assertEquals("[SDUI] block: PARSE parse - spec is not a JSON object", errorLogLine(SduiError("parse", "PARSE", false, "spec is not a JSON object")))
19
- assertEquals("[SDUI] block: UNSUPPORTED_VERSION validate", errorLogLine(SduiError("validate", "UNSUPPORTED_VERSION", false)))
20
- }
21
-
22
- private fun prep(json: String, v: Int = 1) = prepareSduiView(json, v)
23
- private fun codeOf(r: SduiResult<*>) = (r as SduiResult.Err).error.code
24
- private fun ok(r: SduiResult<PreparedView>) = (r as SduiResult.Ok).value
25
-
26
- private val body = """{"type":"View","children":[{"type":"Text","props":{"children":"x"}}]}"""
27
- private fun spec(meta: String = """{"screenName":"S"}""", extra: String = "") = """{"meta":$meta,"body":$body$extra}"""
28
-
29
- // ---- error codes -----------------------------------------------------------------------------------------------
30
- @Test fun tooLargeIsRejectedBeforeParsing() {
31
- assertEquals(ErrorCode.PAYLOAD_TOO_LARGE, codeOf(prep(" ".repeat(MAX_PAYLOAD_BYTES + 1))))
32
- // the gate counts UTF-8 bytes, not chars: 3-byte chars overflow earlier
33
- assertEquals(ErrorCode.PAYLOAD_TOO_LARGE, codeOf(prep("€".repeat(MAX_PAYLOAD_BYTES / 3 + 1))))
34
- }
35
-
36
- @Test fun invalidJsonAndNonObjectAreParseErrors() {
37
- assertEquals(ErrorCode.PARSE, codeOf(prep("{")))
38
- assertEquals(ErrorCode.PARSE, codeOf(prep("")))
39
- assertEquals(ErrorCode.PARSE, codeOf(prep("[1,2]")))
40
- assertEquals(ErrorCode.PARSE, codeOf(prep("\"str\"")))
41
- }
42
-
43
- @Test fun minRenderVersionAboveRendererIsUnsupported() {
44
- assertEquals(ErrorCode.UNSUPPORTED_VERSION, codeOf(prep(spec("""{"minRenderVersion":2}"""))))
45
- assertTrue(prep(spec("""{"minRenderVersion":1}""")) is SduiResult.Ok)
46
- assertEquals(ErrorCode.UNSUPPORTED_VERSION, codeOf(prep(spec("""{"minRenderVersion":3}"""), v = 2)))
47
- }
48
-
49
- @Test fun modeSectionOrAbsentIsOkScreenIsUnsupportedOtherIsShape() {
50
- assertTrue(prep(spec("""{"mode":"section"}""")) is SduiResult.Ok)
51
- assertTrue(prep(spec("""{}""")) is SduiResult.Ok)
52
- assertEquals(ErrorCode.UNSUPPORTED_MODE, codeOf(prep(spec("""{"mode":"screen"}"""))))
53
- assertEquals(ErrorCode.SPEC_SHAPE, codeOf(prep(spec("""{"mode":"wat"}"""))))
54
- assertEquals(ErrorCode.SPEC_SHAPE, codeOf(prep(spec("""{"mode":5}"""))))
55
- }
56
-
57
- @Test fun bodyMustBeANode() {
58
- assertEquals(ErrorCode.SPEC_SHAPE, codeOf(prep("""{"meta":{},"body":{"children":[]}}""")))
59
- assertEquals(ErrorCode.SPEC_SHAPE, codeOf(prep("""{"meta":{},"body":"x"}""")))
60
- assertEquals(ErrorCode.SPEC_SHAPE, codeOf(prep("""{"meta":{}}""")))
61
- }
62
-
63
- // ---- shapes ----------------------------------------------------------------------------------------------------
64
- @Test fun bareSpecIsReadyWithDataAndStateSeed() {
65
- val v = ok(prep("""{"meta":{"screenName":"Blk"},"data":{"a":1},"state":{"s":true},"body":$body}"""))
66
- assertEquals("Blk", v.screenName)
67
- assertEquals(mapOf<String, Any?>("a" to 1L), v.data)
68
- assertEquals(mapOf<String, Any?>("s" to true), v.initialState)
69
- assertEquals("View", v.body["type"])
70
- }
71
-
72
- @Test fun screenNameIsOptionalAndMetaMayBeAbsent() {
73
- assertNull(ok(prep("""{"body":$body}""")).screenName)
74
- assertTrue(ok(prep("""{"body":$body}""")).data.isEmpty())
75
- }
76
-
77
- @Test fun envelopeShapedInputIsRejectedAsSpecShape() {
78
- val events = mutableListOf<String>()
79
- var errorCode: Any? = null
80
- val sink = object : TrackSink {
81
- override val id = "rec"
82
- override fun write(record: TrackRecord) {
83
- events += "${record.event.name}:${record.event.step}"
84
- if (record.event.step == "sdui_error") errorCode = record.event.fields["code"]
85
- }
86
- }
87
- val tracker = Tracker(listOf(sink), "s")
88
- var label: String? = "unset"
89
- val r = prepareSduiView("""{"v":1,"status":"ok","spec":${spec()}}""", 1) { name -> label = name; tracker.begin(SessionCtx("sdui:view:block")) }
90
- assertEquals(ErrorCode.SPEC_SHAPE, codeOf(r))
91
- assertEquals(null, label) // no top-level meta: the session gets no block name
92
- assertEquals(ErrorCode.SPEC_SHAPE, errorCode) // tracking reports the same code as onError
93
- assertEquals(listOf("ops_info_checked:sdui_error"), events.takeLast(1))
94
- }
95
-
96
- @Test fun actionTypeIsAllowedAndUnknownTypeIsNotAValidationError() {
97
- val a = """{"type":"View","actions":[{"name":"onPress","type":"startFeatureCode","params":{"featureCode":"f"}},{"name":"onPress","type":"future"}]}"""
98
- assertTrue(prep("""{"meta":{},"body":$a}""") is SduiResult.Ok)
99
- }
100
-
101
- @Test fun errorsAreReportedToTheSessionOnce() {
102
- val events = mutableListOf<String>()
103
- val sink = object : TrackSink {
104
- override val id = "rec"
105
- override fun write(record: TrackRecord) { events += "${record.event.name}:${record.event.step}" }
106
- }
107
- val tracker = Tracker(listOf(sink), "s")
108
- var begun = 0
109
- var session: RenderSession? = null
110
- prepareSduiView("{", 1) { begun++; tracker.begin(SessionCtx("sdui:view:block")).also { session = it } }
111
- assertEquals(1, begun)
112
- assertEquals(listOf("ops_info_checked:sdui_error"), events)
113
- session!!.mark("render_done") // the failed prepare ended the session: a late step is dropped
114
- assertEquals(listOf("ops_info_checked:sdui_error"), events)
115
- }
116
-
117
- // ---- the bundled blocks must be drawable ---------------------------------------------------------------------------
118
- @Test fun bundledBlocksPrepareOk() {
119
- val dir = File("../sample/shared/src/commonMain/composeResources/files/sdui/blocks")
120
- val files = listOf("buy_insurance", "pay_premium", "community").map { File(dir, "$it.json") }
121
- files.forEach { assertTrue("missing ${it.absolutePath}", it.exists()) }
122
- files.forEach { f ->
123
- val r = prep(f.readText())
124
- assertTrue("${f.name}: ${(r as? SduiResult.Err)?.error}", r is SduiResult.Ok)
125
- }
126
- }
127
-
128
- private val goodSpec = mapOf(
129
- "meta" to mapOf("screenName" to "S"),
130
- "body" to mapOf("type" to "View", "children" to listOf(mapOf("type" to "Text", "props" to mapOf("children" to "x")))),
131
- )
132
-
133
- // ---- structure validation ----------------------------------------------------------------------------------------------
134
- @Test fun structureValidationRejectsBadSpecs() {
135
- assertTrue(validateStructure(goodSpec).errors.isEmpty())
136
- assertTrue(validateStructure("x").errors.isNotEmpty())
137
- assertTrue(validateStructure(goodSpec + ("bogus" to 1L)).errors.any { "unknown top-level key" in it })
138
- // screen-level keys SduiView would silently drop are rejected
139
- listOf("header", "footer", "tabs", "onMount", "actions", "overlays", "components", "tracking", "localization").forEach { k ->
140
- assertTrue(k, validateStructure(goodSpec + (k to emptyMap<String, Any?>())).errors.any { "\"$k\" is not supported in a section" in it })
141
- }
142
- assertTrue(validateStructure(goodSpec + ("data" to emptyMap<String, Any?>()) + ("state" to emptyMap<String, Any?>()) + ("\$schema" to "x") + ("__od" to 1L)).errors.isEmpty())
143
- val noType = goodSpec + ("body" to mapOf("type" to "View", "children" to listOf(mapOf("props" to emptyMap<String, Any?>()))))
144
- assertTrue(validateStructure(noType).errors.any { "without a \"type\"" in it })
145
- fun withAction(a: Map<String, Any?>) = goodSpec + ("body" to mapOf("type" to "View", "children" to listOf(mapOf("type" to "View", "actions" to listOf(a)))))
146
- fun actionErrors(a: Map<String, Any?>) = validateStructure(withAction(a)).errors
147
- assertTrue(actionErrors(mapOf("name" to "onPress", "set" to mapOf("a" to 1L))).any { "unknown field \"set\"" in it })
148
- assertTrue(actionErrors(mapOf("name" to "onPress", "navigate" to "push")).any { "unknown field \"navigate\"" in it })
149
- assertTrue(actionErrors(mapOf("name" to "onPress", "tab" to "t")).any { "unknown field \"tab\"" in it })
150
- assertTrue(actionErrors(mapOf("name" to "onPress", "params" to mapOf("featureCode" to "f"))).any { "actions[0].type is required" in it })
151
- assertTrue(actionErrors(mapOf("name" to "onPress", "type" to 5L)).any { "type is required" in it })
152
- assertTrue(validateStructure(withAction(mapOf("name" to "onPress", "storage" to "get", "key" to "k", "to" to "x"))).errors.any { "unknown field" in it })
153
- assertTrue(actionErrors(mapOf("name" to "onPress", "type" to "startFeatureCode", "params" to mapOf("featureCode" to "f"))).isEmpty())
154
- // fields the runtime never reads
155
- listOf("code", "overlay", "trackOn").forEach { k ->
156
- assertTrue(k, actionErrors(mapOf("name" to "onPress", "type" to "setState", k to "x")).any { "unknown field \"$k\"" in it })
157
- }
158
- }
159
-
160
- @Test fun structureValidationChecksShapesTheRendererSilentlyIgnores() {
161
- fun body(vararg kv: Pair<String, Any?>) = goodSpec + ("body" to mapOf("type" to "View", *kv))
162
- fun child(vararg kv: Pair<String, Any?>) = body("children" to listOf(mapOf("type" to "View", *kv)))
163
- val press = mapOf("name" to "onPress", "type" to "setState", "params" to mapOf("a" to 1L))
164
- // actions must be a list
165
- assertTrue(validateStructure(child("actions" to press)).errors.any { "body.children[0].actions must be a list of actions" in it })
166
- assertTrue(validateStructure(body("actions" to press)).errors.any { "body.actions must be a list of actions" in it })
167
- assertTrue(validateStructure(child("actions" to listOf(press))).errors.isEmpty())
168
- // children must be a list of nodes
169
- val textChildren = "children must be a list of nodes; put text in props.children"
170
- assertTrue(validateStructure(child("children" to "hello")).errors.any { "body.children[0].$textChildren" in it })
171
- assertTrue(validateStructure(body("children" to mapOf("type" to "Text"))).errors.any { "body.$textChildren" in it })
172
- // repeat: `as` names the item, `item` is not read
173
- val rep = mapOf("source" to "{xs}", "as" to "x", "index" to "i")
174
- assertTrue(validateStructure(child("repeat" to rep)).errors.isEmpty())
175
- assertTrue(validateStructure(child("repeat" to mapOf("source" to "{xs}", "item" to "x"))).errors.any { "unknown field \"item\" at body.children[0].repeat" in it })
176
- // styles only: a singular `style` is unknown on nodes and on body
177
- assertTrue(validateStructure(child("styles" to mapOf("flex" to 1L))).errors.isEmpty())
178
- assertTrue(validateStructure(child("style" to mapOf("flex" to 1L))).errors.any { "unknown field \"style\"" in it })
179
- assertTrue(validateStructure(body("style" to mapOf("flex" to 1L))).errors.any { "unknown field \"style\" at body" in it })
180
- // body is drawn once, directly: repeat / visible / visibleWhen / scrollable would be silently ignored, so they are rejected there only
181
- listOf("repeat" to mapOf("source" to "{xs}", "as" to "x"), "visible" to false, "visibleWhen" to "{a}").forEach { (k, v) ->
182
- assertEquals(k, listOf("body.$k is not supported: the block body is always drawn once"), validateStructure(body(k to v)).errors)
183
- assertTrue(k, validateStructure(child(k to v)).errors.isEmpty())
184
- }
185
- assertEquals(listOf("unknown field \"scrollable\" at body"), validateStructure(body("scrollable" to true)).errors)
186
- // meta: stamp / autoShow are not read by SduiView; root (editor marker) / version / description are accepted and ignored
187
- fun withMeta(k: String) = goodSpec + ("meta" to mapOf(k to true))
188
- listOf("stamp", "autoShow").forEach { k ->
189
- assertTrue(k, validateStructure(withMeta(k)).errors.any { "unknown field \"$k\" at meta" in it })
190
- }
191
- listOf("root", "version", "description").forEach { k -> assertTrue(k, validateStructure(withMeta(k)).errors.isEmpty()) }
192
- // nesting depth: 100 levels below body pass, 101 fail with one error
193
- fun nested(levels: Int): Map<String, Any?> {
194
- var n: Map<String, Any?> = mapOf("type" to "View")
195
- repeat(levels - 1) { n = mapOf("type" to "View", "children" to listOf(n)) }
196
- return n
197
- }
198
- assertTrue(validateStructure(body("children" to listOf(nested(100)))).errors.isEmpty())
199
- val deep = validateStructure(body("children" to listOf(nested(5000)))).errors
200
- assertEquals(1, deep.count { "spec nested too deeply" in it })
201
- }
202
-
203
- // ---- utf8Length / parse timing ---------------------------------------------------------------------------------------
204
- @Test fun deeplyNestedJsonIsRejectedBeforeParsing() {
205
- assertEquals(3, jsonNestingDepth("""{"a":[{"b":1}]}"""))
206
- assertEquals(1, jsonNestingDepth("""{"a":"[[[{{{\"]]]"}""")) // brackets inside strings (and escaped quotes) don't count
207
- assertEquals(0, jsonNestingDepth("""]]]}}"""))
208
- // 120k levels fits the size gate but would overflow the parser's stack (fatal on iOS): rejected as PARSE without parsing
209
- val deep = "[".repeat(120_000) + "]".repeat(120_000)
210
- assertEquals(ErrorCode.PARSE, codeOf(prep(deep)))
211
- val ok = """{"meta":{},"body":{"type":"View","props":{"d":""" + "[".repeat(200) + "]".repeat(200) + "}}}"
212
- assertTrue(prep(ok) is SduiResult.Ok)
213
- }
214
-
215
- @Test fun utf8LengthMatchesEncodeToByteArray() {
216
- val cases = listOf("", "plain ascii {\"a\":1}", "Phí bảo hiểm sức khỏe Việt Nam đ", "emoji \uD83D\uDE00 \uD83C\uDDFB\uD83C\uDDF3 end", "中文 \u20AC")
217
- cases.forEach { assertEquals(it, it.encodeToByteArray().size, utf8Length(it)) }
218
- }
219
-
220
- // An unpaired surrogate counts 3 bytes (U+FFFD, what Kotlin/Native's encoder writes); the JVM encoder writes 1 ('?').
221
- @Test fun utf8LengthCountsAnUnpairedSurrogateAsThree() {
222
- assertEquals(3, utf8Length("\uD83D")); assertEquals(3, utf8Length("\uDE00"))
223
- assertEquals(3 + 1, utf8Length("\uD83Dx")); assertEquals(3 + 3, utf8Length("\uDE00\uD83D"))
224
- assertEquals(4, utf8Length("\uD83D\uDE00"))
225
- }
226
-
227
- @Test fun parseDurationIsMeasuredAroundParsingAndPassedToTheSession() {
228
- var t = 100L
229
- val clock = { val v = t; t += 7; v }
230
- val marks = ArrayList<Triple<String, Map<String, Any?>?, Long?>>()
231
- val rec = object : RenderSession by RenderSession.NOOP {
232
- override fun mark(step: String, extra: Map<String, Any?>?, durationMs: Long?) { marks += Triple(step, extra, durationMs) }
233
- }
234
- val r = prepareSduiView(spec(), 1, nowMs = clock) { rec }
235
- assertTrue(r is SduiResult.Ok)
236
- val parse = marks.single { it.first == "sdui_parse" }
237
- assertEquals(7L, parse.third)
238
- assertEquals(true, parse.second!!["ok"])
239
- }
240
-
241
- @Test fun realSessionUsesTheSuppliedParseDuration() {
242
- val sink = object : TrackSink {
243
- override val id = "rec"
244
- val records = ArrayList<TrackRecord>()
245
- override fun write(record: TrackRecord) { records += record }
246
- }
247
- val s = Tracker(listOf(sink), "sess").begin(SessionCtx("sdui:view:t"))
248
- s.mark("sdui_parse", mapOf("ok" to true), durationMs = 42L)
249
- assertEquals(42L, sink.records.single().event.fields["duration"])
250
- }
251
- }
252
- // AI-GENERATED END: unit tests for SduiView's pure part
@@ -1,154 +0,0 @@
1
- // File: compose/src/commonMain/kotlin/vn/momo/kits/sdui/SduiActions.kt
2
- // Created At: 2026-10-27 12: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.snapshots.SnapshotStateMap
10
- import vn.momo.kits.const.Theme
11
- import vn.momo.maxapi.IMaxApi
12
-
13
- // AI-GENERATED START: SDUI action runner
14
- internal val FEATURE_CODE_RE = Regex("^[A-Za-z0-9_][A-Za-z0-9_./-]*$")
15
- internal val EVENT_NAME_RE = Regex("^[A-Za-z][A-Za-z0-9_]{0,63}$")
16
- internal val EVENT_PARAM_KEY_RE = Regex("^[A-Za-z_][A-Za-z0-9_]{0,63}$")
17
-
18
- /**
19
- * One view's handle on the host's MaxApi (the calls the renderer makes). [SduiView] resolves the api per view
20
- * (`maxApi` parameter, else `LocalMaxApi`), so views never share or overwrite each other's api. With no api bound
21
- * (or a throwing call) a call does nothing and reports nothing: reporting would recurse into [logFile].
22
- */
23
- internal class SduiMaxApi(private val resolve: () -> IMaxApi?) {
24
- private fun <T> withApi(call: (IMaxApi) -> T): T? {
25
- val api = resolve() ?: return null
26
- return runCatching { call(api) }.getOrNull()
27
- }
28
-
29
- fun startFeatureCode(featureCode: String, params: Map<String, Any>) {
30
- withApi { api -> api.startFeatureCode(featureCode, params) { } }
31
- }
32
-
33
- fun track(name: String, params: Map<String, Any>) {
34
- withApi { api -> api.track(name, params) { } }
35
- }
36
-
37
- /** Appends a line to the device log file. */
38
- fun logFile(message: String) {
39
- withApi { api -> api.logFile(message) { } }
40
- }
41
-
42
- companion object {
43
- /** No api (tests / helpers called without a view). */
44
- val NONE = SduiMaxApi({ null })
45
- }
46
- }
47
-
48
- /** The api [SduiView] uses: the `maxApi` parameter, else the kits' `LocalMaxApi` (provided by NavigationContainer). */
49
- internal fun pickMaxApi(param: IMaxApi?, kitLocal: IMaxApi?): IMaxApi? = param ?: kitLocal
50
-
51
- internal class SduiActionRunner(
52
- private val state: SnapshotStateMap<String, Any?>,
53
- private val theme: () -> Theme,
54
- private val session: () -> RenderSession = { RenderSession.NOOP },
55
- /** This view's MaxApi handle and error sink (warnings). */
56
- private val maxApi: SduiMaxApi = SduiMaxApi.NONE,
57
- private val log: SduiLog = SduiLog.NONE,
58
- /** Keys of the spec's top-level `state`: the only ones typed `setState` may write. `null` = unrestricted. */
59
- private val declaredState: Set<String>? = null,
60
- ) {
61
- private fun logW(path: String, msg: String) = log.w(if (path.isEmpty()) msg else "$path: $msg")
62
-
63
- /** The warning's `sdui_node_error` twin (code `invalid_action`): the logFile line and the tracking event both happen. */
64
- private fun invalid(reason: String, path: String, nodeId: String?, nodeType: String?) =
65
- session().nodeError("invalid_action", reason, path, nodeType, nodeId)
66
-
67
- private fun actionHasCode(a: Any?): Boolean {
68
- val m = a.asMap() ?: return false
69
- return m["code"] is String
70
- }
71
-
72
- /** Actions sharing a `name` run in spec order. */
73
- fun run(actions: List<Any?>?, name: String, scope: SduiScope, callArgs: List<Any?>, path: String = "", nodeId: String? = null, nodeType: String? = null) {
74
- actions.orEmpty().mapNotNull { it.asMap() }.filter { it["name"] == name }.forEach { runOne(it, scope, callArgs, path, nodeId, nodeType) }
75
- }
76
-
77
- /** [scope] is the node's render scope (repeat locals included); state is a live snapshot map, so it reads current values. */
78
- fun runOne(action: Map<String, Any?>, scope: SduiScope, callArgs: List<Any?>, path: String = "", nodeId: String? = null, nodeType: String? = null) {
79
- try {
80
- runUnsafe(action, scope, callArgs, path, nodeId, nodeType)
81
- } catch (e: Throwable) {
82
- // an unexpected throw abandons this action; the report itself must not escape either
83
- runCatching { logW(path, "action error") }
84
- runCatching { invalid("action_error", path, nodeId, nodeType) }
85
- }
86
- }
87
-
88
- private fun runUnsafe(action: Map<String, Any?>, scope: SduiScope, callArgs: List<Any?>, path: String, nodeId: String?, nodeType: String?) {
89
- if (actionHasCode(action)) return logW(path, "action skipped: carries `code` (never executed)")
90
- if (!action.containsKey("type")) {
91
- invalid("missing_type", path, nodeId, nodeType)
92
- return logW(path, "action skipped: missing type")
93
- }
94
- var sc = scope.with("args", callArgs)
95
- (action["args"].asList().orEmpty()).forEachIndexed { i, n -> if (n is String) sc = sc.with(n, callArgs.getOrNull(i)) }
96
- val whenExpr = action["when"]
97
- if (whenExpr != null && !truthy(if (whenExpr is String) resolveString(whenExpr, sc) else whenExpr)) return
98
- val params = resolveValue(action["params"] ?: emptyMap<String, Any?>(), sc, theme()).asMap().orEmpty()
99
-
100
- // a whole-binding `params` gets its keys from data: name no key in the log then
101
- runTyped(action["type"], params, path, nodeId, nodeType, keysFromData = action["params"] is String)
102
- }
103
-
104
- /** Forward compatible: a `type` this app does not know is skipped (and reported), never an error. */
105
- private fun runTyped(type: Any?, params: Map<String, Any?>, path: String, nodeId: String?, nodeType: String?, keysFromData: Boolean) {
106
- fun key(k: String) = if (keysFromData) "(from binding)" else "'$k'"
107
- when (type) {
108
- "startFeatureCode" -> {
109
- val featureCode = params["featureCode"]
110
- if (featureCode !is String || !FEATURE_CODE_RE.matches(featureCode)) {
111
- invalid("invalid_feature_code", path, nodeId, nodeType)
112
- return logW(path, "startFeatureCode: invalid featureCode")
113
- }
114
- val rest = params.filterKeys { it != "featureCode" }
115
- maxApi.startFeatureCode(featureCode, rest.filterValues { it != null }.mapValues { it.value!! })
116
- }
117
- "trackEvent" -> {
118
- val eventName = params["eventName"]
119
- if (eventName !is String || !EVENT_NAME_RE.matches(eventName)) {
120
- invalid("invalid_event_name", path, nodeId, nodeType)
121
- return logW(path, "trackEvent: invalid eventName")
122
- }
123
- if (eventName.equals(OPS_INFO_CHECKED, ignoreCase = true)) {
124
- invalid("reserved_event_name", path, nodeId, nodeType)
125
- return logW(path, "trackEvent: reserved eventName")
126
- }
127
- // several bad params on one node: one `invalid_param` event (the session dedupes per node path / code / reason), one log line each
128
- val clean = LinkedHashMap<String, Any>()
129
- params.forEach { (k, v) ->
130
- if (k == "eventName" || v == null) return@forEach
131
- if (!EVENT_PARAM_KEY_RE.matches(k)) return@forEach run { invalid("invalid_param", path, nodeId, nodeType); logW(path, "trackEvent: dropped param ${key(k)} (invalid key)") }
132
- when {
133
- v is Double && !v.isFinite() || v is Float && !v.isFinite() -> { invalid("invalid_param", path, nodeId, nodeType); logW(path, "trackEvent: dropped param ${key(k)} (not a finite number)") }
134
- v is String || v is Number || v is Boolean -> clean[k] = v
135
- else -> { invalid("invalid_param", path, nodeId, nodeType); logW(path, "trackEvent: dropped param ${key(k)} (unsupported value type)") }
136
- }
137
- }
138
- maxApi.track(eventName, clean)
139
- }
140
- "setState" -> {
141
- // params are already resolved, so every value was computed before the first write
142
- params.forEach { (k, v) ->
143
- if (declaredState != null && k !in declaredState) return@forEach run { invalid("state_not_declared", path, nodeId, nodeType); logW(path, "setState: ${key(k)} is not declared in state") }
144
- state[k] = v
145
- }
146
- }
147
- else -> {
148
- logW(path, "action skipped: unknown type '$type'")
149
- invalid("unknown_type", path, nodeId, nodeType)
150
- }
151
- }
152
- }
153
- }
154
- // AI-GENERATED END: SDUI action runner