@onekeyfe/react-native-native-list 6.7.0-4 → 6.7.0-41

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 (214) hide show
  1. package/README.md +4 -0
  2. package/android/src/main/java/com/onekey/nativelist/HybridNativeList.kt +14 -1
  3. package/android/src/main/java/com/onekey/nativelist/NativeListAccessoryStack.kt +250 -9
  4. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +35 -7
  5. package/android/src/main/java/com/onekey/nativelist/NativeListActivityRenderer.kt +25 -3
  6. package/android/src/main/java/com/onekey/nativelist/NativeListAdapter.kt +17 -1
  7. package/android/src/main/java/com/onekey/nativelist/NativeListButtonGroupRenderer.kt +102 -0
  8. package/android/src/main/java/com/onekey/nativelist/NativeListContainerSlotAdapter.kt +12 -0
  9. package/android/src/main/java/com/onekey/nativelist/NativeListDataRowRenderer.kt +102 -7
  10. package/android/src/main/java/com/onekey/nativelist/NativeListGeneratedIcons.kt +47 -0
  11. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +225 -11
  12. package/android/src/main/java/com/onekey/nativelist/NativeListLeadingVisual.kt +152 -33
  13. package/android/src/main/java/com/onekey/nativelist/NativeListMarketRenderer.kt +92 -28
  14. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPlaceholderView.kt +244 -0
  15. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPreviewSlot.kt +66 -31
  16. package/android/src/main/java/com/onekey/nativelist/NativeListMediaTileRenderer.kt +32 -11
  17. package/android/src/main/java/com/onekey/nativelist/NativeListMessageRenderer.kt +25 -0
  18. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +149 -3
  19. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +120 -287
  20. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRegistry.kt +2 -0
  21. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRowView.kt +7 -0
  22. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +3 -2
  23. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  24. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +55 -1
  25. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +1953 -117
  26. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListActivityHostClipPolicyTest.kt +35 -0
  27. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListIdentityTrailingAxisTest.kt +36 -0
  28. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingSlotFrameTest.kt +68 -0
  29. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  30. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +10 -0
  31. package/docs/ROW_TEMPLATES.md +74 -13
  32. package/docs/SPEC.md +1206 -15
  33. package/docs/STYLE_SPEC.md +14 -0
  34. package/ios/HybridNativeList.swift +21 -2
  35. package/ios/NativeListAccessoryStack.swift +237 -51
  36. package/ios/NativeListActivityDetailsView.swift +30 -11
  37. package/ios/NativeListActivityRenderer.swift +8 -2
  38. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  39. package/ios/NativeListDataRowRenderer.swift +167 -30
  40. package/ios/NativeListDesignAssets.swift +13 -75
  41. package/ios/NativeListGeneratedIcons.swift +55 -0
  42. package/ios/NativeListIconBinding.swift +171 -0
  43. package/ios/NativeListIdentityRenderer.swift +256 -39
  44. package/ios/NativeListLeadingVisual.swift +127 -28
  45. package/ios/NativeListMarketRenderer.swift +120 -31
  46. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  47. package/ios/NativeListMediaPreviewSlot.swift +122 -61
  48. package/ios/NativeListMediaTileRenderer.swift +15 -11
  49. package/ios/NativeListMessageRenderer.swift +34 -1
  50. package/ios/NativeListMetricCardRenderer.swift +4 -2
  51. package/ios/NativeListModels.swift +42 -2
  52. package/ios/NativeListRendererRegistry.swift +1 -0
  53. package/ios/NativeListResolvedText.swift +2 -1
  54. package/ios/NativeListRowHost.swift +14 -0
  55. package/ios/NativeListSectionHeaderRenderer.swift +100 -4
  56. package/ios/RNCNativeListView.swift +1053 -58
  57. package/ios/tests/NativeListAccessoryStackTests.swift +101 -0
  58. package/ios/tests/NativeListAccountSelectorLayoutTests.swift +96 -0
  59. package/ios/tests/NativeListActivityPresentationTests.swift +153 -0
  60. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +81 -0
  61. package/ios/tests/NativeListLeadingVisualPairBackdropTests.swift +50 -0
  62. package/ios/tests/NativeListLifecycleTests.swift +2819 -3
  63. package/ios/tests/NativeListMarketMetricsTests.swift +117 -0
  64. package/ios/tests/NativeListMediaVisibilityTests.swift +26 -1
  65. package/ios/tests/NativeListSharedIconTests.swift +236 -0
  66. package/lib/module/NativeList.js +221 -36
  67. package/lib/module/NativeList.web.js +167 -46
  68. package/lib/module/index.js +1 -1
  69. package/lib/module/models.js +3 -0
  70. package/lib/module/selection.js +1 -1
  71. package/lib/module/validation.js +1246 -48
  72. package/lib/module/web/NativeListGeneratedIcons.js +31 -0
  73. package/lib/module/web/NativeListWebEngine.js +513 -275
  74. package/lib/module/web/templates/ActivityRowRenderer.js +120 -87
  75. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  76. package/lib/module/web/templates/DataRowRenderer.js +40 -5
  77. package/lib/module/web/templates/IdentityRowRenderer.js +158 -6
  78. package/lib/module/web/templates/MarketTableRowRenderer.js +36 -19
  79. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -25
  80. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  81. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  82. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  83. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  84. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  85. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  86. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  87. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  88. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  89. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  90. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  91. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  92. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  93. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  94. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  95. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  96. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  97. package/lib/typescript/src/NativeList.d.ts +3 -3
  98. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  99. package/lib/typescript/src/NativeList.types.d.ts +20 -2
  100. package/lib/typescript/src/index.d.ts +2 -2
  101. package/lib/typescript/src/models.d.ts +126 -17
  102. package/lib/typescript/src/validation.d.ts +20 -0
  103. package/lib/typescript/src/web/NativeListGeneratedIcons.d.ts +2 -0
  104. package/lib/typescript/src/web/NativeListWebEngine.d.ts +32 -1
  105. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  106. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  107. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  108. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  109. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  110. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  111. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  112. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  113. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  114. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  115. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  116. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  117. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  118. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  119. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  120. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  121. package/package.json +16 -10
  122. package/react-native-native-list.podspec +2 -6
  123. package/scripts/generate-icons.mjs +150 -0
  124. package/scripts/generate-icons.test.mjs +288 -0
  125. package/scripts/native-list-icons.json +260 -0
  126. package/src/NativeList.nitro.ts +2 -0
  127. package/src/NativeList.tsx +416 -89
  128. package/src/NativeList.types.ts +24 -2
  129. package/src/NativeList.web.tsx +295 -89
  130. package/src/index.ts +2 -0
  131. package/src/models.ts +263 -144
  132. package/src/selection.ts +1 -0
  133. package/src/validation.ts +3013 -152
  134. package/src/web/NativeListGeneratedIcons.ts +28 -0
  135. package/src/web/NativeListWebEngine.ts +818 -343
  136. package/src/web/templates/ActivityRowRenderer.ts +178 -141
  137. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  138. package/src/web/templates/DataRowRenderer.ts +93 -20
  139. package/src/web/templates/IdentityRowRenderer.ts +231 -6
  140. package/src/web/templates/MarketTableRowRenderer.ts +53 -33
  141. package/src/web/templates/MediaTileRowRenderer.ts +90 -28
  142. package/src/web/templates/MessageRowRenderer.ts +23 -7
  143. package/src/web/templates/RowContainerStyle.ts +2 -0
  144. package/src/web/templates/RowRendererRegistry.ts +11 -1
  145. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
  146. package/ios/Resources/NativeListIcons.xcassets/Contents.json +0 -1
  147. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/Contents.json +0 -1
  148. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/icon.svg +0 -1
  149. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/Contents.json +0 -1
  150. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/icon.svg +0 -1
  151. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/Contents.json +0 -1
  152. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/icon.svg +0 -1
  153. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/Contents.json +0 -1
  154. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/icon.svg +0 -1
  155. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/Contents.json +0 -1
  156. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/icon.svg +0 -1
  157. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/Contents.json +0 -1
  158. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/icon.svg +0 -1
  159. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/Contents.json +0 -1
  160. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/icon.svg +0 -1
  161. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/Contents.json +0 -1
  162. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/icon.svg +0 -1
  163. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/Contents.json +0 -1
  164. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/icon.svg +0 -1
  165. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/Contents.json +0 -1
  166. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/icon.svg +0 -1
  167. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/Contents.json +0 -1
  168. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/icon.svg +0 -1
  169. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/Contents.json +0 -1
  170. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/icon.svg +0 -1
  171. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/Contents.json +0 -1
  172. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/icon.svg +0 -1
  173. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/Contents.json +0 -1
  174. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/icon.svg +0 -1
  175. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/Contents.json +0 -1
  176. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/icon.svg +0 -1
  177. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/Contents.json +0 -1
  178. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/icon.svg +0 -1
  179. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/Contents.json +0 -1
  180. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/icon.svg +0 -1
  181. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/Contents.json +0 -1
  182. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/icon.svg +0 -1
  183. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/Contents.json +0 -1
  184. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/icon.svg +0 -1
  185. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/Contents.json +0 -1
  186. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/icon.svg +0 -1
  187. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/Contents.json +0 -1
  188. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/icon.svg +0 -1
  189. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/Contents.json +0 -15
  190. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/icon.svg +0 -14
  191. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/Contents.json +0 -15
  192. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/icon.svg +0 -12
  193. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/Contents.json +0 -15
  194. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/icon.svg +0 -6
  195. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/Contents.json +0 -15
  196. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/icon.svg +0 -15
  197. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/Contents.json +0 -15
  198. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/icon.svg +0 -3
  199. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/Contents.json +0 -15
  200. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/icon.svg +0 -7
  201. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/Contents.json +0 -15
  202. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/icon.svg +0 -18
  203. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/Contents.json +0 -15
  204. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/icon.svg +0 -7
  205. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/Contents.json +0 -1
  206. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/icon.svg +0 -1
  207. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/Contents.json +0 -1
  208. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/icon.svg +0 -1
  209. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/Contents.json +0 -1
  210. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/icon.svg +0 -1
  211. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/Contents.json +0 -1
  212. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/icon.svg +0 -1
  213. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/Contents.json +0 -1
  214. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/icon.svg +0 -1
package/src/validation.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { ROW_BOX_STYLE_KEYS_BY_TYPE } from './models';
2
2
  import type {
3
3
  ActivityRow,
4
+ ButtonGroupRow,
4
5
  IdentityRow,
5
6
  ImageSource,
6
7
  LeadingVisual,
@@ -13,10 +14,12 @@ import type {
13
14
  RowBoxStyle,
14
15
  RowModel,
15
16
  RowPatch,
17
+ RowTextHelp,
16
18
  WalletGroupRow,
17
19
  WebMarketTableCell,
18
20
  WebMarketTablePresentation,
19
21
  WebMarketTableText,
22
+ ValueTextSegment,
20
23
  } from './models';
21
24
 
22
25
  const MAX_KEY_LENGTH = 256;
@@ -30,21 +33,68 @@ const MAX_HEADER_LENGTH = 4096;
30
33
  const MAX_SPACER_HEIGHT = 512;
31
34
  const MAX_SECTION_INDEX_TITLE_LENGTH = 8;
32
35
  const MAX_MARKET_BADGES = 3;
36
+ const MARKET_METRIC_FIELDS = [
37
+ 'key',
38
+ 'text',
39
+ 'textSegments',
40
+ 'secondaryText',
41
+ 'secondaryTextSegments',
42
+ 'weight',
43
+ 'alignment',
44
+ 'tone',
45
+ 'secondaryTone',
46
+ ] as const;
47
+
48
+ function isDevelopment(): boolean {
49
+ return typeof __DEV__ !== 'undefined' && __DEV__;
50
+ }
51
+
52
+ class NativeListInputError extends Error {
53
+ constructor(readonly path: string, readonly reason: string) {
54
+ super(`NativeList ${path}: ${reason}`);
55
+ }
56
+ }
33
57
 
34
58
  function fail(path: string, message: string): never {
35
- throw new Error(`NativeList ${path}: ${message}`);
59
+ throw new NativeListInputError(path, message);
60
+ }
61
+
62
+ /** Component boundaries report locations, never caller-controlled payload values. */
63
+ export function containNativeListInput<T>(operation: () => T): T | undefined {
64
+ try {
65
+ return operation();
66
+ } catch (error) {
67
+ const path = error instanceof NativeListInputError ? error.path : 'input';
68
+ const reason =
69
+ isDevelopment() && error instanceof NativeListInputError
70
+ ? `: ${error.reason.split('"')[0].trim()}`
71
+ : '';
72
+ console.warn(`NativeList rejected invalid input at ${path}${reason}`);
73
+ return undefined;
74
+ }
75
+ }
76
+
77
+ export function emptyNativeListSnapshot(): NativeListSnapshot {
78
+ return {
79
+ schemaVersion: 1,
80
+ generation: 0,
81
+ layout: { kind: 'linear' },
82
+ rows: [],
83
+ };
36
84
  }
37
85
 
38
86
  function assertPlainSerializable(
39
87
  value: unknown,
40
88
  path: string,
41
- seen: Set<object>
89
+ seen: Set<object>,
90
+ requireFinite = true
42
91
  ): void {
43
92
  if (value === null || value === undefined) return;
44
93
  const valueType = typeof value;
45
94
  if (valueType === 'string' || valueType === 'boolean') return;
46
95
  if (valueType === 'number') {
47
- if (!Number.isFinite(value)) fail(path, 'numbers must be finite');
96
+ if (requireFinite && !Number.isFinite(value))
97
+ fail(path, 'numbers must be finite');
48
98
  return;
49
99
  }
50
100
  if (valueType !== 'object')
@@ -55,16 +105,21 @@ function assertPlainSerializable(
55
105
  seen.add(objectValue);
56
106
  if (Array.isArray(value)) {
57
107
  value.forEach((item, index) =>
58
- assertPlainSerializable(item, `${path}[${index}]`, seen)
108
+ assertPlainSerializable(item, `${path}[${index}]`, seen, requireFinite)
59
109
  );
60
110
  } else {
61
111
  const prototype = Object.getPrototypeOf(value);
62
112
  if (prototype !== Object.prototype && prototype !== null) {
63
113
  fail(path, 'must contain plain objects only');
64
114
  }
65
- Object.entries(value as Record<string, unknown>).forEach(([key, item]) =>
66
- assertPlainSerializable(item, `${path}.${key}`, seen)
67
- );
115
+ Object.entries(value as Record<string, unknown>).forEach(([key, item]) => {
116
+ if (
117
+ key === '__proto__' ||
118
+ (key === 'constructor' && typeof item === 'object')
119
+ )
120
+ fail(path, 'unsafe object key');
121
+ assertPlainSerializable(item, `${path}.${key}`, seen, requireFinite);
122
+ });
68
123
  }
69
124
  seen.delete(objectValue);
70
125
  }
@@ -72,16 +127,14 @@ function assertPlainSerializable(
72
127
  function assertKey(key: string, path: string): void {
73
128
  if (
74
129
  typeof key !== 'string' ||
75
- key.length === 0 ||
130
+ key.trim().length === 0 ||
76
131
  key.length > MAX_KEY_LENGTH
77
132
  ) {
78
133
  fail(
79
134
  path,
80
- `must be a non-empty string no longer than ${MAX_KEY_LENGTH} characters`
135
+ `must be a non-blank string no longer than ${MAX_KEY_LENGTH} characters`
81
136
  );
82
137
  }
83
- if (key.trim() !== key)
84
- fail(path, 'must not have leading or trailing whitespace');
85
138
  }
86
139
 
87
140
  function assertText(text: string | undefined, path: string): void {
@@ -188,12 +241,14 @@ const TEXT_STYLE_KEYS_BY_ROW_TYPE: Readonly<
188
241
  metricCard: ['title', 'value', 'subtitle', 'trend'],
189
242
  sectionHeader: ['title', 'subtitle', 'value'],
190
243
  action: ['title', 'value'],
244
+ buttonGroup: [],
191
245
  system: ['title', 'message', 'actionText'],
192
246
  };
193
247
 
194
248
  const EXTRA_STYLE_KEYS_BY_ROW_TYPE: Readonly<
195
249
  Partial<Record<RowModel['type'], readonly string[]>>
196
250
  > = {
251
+ identity: ['leadingContentMaxWidthRatio'],
197
252
  market: [
198
253
  'titleBadgeLayout',
199
254
  'contentTrailingGap',
@@ -202,6 +257,7 @@ const EXTRA_STYLE_KEYS_BY_ROW_TYPE: Readonly<
202
257
  'changeHeight',
203
258
  'changeCornerRadius',
204
259
  ],
260
+ sectionHeader: ['valuePlacement', 'titleDecoration'],
205
261
  };
206
262
 
207
263
  function assertTextStyle(
@@ -460,6 +516,33 @@ function assertRowStyle(row: RowModel, path: string): void {
460
516
  // Market keeps its own richer assertions, driven from assertMarketRow.
461
517
  if (row.type === 'market') return;
462
518
  assertBoxStyle(style as RowBoxStyle, `${path}.style`);
519
+ if (row.type === 'identity') {
520
+ const ratio = (style as IdentityRow['style'])?.leadingContentMaxWidthRatio;
521
+ if (
522
+ ratio !== undefined &&
523
+ (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1)
524
+ )
525
+ fail(
526
+ `${path}.style.leadingContentMaxWidthRatio`,
527
+ 'must be within (0, 1]'
528
+ );
529
+ }
530
+ if (row.type === 'sectionHeader') {
531
+ const sectionStyle = style as Extract<
532
+ RowModel,
533
+ { type: 'sectionHeader' }
534
+ >['style'];
535
+ if (
536
+ sectionStyle?.valuePlacement !== undefined &&
537
+ sectionStyle.valuePlacement !== 'afterTitle'
538
+ )
539
+ fail(`${path}.style.valuePlacement`, 'must be afterTitle');
540
+ if (
541
+ sectionStyle?.titleDecoration !== undefined &&
542
+ !['none', 'dashed'].includes(sectionStyle.titleDecoration)
543
+ )
544
+ fail(`${path}.style.titleDecoration`, 'must be none or dashed');
545
+ }
463
546
  const slots = style as Record<string, NativeListTextStyle | undefined>;
464
547
  textKeys.forEach((key) =>
465
548
  assertTextStyle(slots[key], `${path}.style.${key}`)
@@ -911,8 +994,88 @@ function assertWebMarketTable(
911
994
  });
912
995
  }
913
996
 
997
+ function assertMarketMetrics(
998
+ metrics: MarketRow['metrics'],
999
+ path: string
1000
+ ): void {
1001
+ if (metrics === undefined) return;
1002
+ if (!Array.isArray(metrics) || ![2, 3].includes(metrics.length))
1003
+ fail(path, 'must contain 2 or 3 columns');
1004
+ const keys = new Set<string>();
1005
+ metrics.forEach(
1006
+ (column: NonNullable<MarketRow['metrics']>[number], index: number) => {
1007
+ const columnPath = `${path}[${index}]`;
1008
+ const value = protocolObject(column, columnPath);
1009
+ protocolKey(value.key, `${columnPath}.key`);
1010
+ if (keys.has(column.key)) fail(`${columnPath}.key`, 'must be unique');
1011
+ keys.add(column.key);
1012
+ if (typeof value.text !== 'string')
1013
+ fail(`${columnPath}.text`, 'must be a string');
1014
+ for (const field of ['textSegments', 'secondaryTextSegments'] as const) {
1015
+ const segments = column[field];
1016
+ if (segments !== undefined && !Array.isArray(segments))
1017
+ fail(`${columnPath}.${field}`, 'must be an array');
1018
+ segments?.forEach((segment: ValueTextSegment, segmentIndex: number) => {
1019
+ const segmentPath = `${columnPath}.${field}[${segmentIndex}]`;
1020
+ protocolObject(segment, segmentPath);
1021
+ if (typeof segment.text !== 'string')
1022
+ fail(`${segmentPath}.text`, 'must be a string');
1023
+ if (segment.style !== undefined && segment.style !== 'subscript')
1024
+ fail(`${segmentPath}.style`, 'must be subscript');
1025
+ });
1026
+ }
1027
+ if (
1028
+ value.weight !== undefined &&
1029
+ ![1, 2, 3].includes(value.weight as number)
1030
+ )
1031
+ fail(`${columnPath}.weight`, 'must be 1, 2, or 3');
1032
+ if (
1033
+ value.alignment !== undefined &&
1034
+ !['start', 'center', 'end'].includes(value.alignment as string)
1035
+ )
1036
+ fail(`${columnPath}.alignment`, 'must be start, center, or end');
1037
+ if (
1038
+ value.secondaryText !== undefined &&
1039
+ typeof value.secondaryText !== 'string'
1040
+ )
1041
+ fail(`${columnPath}.secondaryText`, 'must be a string');
1042
+ assertTextTone(value.tone as string | undefined, `${columnPath}.tone`);
1043
+ assertTextTone(
1044
+ value.secondaryTone as string | undefined,
1045
+ `${columnPath}.secondaryTone`
1046
+ );
1047
+ }
1048
+ );
1049
+ }
1050
+
914
1051
  function assertMarketRow(row: MarketRow, path: string): void {
915
1052
  assertWebMarketTable(row.webTable, `${path}.webTable`);
1053
+ assertMarketMetrics(row.metrics, `${path}.metrics`);
1054
+ if (row.metrics !== undefined) {
1055
+ row.metrics.forEach((column, index) => {
1056
+ const columnPath = `${path}.metrics[${index}]`;
1057
+ const value = protocolObject(column, columnPath);
1058
+ assertUnknownKeys(
1059
+ value,
1060
+ MARKET_METRIC_FIELDS,
1061
+ columnPath,
1062
+ 'Market metric key'
1063
+ );
1064
+ assertKey(column.key, `${columnPath}.key`);
1065
+ assertText(column.text, `${columnPath}.text`);
1066
+ assertText(column.secondaryText, `${columnPath}.secondaryText`);
1067
+ assertTextTone(column.tone, `${columnPath}.tone`);
1068
+ assertTextTone(column.secondaryTone, `${columnPath}.secondaryTone`);
1069
+ for (const field of ['textSegments', 'secondaryTextSegments'] as const) {
1070
+ column[field]?.forEach((segment, segmentIndex) => {
1071
+ const segmentPath = `${columnPath}.${field}[${segmentIndex}]`;
1072
+ assertText(segment.text, `${segmentPath}.text`);
1073
+ if (segment.style !== undefined && segment.style !== 'subscript')
1074
+ fail(`${segmentPath}.style`, 'must be subscript');
1075
+ });
1076
+ }
1077
+ });
1078
+ }
916
1079
  if (!['token', 'stock', 'perp'].includes(row.variant)) {
917
1080
  fail(`${path}.variant`, 'must be token, stock, or perp');
918
1081
  }
@@ -1017,6 +1180,55 @@ function assertTrailingAccessories(
1017
1180
  ): void {
1018
1181
  accessories?.forEach((accessory, index) => {
1019
1182
  const accessoryPath = `${path}[${index}]`;
1183
+ if (accessory.kind === 'button') {
1184
+ assertUnknownKeys(
1185
+ accessory as Record<string, unknown>,
1186
+ [
1187
+ 'kind',
1188
+ 'label',
1189
+ 'actionKey',
1190
+ 'disabled',
1191
+ 'testID',
1192
+ 'accessibilityLabel',
1193
+ 'textColor',
1194
+ 'backgroundColor',
1195
+ 'pressedBackgroundColor',
1196
+ 'hoverBackgroundColor',
1197
+ 'focusRingColor',
1198
+ ],
1199
+ accessoryPath,
1200
+ 'button key'
1201
+ );
1202
+ if (typeof accessory.label !== 'string' || !accessory.label.trim())
1203
+ fail(`${accessoryPath}.label`, 'must be non-blank');
1204
+ assertKey(accessory.actionKey, `${accessoryPath}.actionKey`);
1205
+ if (
1206
+ accessory.disabled !== undefined &&
1207
+ typeof accessory.disabled !== 'boolean'
1208
+ )
1209
+ fail(`${accessoryPath}.disabled`, 'must be boolean');
1210
+ for (const field of [
1211
+ 'textColor',
1212
+ 'backgroundColor',
1213
+ 'pressedBackgroundColor',
1214
+ 'hoverBackgroundColor',
1215
+ 'focusRingColor',
1216
+ ] as const) {
1217
+ const value = accessory[field];
1218
+ if (
1219
+ value !== undefined &&
1220
+ (typeof value !== 'string' ||
1221
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))
1222
+ )
1223
+ fail(`${accessoryPath}.${field}`, 'must be #RRGGBB or #RRGGBBAA');
1224
+ }
1225
+ }
1226
+ if (
1227
+ accessory.kind === 'icon' &&
1228
+ accessory.buttonStyle !== undefined &&
1229
+ accessory.buttonStyle !== 'tertiary'
1230
+ )
1231
+ fail(`${accessoryPath}.buttonStyle`, 'must be tertiary');
1020
1232
  if (
1021
1233
  accessory.kind === 'progress' &&
1022
1234
  (accessory.value < 0 || accessory.value > 1)
@@ -1024,14 +1236,188 @@ function assertTrailingAccessories(
1024
1236
  fail(`${accessoryPath}.value`, 'must be within 0...1');
1025
1237
  }
1026
1238
  if (accessory.kind === 'valuePair') {
1239
+ if (
1240
+ accessory.primaryFontWeight !== undefined &&
1241
+ accessory.primaryFontWeight !== 'medium'
1242
+ )
1243
+ fail(
1244
+ `${accessoryPath}.primaryFontWeight`,
1245
+ 'must be medium when provided'
1246
+ );
1247
+ assertTextHelp(accessory.primaryHelp, `${accessoryPath}.primaryHelp`);
1027
1248
  assertTextTone(accessory.primaryTone, `${accessoryPath}.primaryTone`);
1028
1249
  assertTextTone(accessory.secondaryTone, `${accessoryPath}.secondaryTone`);
1250
+ for (const field of [
1251
+ 'primaryTextSegments',
1252
+ 'secondaryTextSegments',
1253
+ ] as const) {
1254
+ const segments = accessory[field];
1255
+ if (segments === undefined) continue;
1256
+ const segmentPath = `${accessoryPath}.${field}`;
1257
+ if (!Array.isArray(segments) || segments.length > 64)
1258
+ fail(segmentPath, 'must be an array of at most 64 segments');
1259
+ let textLength = 0;
1260
+ segments.forEach((segment, segmentIndex) => {
1261
+ const path = `${segmentPath}[${segmentIndex}]`;
1262
+ const entry = protocolObject(segment, path);
1263
+ assertUnknownKeys(entry, ['text', 'style'], path, 'segment key');
1264
+ if (
1265
+ typeof entry.text !== 'string' ||
1266
+ entry.text.length > MAX_TEXT_LENGTH
1267
+ )
1268
+ fail(
1269
+ `${path}.text`,
1270
+ `must be a string no longer than ${MAX_TEXT_LENGTH} characters`
1271
+ );
1272
+ if (entry.style !== undefined && entry.style !== 'subscript')
1273
+ fail(`${path}.style`, 'must be subscript when provided');
1274
+ textLength += entry.text.length;
1275
+ });
1276
+ if (textLength > MAX_TEXT_LENGTH)
1277
+ fail(
1278
+ segmentPath,
1279
+ `total text must be at most ${MAX_TEXT_LENGTH} characters`
1280
+ );
1281
+ }
1282
+ }
1283
+ });
1284
+ }
1285
+
1286
+ function assertTextHelp(help: RowTextHelp | undefined, path: string): void {
1287
+ if (help === undefined) return;
1288
+ const object = protocolObject(help, path);
1289
+ assertUnknownKeys(
1290
+ object,
1291
+ ['actionKey', 'presentation', 'underline'],
1292
+ path,
1293
+ 'help key'
1294
+ );
1295
+ assertKey(help.actionKey, `${path}.actionKey`);
1296
+ if (!['tooltip', 'popover'].includes(help.presentation))
1297
+ fail(`${path}.presentation`, 'must be tooltip or popover');
1298
+ if (help.underline !== undefined && help.underline !== 'dashed')
1299
+ fail(`${path}.underline`, 'must be dashed');
1300
+ }
1301
+
1302
+ function assertButtonGroup(
1303
+ row: Pick<ButtonGroupRow, 'buttons'>,
1304
+ path: string
1305
+ ): void {
1306
+ if (!Array.isArray(row.buttons) || row.buttons.length === 0)
1307
+ fail(`${path}.buttons`, 'must contain at least one button');
1308
+ const keys = new Set<string>();
1309
+ row.buttons.forEach((button, index) => {
1310
+ const itemPath = `${path}.buttons[${index}]`;
1311
+ const object = protocolObject(button, itemPath);
1312
+ assertUnknownKeys(
1313
+ object,
1314
+ [
1315
+ 'key',
1316
+ 'label',
1317
+ 'actionKey',
1318
+ 'disabled',
1319
+ 'loading',
1320
+ 'testID',
1321
+ 'accessibilityLabel',
1322
+ ],
1323
+ itemPath,
1324
+ 'button key'
1325
+ );
1326
+ assertKey(button.key, `${itemPath}.key`);
1327
+ if (keys.has(button.key)) fail(`${itemPath}.key`, 'duplicate button key');
1328
+ keys.add(button.key);
1329
+ if (
1330
+ typeof button.label !== 'string' ||
1331
+ !button.label.trim() ||
1332
+ button.label.length > MAX_TEXT_LENGTH
1333
+ )
1334
+ fail(`${itemPath}.label`, 'must be non-blank bounded text');
1335
+ assertKey(button.actionKey, `${itemPath}.actionKey`);
1336
+ for (const field of ['disabled', 'loading'] as const) {
1337
+ if (button[field] !== undefined && typeof button[field] !== 'boolean')
1338
+ fail(`${itemPath}.${field}`, 'must be boolean');
1339
+ }
1340
+ for (const field of ['testID', 'accessibilityLabel'] as const) {
1341
+ if (button[field] !== undefined && typeof button[field] !== 'string')
1342
+ fail(`${itemPath}.${field}`, 'must be a string');
1029
1343
  }
1030
1344
  });
1031
1345
  }
1032
1346
 
1347
+ function assertIdentityExtras(
1348
+ row: Pick<
1349
+ IdentityRow,
1350
+ 'titleIcon' | 'secondaryTitleIcon' | 'titleImage' | 'trailing' | 'style'
1351
+ >,
1352
+ path: string
1353
+ ): void {
1354
+ for (const field of ['titleIcon', 'secondaryTitleIcon'] as const) {
1355
+ const titleIcon = row[field];
1356
+ if (titleIcon === undefined) continue;
1357
+ const iconPath = `${path}.${field}`;
1358
+ const icon = protocolObject(titleIcon, iconPath);
1359
+ assertUnknownKeys(
1360
+ icon,
1361
+ ['name', 'tintColor', 'accessibilityLabel', 'hoverActionKey'],
1362
+ iconPath,
1363
+ 'title icon key'
1364
+ );
1365
+ if (typeof titleIcon.name !== 'string' || !titleIcon.name.trim())
1366
+ fail(`${iconPath}.name`, 'must be non-blank');
1367
+ if (
1368
+ titleIcon.tintColor !== undefined &&
1369
+ (typeof titleIcon.tintColor !== 'string' ||
1370
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(titleIcon.tintColor))
1371
+ )
1372
+ fail(`${iconPath}.tintColor`, 'must be #RRGGBB or #RRGGBBAA');
1373
+ if (
1374
+ titleIcon.accessibilityLabel !== undefined &&
1375
+ typeof titleIcon.accessibilityLabel !== 'string'
1376
+ )
1377
+ fail(`${iconPath}.accessibilityLabel`, 'must be a string');
1378
+ if (titleIcon.hoverActionKey !== undefined)
1379
+ assertKey(titleIcon.hoverActionKey, `${iconPath}.hoverActionKey`);
1380
+ }
1381
+ if (row.titleImage !== undefined) {
1382
+ const imagePath = `${path}.titleImage`;
1383
+ const descriptor = protocolObject(row.titleImage, imagePath);
1384
+ assertUnknownKeys(
1385
+ descriptor,
1386
+ ['image', 'accessibilityLabel', 'hoverActionKey'],
1387
+ imagePath,
1388
+ 'title image key'
1389
+ );
1390
+ protocolObject(row.titleImage.image, `${imagePath}.image`);
1391
+ if (typeof row.titleImage.image.uri !== 'string')
1392
+ fail(`${imagePath}.image.uri`, 'must be a string');
1393
+ assertImage(row.titleImage.image, `${imagePath}.image`);
1394
+ const { width, height } = row.titleImage.image;
1395
+ if (width !== height || width < 1 || width > 40)
1396
+ fail(`${imagePath}.image`, 'must be square within 1...40');
1397
+ if (
1398
+ row.titleImage.accessibilityLabel !== undefined &&
1399
+ typeof row.titleImage.accessibilityLabel !== 'string'
1400
+ )
1401
+ fail(`${imagePath}.accessibilityLabel`, 'must be a string');
1402
+ if (row.titleImage.hoverActionKey !== undefined)
1403
+ assertKey(row.titleImage.hoverActionKey, `${imagePath}.hoverActionKey`);
1404
+ }
1405
+ const ratio = row.style?.leadingContentMaxWidthRatio;
1406
+ if (
1407
+ ratio !== undefined &&
1408
+ (typeof ratio !== 'number' ||
1409
+ !Number.isFinite(ratio) ||
1410
+ ratio <= 0 ||
1411
+ ratio > 1)
1412
+ )
1413
+ fail(`${path}.style.leadingContentMaxWidthRatio`, 'must be within (0, 1]');
1414
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
1415
+ }
1416
+
1033
1417
  function assertImage(image: ImageSource | undefined, path: string): void {
1034
1418
  if (!image) return;
1419
+ if (!isAllowedImageUri(image.uri))
1420
+ fail(`${path}.uri`, 'unsupported image URI');
1035
1421
  if (!image.uri.trim()) fail(`${path}.uri`, 'must not be empty');
1036
1422
  if (image.fallbackUris !== undefined) {
1037
1423
  if (!Array.isArray(image.fallbackUris))
@@ -1100,6 +1486,24 @@ function assertLeadingVisual(
1100
1486
  assertText(visual.cornerIcon?.name, `${path}.cornerIcon.name`);
1101
1487
  // OneKey patch: validate optional selector overlays at the JSON boundary.
1102
1488
  assertText(visual.fallbackIcon?.name, `${path}.fallbackIcon.name`);
1489
+ if (
1490
+ visual.fallbackTextColor !== undefined &&
1491
+ (typeof visual.fallbackTextColor !== 'string' ||
1492
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(visual.fallbackTextColor))
1493
+ )
1494
+ fail(`${path}.fallbackTextColor`, 'must be a hex color');
1495
+ if (
1496
+ visual.fallbackIcon?.size !== undefined &&
1497
+ (!Number.isFinite(visual.fallbackIcon.size) ||
1498
+ visual.fallbackIcon.size <= 0 ||
1499
+ visual.fallbackIcon.size > 40)
1500
+ )
1501
+ fail(`${path}.fallbackIcon.size`, 'must be within (0, 40]');
1502
+ if (
1503
+ visual.fallbackIcon?.backgroundColor !== undefined &&
1504
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(visual.fallbackIcon.backgroundColor)
1505
+ )
1506
+ fail(`${path}.fallbackIcon.backgroundColor`, 'must be a hex color');
1103
1507
  if ((visual.overlays?.length ?? 0) > 2)
1104
1508
  fail(`${path}.overlays`, 'supports at most two overlays');
1105
1509
  visual.overlays?.forEach((overlay, index) => {
@@ -1159,7 +1563,34 @@ function assertLeadingVisual(
1159
1563
  'must fit inside the overlay'
1160
1564
  );
1161
1565
  assertImage(overlay.image, `${path}.overlays[${index}].image`);
1566
+ if (overlay.fallbackIcon !== undefined && !overlay.image)
1567
+ fail(`${path}.overlays[${index}].fallbackIcon`, 'requires image');
1568
+ if (
1569
+ overlay.fallbackIcon !== undefined &&
1570
+ (typeof overlay.fallbackIcon.name !== 'string' ||
1571
+ !overlay.fallbackIcon.name.trim())
1572
+ )
1573
+ fail(
1574
+ `${path}.overlays[${index}].fallbackIcon.name`,
1575
+ 'must be non-blank'
1576
+ );
1577
+ if (
1578
+ overlay.fallbackIcon?.tintColor !== undefined &&
1579
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(overlay.fallbackIcon.tintColor)
1580
+ )
1581
+ fail(
1582
+ `${path}.overlays[${index}].fallbackIcon.tintColor`,
1583
+ 'must be a hex color'
1584
+ );
1162
1585
  assertText(overlay.text, `${path}.overlays[${index}].text`);
1586
+ if (
1587
+ overlay.fontWeight !== undefined &&
1588
+ !['regular', 'medium', 'semibold', 'bold'].includes(overlay.fontWeight)
1589
+ )
1590
+ fail(
1591
+ `${path}.overlays[${index}].fontWeight`,
1592
+ 'must be regular, medium, semibold, or bold'
1593
+ );
1163
1594
  });
1164
1595
  if (visual.kind === 'token') {
1165
1596
  assertImage(visual.networkImage, `${path}.networkImage`);
@@ -1191,6 +1622,8 @@ function assertVisual(row: RowModel, path: string): void {
1191
1622
  }
1192
1623
 
1193
1624
  function assertActivity(row: Partial<ActivityRow>, path: string): void {
1625
+ if (row.hideLeading !== undefined && typeof row.hideLeading !== 'boolean')
1626
+ fail(`${path}.hideLeading`, 'must be boolean');
1194
1627
  assertText(row.title, `${path}.title`);
1195
1628
  assertText(row.description, `${path}.description`);
1196
1629
  if (
@@ -1326,6 +1759,7 @@ function assertRow(
1326
1759
  path = `rows[${index}]`
1327
1760
  ): void {
1328
1761
  assertRowType(row.type, path);
1762
+ assertUnknownKeys(row, ROW_FIELDS[row.type], path, 'row key');
1329
1763
  assertKey(row.key, `${path}.key`);
1330
1764
  // OneKey patch: explicit dimensions and opacity cannot corrupt list layout.
1331
1765
  if (row.height !== undefined && (row.height < 0 || row.height > 4096))
@@ -1355,6 +1789,18 @@ function assertRow(
1355
1789
  assertWalletGroup(row, path);
1356
1790
  break;
1357
1791
  case 'identity':
1792
+ if (row.contentHeight !== undefined && row.contentHeight !== 'auto') {
1793
+ fail(`${path}.contentHeight`, 'must be auto');
1794
+ }
1795
+ if (
1796
+ row.subtitleLines !== undefined &&
1797
+ ![0, 1, 2].includes(row.subtitleLines)
1798
+ ) {
1799
+ fail(`${path}.subtitleLines`, 'must be 0, 1, or 2');
1800
+ }
1801
+ if (row.longPressActionKey !== undefined) {
1802
+ assertKey(row.longPressActionKey, `${path}.longPressActionKey`);
1803
+ }
1358
1804
  if (
1359
1805
  row.presentation !== undefined &&
1360
1806
  row.presentation !== 'walletSidebar' &&
@@ -1367,6 +1813,27 @@ function assertRow(
1367
1813
  );
1368
1814
  }
1369
1815
  assertText(row.title, `${path}.title`);
1816
+ if ((row.titleSuffixes?.length ?? 0) > 3)
1817
+ fail(`${path}.titleSuffixes`, 'supports at most 3 suffixes');
1818
+ row.titleSuffixes?.forEach((suffix, index) => {
1819
+ assertText(suffix.text, `${path}.titleSuffixes[${index}].text`);
1820
+ if (!['secondary', 'disabled'].includes(suffix.tone))
1821
+ fail(
1822
+ `${path}.titleSuffixes[${index}].tone`,
1823
+ 'must be secondary or disabled'
1824
+ );
1825
+ if (
1826
+ suffix.maxWidth !== undefined &&
1827
+ (!Number.isFinite(suffix.maxWidth) ||
1828
+ suffix.maxWidth < 0 ||
1829
+ suffix.maxWidth > 4096)
1830
+ )
1831
+ fail(
1832
+ `${path}.titleSuffixes[${index}].maxWidth`,
1833
+ 'must be finite within 0...4096'
1834
+ );
1835
+ });
1836
+ assertIdentityExtras(row, path);
1370
1837
  assertText(row.subtitle, `${path}.subtitle`);
1371
1838
  // OneKey patch: selector text segments truncate independently.
1372
1839
  row.subtitleSegments?.forEach((segment, segmentIndex) => {
@@ -1434,10 +1901,16 @@ function assertRow(
1434
1901
  assertActivity(row, path);
1435
1902
  break;
1436
1903
  case 'message':
1904
+ if (
1905
+ row.presentation !== undefined &&
1906
+ row.presentation !== 'inlineWarning'
1907
+ ) {
1908
+ fail(`${path}.presentation`, 'must be inlineWarning');
1909
+ }
1437
1910
  assertText(row.title, `${path}.title`);
1438
1911
  assertText(row.body, `${path}.body`);
1439
- if (![1, 2, 3].includes(row.bodyLines ?? 3)) {
1440
- fail(`${path}.bodyLines`, 'must be 1, 2, or 3');
1912
+ if (![0, 1, 2, 3].includes(row.bodyLines ?? 3)) {
1913
+ fail(`${path}.bodyLines`, 'must be 0, 1, 2, or 3');
1441
1914
  }
1442
1915
  assertImage(row.thumbnail, `${path}.thumbnail`);
1443
1916
  break;
@@ -1448,6 +1921,23 @@ function assertRow(
1448
1921
  row.columns.forEach((column, columnIndex) => {
1449
1922
  assertKey(column.key, `${path}.columns[${columnIndex}].key`);
1450
1923
  assertText(column.text, `${path}.columns[${columnIndex}].text`);
1924
+ assertIdentityExtras(column, `${path}.columns[${columnIndex}]`);
1925
+ for (const field of [
1926
+ 'textSegments',
1927
+ 'secondaryTextSegments',
1928
+ ] as const) {
1929
+ column[field]?.forEach((segment, segmentIndex) => {
1930
+ assertText(
1931
+ segment.text,
1932
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].text`
1933
+ );
1934
+ if (segment.style !== undefined && segment.style !== 'subscript')
1935
+ fail(
1936
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].style`,
1937
+ 'must be subscript'
1938
+ );
1939
+ });
1940
+ }
1451
1941
  assertText(
1452
1942
  column.secondaryLeadingText,
1453
1943
  `${path}.columns[${columnIndex}].secondaryLeadingText`
@@ -1464,6 +1954,13 @@ function assertRow(
1464
1954
  if ((row.badges?.length ?? 0) > MAX_BADGES) {
1465
1955
  fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
1466
1956
  }
1957
+ if ((row.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
1958
+ fail(
1959
+ `${path}.trailing`,
1960
+ `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
1961
+ );
1962
+ }
1963
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
1467
1964
  break;
1468
1965
  case 'market':
1469
1966
  assertMarketRow(row, path);
@@ -1540,6 +2037,11 @@ function assertRow(
1540
2037
  assertText(row.title, `${path}.title`);
1541
2038
  assertText(row.subtitle, `${path}.subtitle`);
1542
2039
  assertText(row.value, `${path}.value`);
2040
+ if (row.leadingBadge) {
2041
+ assertKey(row.leadingBadge.key, `${path}.leadingBadge.key`);
2042
+ assertText(row.leadingBadge.text, `${path}.leadingBadge.text`);
2043
+ }
2044
+ assertTextHelp(row.valueHelp, `${path}.valueHelp`);
1543
2045
  if (row.valueActionKey !== undefined) {
1544
2046
  assertKey(row.valueActionKey, `${path}.valueActionKey`);
1545
2047
  }
@@ -1572,6 +2074,9 @@ function assertRow(
1572
2074
  }
1573
2075
  assertTrailingAccessories(row.trailing, `${path}.trailing`);
1574
2076
  break;
2077
+ case 'buttonGroup':
2078
+ assertButtonGroup(row, path);
2079
+ break;
1575
2080
  case 'system':
1576
2081
  const presentation = 'presentation' in row ? row.presentation : undefined;
1577
2082
  if (presentation !== undefined && presentation !== 'market') {
@@ -1677,9 +2182,39 @@ function assertMediaPreview(value: unknown, path: string) {
1677
2182
  }
1678
2183
  }
1679
2184
 
1680
- export function validateSnapshot(
2185
+ function assertSnapshotContract(
1681
2186
  snapshot: NativeListSnapshot
1682
2187
  ): NativeListSnapshot {
2188
+ if (snapshot.disclosure !== undefined) {
2189
+ if (typeof snapshot.disclosure.expanded !== 'boolean')
2190
+ fail('snapshot.disclosure.expanded', 'must be a boolean');
2191
+ const inset = snapshot.disclosure.expandedTrailingInset;
2192
+ if (inset !== undefined && (!Number.isFinite(inset) || inset < 0))
2193
+ fail(
2194
+ 'snapshot.disclosure.expandedTrailingInset',
2195
+ 'must be finite and nonnegative'
2196
+ );
2197
+ }
2198
+ if (snapshot.structuralTransition) {
2199
+ assertKey(
2200
+ snapshot.structuralTransition.id,
2201
+ 'snapshot.structuralTransition.id'
2202
+ );
2203
+ if (snapshot.structuralTransition.anchorKey !== undefined)
2204
+ assertKey(
2205
+ snapshot.structuralTransition.anchorKey,
2206
+ 'snapshot.structuralTransition.anchorKey'
2207
+ );
2208
+ const duration = snapshot.structuralTransition.durationMs;
2209
+ if (
2210
+ duration !== undefined &&
2211
+ (!Number.isFinite(duration) || duration < 0 || duration > 2000)
2212
+ )
2213
+ fail(
2214
+ 'snapshot.structuralTransition.durationMs',
2215
+ 'must be finite within 0...2000'
2216
+ );
2217
+ }
1683
2218
  if (
1684
2219
  snapshot.capabilities?.refreshTriggerDistance !== undefined &&
1685
2220
  (!Number.isFinite(snapshot.capabilities.refreshTriggerDistance) ||
@@ -1695,6 +2230,18 @@ export function validateSnapshot(
1695
2230
  snapshot.theme?.imageFallbackBackground,
1696
2231
  'theme.imageFallbackBackground'
1697
2232
  );
2233
+ if (
2234
+ snapshot.theme?.successBackground !== undefined &&
2235
+ (typeof snapshot.theme.successBackground !== 'string' ||
2236
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.successBackground))
2237
+ )
2238
+ fail('theme.successBackground', 'must be a hex color');
2239
+ if (
2240
+ snapshot.theme?.rowHoverBackground !== undefined &&
2241
+ (typeof snapshot.theme.rowHoverBackground !== 'string' ||
2242
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.rowHoverBackground))
2243
+ )
2244
+ fail('theme.rowHoverBackground', 'must be a hex color');
1698
2245
  if (snapshot.schemaVersion !== 1) fail('snapshot.schemaVersion', 'must be 1');
1699
2246
  if (!Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0) {
1700
2247
  fail('snapshot.generation', 'must be a non-negative safe integer');
@@ -1826,102 +2373,1970 @@ export function validateSnapshot(
1826
2373
  'supports at most one key in single mode'
1827
2374
  );
1828
2375
  }
1829
- return normalizeSnapshotStyles(snapshot);
1830
- }
1831
-
1832
- /**
1833
- * Resolves typography tokens to numbers. Returns the original snapshot when
1834
- * nothing needs resolving, so the common no-style path keeps object identity.
1835
- */
1836
- function normalizeSnapshotStyles(
1837
- snapshot: NativeListSnapshot
1838
- ): NativeListSnapshot {
1839
- let changed = false;
1840
- const rows = snapshot.rows.map((row) => {
1841
- const next = normalizeRowStyles(row);
1842
- if (next !== row) changed = true;
1843
- return next;
1844
- });
1845
- const emptyState = snapshot.emptyState
1846
- ? normalizeRowStyles(snapshot.emptyState)
1847
- : snapshot.emptyState;
1848
- const fixedFooter = snapshot.fixedFooter
1849
- ? normalizeRowStyles(snapshot.fixedFooter)
1850
- : snapshot.fixedFooter;
1851
- if (
1852
- !changed &&
1853
- emptyState === snapshot.emptyState &&
1854
- fixedFooter === snapshot.fixedFooter
1855
- ) {
1856
- return snapshot;
1857
- }
1858
- return { ...snapshot, rows, emptyState, fixedFooter };
2376
+ return snapshot;
1859
2377
  }
1860
2378
 
1861
- function assertPatchChanges(patch: RowPatch, index: number): void {
1862
- const path = `patches[${index}].changes`;
1863
- const patchedStyle = (patch.changes as { style?: unknown }).style;
1864
- if (patchedStyle !== undefined) {
1865
- assertRowStyle({ type: patch.type, style: patchedStyle } as RowModel, path);
1866
- }
1867
- // OneKey patch: partial balance updates retain a valid, current accessibility label.
1868
- if ('accessibilityLabel' in patch.changes) {
1869
- assertText(patch.changes.accessibilityLabel, `${path}.accessibilityLabel`);
1870
- }
1871
- // OneKey patch: partial updates may refer to an existing height but still require a valid policy.
1872
- if (
1873
- 'heightRounding' in patch.changes &&
1874
- patch.changes.heightRounding !== undefined &&
1875
- !['floor', 'nearest'].includes(patch.changes.heightRounding)
1876
- )
1877
- fail(`${path}.heightRounding`, 'must be floor or nearest');
1878
- if (
1879
- patch.changes.revision !== undefined &&
1880
- (!Number.isSafeInteger(patch.changes.revision) ||
1881
- patch.changes.revision < 0)
1882
- ) {
1883
- fail(`${path}.revision`, 'must be a non-negative safe integer');
1884
- }
2379
+ const COMMON_ROW_FIELDS = [
2380
+ 'height',
2381
+ 'heightRounding',
2382
+ 'testID',
2383
+ 'opacity',
2384
+ 'backgroundColor',
2385
+ 'backgroundFullWidth',
2386
+ 'pressDisabled',
2387
+ 'key',
2388
+ 'revision',
2389
+ 'sectionKey',
2390
+ 'groupId',
2391
+ 'groupPosition',
2392
+ 'size',
2393
+ 'density',
2394
+ 'disabled',
2395
+ 'selected',
2396
+ 'accessibilityLabel',
2397
+ 'separator',
2398
+ 'type',
2399
+ 'style',
2400
+ ];
1885
2401
 
1886
- switch (patch.type) {
1887
- case 'identity':
1888
- assertText(patch.changes.title, `${path}.title`);
1889
- assertText(patch.changes.subtitle, `${path}.subtitle`);
1890
- assertText(patch.changes.tertiary, `${path}.tertiary`);
1891
- if (
1892
- patch.changes.tertiaryTone !== undefined &&
1893
- !['secondary', 'info'].includes(patch.changes.tertiaryTone)
1894
- ) {
1895
- fail(`${path}.tertiaryTone`, 'must be secondary or info');
1896
- }
1897
- assertLeadingVisual(patch.changes.leading, `${path}.leading`);
1898
- assertTrailingAccessories(
1899
- patch.changes.leadingAction ? [patch.changes.leadingAction] : undefined,
1900
- `${path}.leadingAction`
1901
- );
1902
- if ((patch.changes.badges?.length ?? 0) > MAX_BADGES) {
1903
- fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
1904
- }
1905
- if ((patch.changes.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
1906
- fail(
1907
- `${path}.trailing`,
1908
- `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
1909
- );
1910
- }
1911
- assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
1912
- break;
1913
- case 'rail':
1914
- assertText(patch.changes.title, `${path}.title`);
1915
- assertLeadingVisual(patch.changes.visual, `${path}.visual`);
1916
- break;
1917
- case 'activity':
1918
- assertActivity(patch.changes, path);
1919
- assertText(patch.changes.title, `${path}.title`);
1920
- assertText(patch.changes.description, `${path}.description`);
1921
- assertText(patch.changes.status, `${path}.status`);
1922
- assertText(patch.changes.primaryAmount, `${path}.primaryAmount`);
1923
- assertText(patch.changes.secondaryAmount, `${path}.secondaryAmount`);
1924
- assertLeadingVisual(patch.changes.leading, `${path}.leading`);
2402
+ const ROW_FIELDS: Readonly<Record<string, readonly string[]>> = {
2403
+ identity: [
2404
+ ...COMMON_ROW_FIELDS,
2405
+ 'contentHeight',
2406
+ 'longPressActionKey',
2407
+ 'titleMatch',
2408
+ 'titleActionKey',
2409
+ 'titleActionOnHover',
2410
+ 'subtitleSegments',
2411
+ 'presentation',
2412
+ 'leading',
2413
+ 'leadingAction',
2414
+ 'title',
2415
+ 'titleSuffixes',
2416
+ 'titleIcon',
2417
+ 'secondaryTitleIcon',
2418
+ 'titleImage',
2419
+ 'subtitle',
2420
+ 'tertiary',
2421
+ 'tertiaryTone',
2422
+ 'titleLines',
2423
+ 'subtitleLines',
2424
+ 'badges',
2425
+ 'trailing',
2426
+ 'draggable',
2427
+ ],
2428
+ walletGroup: [...COMMON_ROW_FIELDS, 'parent', 'children', 'draggable'],
2429
+ rail: [
2430
+ ...COMMON_ROW_FIELDS,
2431
+ 'visual',
2432
+ 'title',
2433
+ 'status',
2434
+ 'badge',
2435
+ 'draggable',
2436
+ ],
2437
+ activity: [
2438
+ ...COMMON_ROW_FIELDS,
2439
+ 'leading',
2440
+ 'hideLeading',
2441
+ 'secondaryLeading',
2442
+ 'title',
2443
+ 'description',
2444
+ 'status',
2445
+ 'primaryAmount',
2446
+ 'secondaryAmount',
2447
+ 'amounts',
2448
+ 'badges',
2449
+ 'presentation',
2450
+ 'fee',
2451
+ 'descriptionActionKey',
2452
+ 'footerActions',
2453
+ ],
2454
+ message: [
2455
+ ...COMMON_ROW_FIELDS,
2456
+ 'presentation',
2457
+ 'unread',
2458
+ 'leading',
2459
+ 'title',
2460
+ 'body',
2461
+ 'bodyLines',
2462
+ 'time',
2463
+ 'thumbnail',
2464
+ ],
2465
+ dataRow: [
2466
+ ...COMMON_ROW_FIELDS,
2467
+ 'leading',
2468
+ 'columns',
2469
+ 'trailing',
2470
+ 'checkbox',
2471
+ 'index',
2472
+ 'badge',
2473
+ 'badges',
2474
+ 'favorite',
2475
+ 'favoriteActive',
2476
+ ],
2477
+ market: [
2478
+ ...COMMON_ROW_FIELDS,
2479
+ 'variant',
2480
+ 'webTable',
2481
+ 'metrics',
2482
+ 'leadingAction',
2483
+ 'leading',
2484
+ 'title',
2485
+ 'subtitle',
2486
+ 'subtitlePrefix',
2487
+ 'subtitleSegments',
2488
+ 'price',
2489
+ 'priceSegments',
2490
+ 'change',
2491
+ 'badges',
2492
+ 'pressActionKey',
2493
+ 'pressInActionKey',
2494
+ 'longPressActionKey',
2495
+ 'diagnostics',
2496
+ ],
2497
+ mediaTile: [
2498
+ ...COMMON_ROW_FIELDS,
2499
+ 'variant',
2500
+ 'media',
2501
+ 'image',
2502
+ 'imageState',
2503
+ 'networkImage',
2504
+ 'title',
2505
+ 'subtitle',
2506
+ 'badge',
2507
+ 'closeActionKey',
2508
+ ],
2509
+ metricCard: [
2510
+ ...COMMON_ROW_FIELDS,
2511
+ 'variant',
2512
+ 'title',
2513
+ 'value',
2514
+ 'subtitle',
2515
+ 'trend',
2516
+ 'trendTone',
2517
+ 'visual',
2518
+ 'badge',
2519
+ 'metrics',
2520
+ 'progress',
2521
+ ],
2522
+ sectionHeader: [
2523
+ ...COMMON_ROW_FIELDS,
2524
+ 'sticky',
2525
+ 'valueActionTestID',
2526
+ 'valueSegments',
2527
+ 'titleActionKey',
2528
+ 'titleActionOnHover',
2529
+ 'presentation',
2530
+ 'indexTitle',
2531
+ 'variant',
2532
+ 'title',
2533
+ 'leadingBadge',
2534
+ 'titleLoading',
2535
+ 'subtitle',
2536
+ 'value',
2537
+ 'valueHelp',
2538
+ 'valueActionKey',
2539
+ 'titleIcon',
2540
+ 'valueIcon',
2541
+ 'checkbox',
2542
+ ],
2543
+ action: [
2544
+ ...COMMON_ROW_FIELDS,
2545
+ 'presentation',
2546
+ 'title',
2547
+ 'actionKey',
2548
+ 'tone',
2549
+ 'icon',
2550
+ 'checkbox',
2551
+ 'trailing',
2552
+ ],
2553
+ buttonGroup: [...COMMON_ROW_FIELDS, 'buttons'],
2554
+ system: [
2555
+ ...COMMON_ROW_FIELDS,
2556
+ 'variant',
2557
+ 'presentation',
2558
+ 'loadingStyle',
2559
+ 'message',
2560
+ 'actionKey',
2561
+ 'actionText',
2562
+ 'title',
2563
+ 'borderColor',
2564
+ ],
2565
+ };
2566
+
2567
+ const COMMON_PATCH_FIELDS = [
2568
+ 'height',
2569
+ 'heightRounding',
2570
+ 'opacity',
2571
+ 'pressDisabled',
2572
+ 'revision',
2573
+ 'disabled',
2574
+ 'selected',
2575
+ 'accessibilityLabel',
2576
+ 'separator',
2577
+ 'style',
2578
+ ];
2579
+
2580
+ const PATCH_FIELDS: Readonly<Record<string, readonly string[]>> = {
2581
+ identity: [
2582
+ ...COMMON_PATCH_FIELDS,
2583
+ 'contentHeight',
2584
+ 'longPressActionKey',
2585
+ 'titleMatch',
2586
+ 'titleActionKey',
2587
+ 'titleActionOnHover',
2588
+ 'subtitleSegments',
2589
+ 'leading',
2590
+ 'leadingAction',
2591
+ 'title',
2592
+ 'titleSuffixes',
2593
+ 'titleIcon',
2594
+ 'secondaryTitleIcon',
2595
+ 'titleImage',
2596
+ 'subtitle',
2597
+ 'tertiary',
2598
+ 'tertiaryTone',
2599
+ 'subtitleLines',
2600
+ 'badges',
2601
+ 'trailing',
2602
+ ],
2603
+ rail: [...COMMON_PATCH_FIELDS, 'title', 'visual', 'status', 'badge'],
2604
+ activity: [
2605
+ ...COMMON_PATCH_FIELDS,
2606
+ 'presentation',
2607
+ 'leading',
2608
+ 'title',
2609
+ 'badges',
2610
+ 'status',
2611
+ 'hideLeading',
2612
+ 'secondaryLeading',
2613
+ 'description',
2614
+ 'primaryAmount',
2615
+ 'secondaryAmount',
2616
+ 'amounts',
2617
+ 'fee',
2618
+ 'descriptionActionKey',
2619
+ 'footerActions',
2620
+ ],
2621
+ message: [
2622
+ ...COMMON_PATCH_FIELDS,
2623
+ 'presentation',
2624
+ 'title',
2625
+ 'unread',
2626
+ 'body',
2627
+ 'bodyLines',
2628
+ 'time',
2629
+ 'thumbnail',
2630
+ ],
2631
+ dataRow: [
2632
+ ...COMMON_PATCH_FIELDS,
2633
+ 'leading',
2634
+ 'badges',
2635
+ 'trailing',
2636
+ 'badge',
2637
+ 'columns',
2638
+ 'checkbox',
2639
+ 'index',
2640
+ 'favorite',
2641
+ 'favoriteActive',
2642
+ ],
2643
+ market: [
2644
+ ...COMMON_PATCH_FIELDS,
2645
+ 'longPressActionKey',
2646
+ 'subtitleSegments',
2647
+ 'leading',
2648
+ 'leadingAction',
2649
+ 'title',
2650
+ 'subtitle',
2651
+ 'badges',
2652
+ 'webTable',
2653
+ 'metrics',
2654
+ 'price',
2655
+ 'priceSegments',
2656
+ 'change',
2657
+ 'pressActionKey',
2658
+ 'pressInActionKey',
2659
+ 'diagnostics',
2660
+ ],
2661
+ mediaTile: [
2662
+ ...COMMON_PATCH_FIELDS,
2663
+ 'title',
2664
+ 'subtitle',
2665
+ 'badge',
2666
+ 'media',
2667
+ 'image',
2668
+ 'imageState',
2669
+ 'networkImage',
2670
+ 'closeActionKey',
2671
+ ],
2672
+ metricCard: [
2673
+ ...COMMON_PATCH_FIELDS,
2674
+ 'title',
2675
+ 'subtitle',
2676
+ 'visual',
2677
+ 'badge',
2678
+ 'variant',
2679
+ 'value',
2680
+ 'trend',
2681
+ 'trendTone',
2682
+ 'metrics',
2683
+ 'progress',
2684
+ ],
2685
+ sectionHeader: [
2686
+ ...COMMON_PATCH_FIELDS,
2687
+ 'titleActionKey',
2688
+ 'titleActionOnHover',
2689
+ 'title',
2690
+ 'titleIcon',
2691
+ 'subtitle',
2692
+ 'checkbox',
2693
+ 'variant',
2694
+ 'value',
2695
+ 'leadingBadge',
2696
+ 'titleLoading',
2697
+ 'valueHelp',
2698
+ 'valueActionKey',
2699
+ 'valueIcon',
2700
+ ],
2701
+ action: [
2702
+ ...COMMON_PATCH_FIELDS,
2703
+ 'title',
2704
+ 'trailing',
2705
+ 'checkbox',
2706
+ 'tone',
2707
+ 'icon',
2708
+ ],
2709
+ buttonGroup: [...COMMON_PATCH_FIELDS, 'buttons'],
2710
+ system: ['revision', 'disabled', 'message'],
2711
+ };
2712
+
2713
+ function protocolObject(value: unknown, path: string): Record<string, unknown> {
2714
+ if (!value || typeof value !== 'object' || Array.isArray(value))
2715
+ fail(path, 'must be an object');
2716
+ return value as Record<string, unknown>;
2717
+ }
2718
+
2719
+ function protocolKey(value: unknown, path: string): void {
2720
+ if (typeof value !== 'string' || value.trim().length === 0)
2721
+ fail(path, 'must be a non-blank string');
2722
+ }
2723
+
2724
+ const PROTOCOL_ARRAY_FIELDS = new Set([
2725
+ 'columns',
2726
+ 'titleSuffixes',
2727
+ 'cells',
2728
+ 'points',
2729
+ 'images',
2730
+ 'overlays',
2731
+ 'badges',
2732
+ 'trailing',
2733
+ 'footerActions',
2734
+ 'buttons',
2735
+ 'amounts',
2736
+ 'metrics',
2737
+ 'children',
2738
+ 'subtitleSegments',
2739
+ 'titleMatch',
2740
+ 'selectedKeys',
2741
+ 'segments',
2742
+ 'hoverSecondary',
2743
+ 'hoverImages',
2744
+ 'secondaryBadges',
2745
+ 'fallbackUris',
2746
+ 'probeOrder',
2747
+ 'priceSegments',
2748
+ 'textSegments',
2749
+ 'secondaryTextSegments',
2750
+ 'primaryTextSegments',
2751
+ ]);
2752
+ const PROTOCOL_NUMBER_FIELDS = new Set([
2753
+ 'leadingContentMaxWidthRatio',
2754
+ 'height',
2755
+ 'width',
2756
+ 'fontSize',
2757
+ 'lineHeight',
2758
+ 'opacity',
2759
+ 'offsetY',
2760
+ 'offsetX',
2761
+ 'cornerRadius',
2762
+ 'borderWidth',
2763
+ 'horizontalPadding',
2764
+ 'verticalPadding',
2765
+ 'leadingGap',
2766
+ 'lineGap',
2767
+ 'titleBadgeGap',
2768
+ 'trailingGap',
2769
+ 'start',
2770
+ 'end',
2771
+ 'padding',
2772
+ 'offset',
2773
+ 'overscan',
2774
+ 'minWidth',
2775
+ 'flex',
2776
+ 'paddingStart',
2777
+ 'paddingEnd',
2778
+ 'changeWidth',
2779
+ 'changeHeight',
2780
+ 'changeCornerRadius',
2781
+ 'contentTrailingGap',
2782
+ 'subtitleTrailingPadding',
2783
+ 'partGap',
2784
+ 'contentPadding',
2785
+ 'contentPaddingHorizontal',
2786
+ 'contentPaddingTop',
2787
+ 'contentPaddingBottom',
2788
+ 'itemSpacing',
2789
+ 'gridColumns',
2790
+ ]);
2791
+
2792
+ /** Validate only shapes that renderers dereference, not display budgets. */
2793
+ function assertProtocolFields(
2794
+ value: unknown,
2795
+ path: string,
2796
+ parentField = ''
2797
+ ): void {
2798
+ if (value === undefined || value === null || typeof value !== 'object')
2799
+ return;
2800
+ if (Array.isArray(value)) {
2801
+ for (const [index, item] of value.entries()) {
2802
+ const itemPath = `${path}[${index}]`;
2803
+ if (
2804
+ ['selectedKeys', 'fallbackUris', 'probeOrder'].includes(parentField)
2805
+ ) {
2806
+ if (typeof item !== 'string') fail(itemPath, 'must be a string');
2807
+ } else if (parentField === 'points') {
2808
+ if (typeof item !== 'number') fail(itemPath, 'must be a finite number');
2809
+ } else if (parentField === 'hoverImages' && item === null) continue;
2810
+ else protocolObject(item, itemPath);
2811
+ assertProtocolFields(item, itemPath, parentField);
2812
+ }
2813
+ return;
2814
+ }
2815
+ const object = value as Record<string, unknown>;
2816
+ if (parentField === 'fallbackIcon') {
2817
+ protocolKey(object.name, `${path}.name`);
2818
+ if (
2819
+ object.size !== undefined &&
2820
+ (typeof object.size !== 'number' ||
2821
+ !Number.isFinite(object.size) ||
2822
+ object.size <= 0 ||
2823
+ object.size > 40)
2824
+ )
2825
+ fail(`${path}.size`, 'must be within (0, 40]');
2826
+ for (const field of ['tintColor', 'backgroundColor'] as const) {
2827
+ const color = object[field];
2828
+ if (
2829
+ color !== undefined &&
2830
+ (typeof color !== 'string' ||
2831
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(color))
2832
+ )
2833
+ fail(`${path}.${field}`, 'must be a hex color');
2834
+ }
2835
+ }
2836
+ if (
2837
+ parentField === 'overlays' &&
2838
+ object.fallbackIcon !== undefined &&
2839
+ !object.image
2840
+ )
2841
+ fail(`${path}.fallbackIcon`, 'requires image');
2842
+ if (
2843
+ !path.includes('.style.') &&
2844
+ ['image', 'networkImage', 'thumbnail', 'images', 'hoverImages'].includes(
2845
+ parentField
2846
+ ) &&
2847
+ typeof object.uri !== 'string'
2848
+ )
2849
+ fail(`${path}.uri`, 'must be a string');
2850
+ Object.entries(value).forEach(([field, item]) => {
2851
+ if (item === undefined) return;
2852
+ if (field === 'headers') {
2853
+ const headers = protocolObject(item, `${path}.headers`);
2854
+ for (const [name, headerValue] of Object.entries(headers)) {
2855
+ if (!name.trim() || typeof headerValue !== 'string')
2856
+ fail(`${path}.headers`, 'must contain string headers');
2857
+ }
2858
+ return;
2859
+ }
2860
+ const fieldPath = `${path}.${field}`;
2861
+ if (
2862
+ !path.endsWith('.style') &&
2863
+ PROTOCOL_ARRAY_FIELDS.has(field) &&
2864
+ !Array.isArray(item)
2865
+ )
2866
+ fail(fieldPath, 'must be an array');
2867
+ if (PROTOCOL_NUMBER_FIELDS.has(field) && typeof item !== 'number')
2868
+ fail(fieldPath, 'must be a finite number');
2869
+ if (
2870
+ PROTOCOL_NUMBER_FIELDS.has(field) &&
2871
+ typeof item === 'number' &&
2872
+ item < 0 &&
2873
+ !['offsetX', 'offsetY'].includes(field)
2874
+ )
2875
+ fail(fieldPath, 'must be non-negative');
2876
+ if (
2877
+ parentField === 'overlays' &&
2878
+ field === 'fontWeight' &&
2879
+ !['regular', 'medium', 'semibold', 'bold'].includes(item as string)
2880
+ )
2881
+ fail(fieldPath, 'must be regular, medium, semibold, or bold');
2882
+ if (field === 'buttonStyle' && item !== 'tertiary')
2883
+ fail(fieldPath, 'must be tertiary');
2884
+ if (field === 'hideLeading' && typeof item !== 'boolean')
2885
+ fail(fieldPath, 'must be boolean');
2886
+ if (
2887
+ field === 'key' ||
2888
+ field === 'sectionKey' ||
2889
+ field === 'groupId' ||
2890
+ field === 'actionKey' ||
2891
+ field.endsWith('ActionKey')
2892
+ )
2893
+ protocolKey(item, fieldPath);
2894
+ if (
2895
+ (field === 'uri' || field === 'fallbackUri') &&
2896
+ typeof item !== 'string'
2897
+ )
2898
+ fail(fieldPath, 'must be a string');
2899
+ if (
2900
+ (field === 'style' &&
2901
+ !(item === 'subscript' && /[Ss]egments\[/.test(path))) ||
2902
+ field === 'container'
2903
+ )
2904
+ protocolObject(item, fieldPath);
2905
+ if (
2906
+ path.endsWith('.style') &&
2907
+ [
2908
+ 'title',
2909
+ 'subtitle',
2910
+ 'tertiary',
2911
+ 'body',
2912
+ 'time',
2913
+ 'price',
2914
+ 'change',
2915
+ 'columns',
2916
+ 'columnSecondary',
2917
+ 'value',
2918
+ 'valueSecondary',
2919
+ 'badge',
2920
+ 'description',
2921
+ 'status',
2922
+ 'primaryAmount',
2923
+ 'secondaryAmount',
2924
+ 'trend',
2925
+ 'message',
2926
+ 'actionText',
2927
+ ].includes(field)
2928
+ )
2929
+ protocolObject(item, fieldPath);
2930
+ assertProtocolFields(item, fieldPath, field);
2931
+ });
2932
+ }
2933
+
2934
+ function assertRowProtocol(row: RowModel, path: string): void {
2935
+ protocolObject(row, path);
2936
+ assertRowType(row.type, path);
2937
+ protocolKey(row.key, `${path}.key`);
2938
+ assertCoreRow(row, path);
2939
+ assertProtocolFields(row, path);
2940
+ for (const field of ['leading', 'visual', 'secondaryLeading'] as const) {
2941
+ const visual = (row as unknown as Record<string, unknown>)[field];
2942
+ if (
2943
+ visual !== undefined ||
2944
+ (field === 'leading' &&
2945
+ (row.type === 'identity' || row.type === 'market'))
2946
+ ) {
2947
+ const object = protocolObject(visual, `${path}.${field}`);
2948
+ if (object.kind === 'stackedImages' && !Array.isArray(object.images))
2949
+ fail(`${path}.${field}.images`, 'must be an array');
2950
+ }
2951
+ }
2952
+ for (const field of [
2953
+ 'title',
2954
+ 'subtitle',
2955
+ 'tertiary',
2956
+ 'body',
2957
+ 'time',
2958
+ 'price',
2959
+ 'indexTitle',
2960
+ ] as const) {
2961
+ const value = (row as unknown as Record<string, unknown>)[field];
2962
+ if (value !== undefined && typeof value !== 'string')
2963
+ fail(`${path}.${field}`, 'must be a string');
2964
+ }
2965
+ if (row.height !== undefined && row.height < 0)
2966
+ fail(`${path}.height`, 'must be non-negative');
2967
+ if (row.type === 'identity') {
2968
+ if (isDevelopment()) assertIdentityExtras(row, path);
2969
+ if (row.titleSuffixes !== undefined && !Array.isArray(row.titleSuffixes))
2970
+ fail(`${path}.titleSuffixes`, 'must be an array');
2971
+ row.titleSuffixes?.forEach((suffix, index) => {
2972
+ protocolObject(suffix, `${path}.titleSuffixes[${index}]`);
2973
+ if (
2974
+ typeof suffix.text !== 'string' ||
2975
+ !['secondary', 'disabled'].includes(suffix.tone)
2976
+ )
2977
+ fail(`${path}.titleSuffixes[${index}]`, 'invalid title suffix');
2978
+ if (
2979
+ suffix.maxWidth !== undefined &&
2980
+ (!Number.isFinite(suffix.maxWidth) ||
2981
+ suffix.maxWidth < 0 ||
2982
+ suffix.maxWidth > 4096)
2983
+ )
2984
+ fail(
2985
+ `${path}.titleSuffixes[${index}].maxWidth`,
2986
+ 'must be finite within 0...4096'
2987
+ );
2988
+ });
2989
+ let end = 0;
2990
+ row.titleMatch?.forEach((match) => {
2991
+ if (
2992
+ !Number.isInteger(match.start) ||
2993
+ !Number.isInteger(match.end) ||
2994
+ match.start < end ||
2995
+ match.end <= match.start ||
2996
+ match.end > row.title.length
2997
+ )
2998
+ fail(`${path}.titleMatch`, 'invalid text range');
2999
+ end = match.end;
3000
+ });
3001
+ }
3002
+ if (row.type === 'buttonGroup' && isDevelopment())
3003
+ assertButtonGroup(row, path);
3004
+ if (row.type === 'sectionHeader' && isDevelopment())
3005
+ assertTextHelp(row.valueHelp, `${path}.valueHelp`);
3006
+ if (row.type === 'mediaTile' && row.media) {
3007
+ protocolObject(row.media.source, `${path}.media.source`);
3008
+ if (!Array.isArray(row.media.probeOrder))
3009
+ fail(`${path}.media.probeOrder`, 'must be an array');
3010
+ }
3011
+ if (row.type === 'walletGroup') {
3012
+ protocolObject(row.parent, `${path}.parent`);
3013
+ if (!Array.isArray(row.children))
3014
+ fail(`${path}.children`, 'must be an array');
3015
+ const members = [row.parent, ...row.children];
3016
+ const keys = new Set<string>();
3017
+ if (row.parent.key !== row.key)
3018
+ fail(`${path}.parent.key`, 'must match its group');
3019
+ members.forEach((member, index) => {
3020
+ assertRowProtocol(member, `${path}.members[${index}]`);
3021
+ if (member.type !== 'identity' || keys.has(member.key))
3022
+ fail(path, 'invalid wallet member identity');
3023
+ keys.add(member.key);
3024
+ });
3025
+ }
3026
+ if (row.type === 'dataRow') {
3027
+ if (!Array.isArray(row.columns))
3028
+ fail(`${path}.columns`, 'must be an array');
3029
+ row.columns.forEach((column, index) => {
3030
+ const columnPath = `${path}.columns[${index}]`;
3031
+ protocolObject(column, columnPath);
3032
+ if (isDevelopment()) assertIdentityExtras(column, columnPath);
3033
+ });
3034
+ if (isDevelopment())
3035
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
3036
+ }
3037
+ if (row.type === 'market') {
3038
+ protocolObject(row.change, `${path}.change`);
3039
+ assertMarketMetrics(row.metrics, `${path}.metrics`);
3040
+ if (row.webTable) {
3041
+ const { columns, cells } = row.webTable;
3042
+ if (
3043
+ !Array.isArray(columns) ||
3044
+ !Array.isArray(cells) ||
3045
+ columns.length !== cells.length
3046
+ )
3047
+ fail(`${path}.webTable`, 'columns and cells must match');
3048
+ const keys = new Set<string>();
3049
+ columns.forEach((column, index) => {
3050
+ protocolKey(column.key, `${path}.webTable.columns[${index}].key`);
3051
+ if (keys.has(column.key) || cells[index]?.key !== column.key)
3052
+ fail(`${path}.webTable`, 'invalid column identity');
3053
+ keys.add(column.key);
3054
+ const cell = cells[index];
3055
+ if (!['favorite', 'asset', 'text', 'sparkline'].includes(cell.kind))
3056
+ fail(`${path}.webTable.cells[${index}]`, 'unsupported cell kind');
3057
+ if (cell.kind === 'asset')
3058
+ protocolObject(cell.title, `${path}.webTable.cells[${index}].title`);
3059
+ if (
3060
+ (cell.kind === 'asset' || cell.kind === 'text') &&
3061
+ cell.secondary !== undefined &&
3062
+ !Array.isArray(cell.secondary)
3063
+ )
3064
+ fail(
3065
+ `${path}.webTable.cells[${index}].secondary`,
3066
+ 'must be an array'
3067
+ );
3068
+ if (cell.kind === 'text' && !Array.isArray(cell.primary))
3069
+ fail(`${path}.webTable.cells[${index}].primary`, 'must be an array');
3070
+ // The Web renderer spreads samples into Math.min/Math.max.
3071
+ if (
3072
+ cell.kind === 'sparkline' &&
3073
+ (!Array.isArray(cell.points) || cell.points.length > 256)
3074
+ )
3075
+ fail(
3076
+ `${path}.webTable.cells[${index}].points`,
3077
+ 'must be an array of at most 256 samples'
3078
+ );
3079
+ });
3080
+ }
3081
+ }
3082
+ }
3083
+
3084
+ function assertSnapshotProtocol(snapshot: NativeListSnapshot): void {
3085
+ protocolObject(snapshot, 'snapshot');
3086
+ if (snapshot.disclosure !== undefined) {
3087
+ protocolObject(snapshot.disclosure, 'snapshot.disclosure');
3088
+ if (typeof snapshot.disclosure.expanded !== 'boolean')
3089
+ fail('snapshot.disclosure.expanded', 'must be a boolean');
3090
+ const inset = snapshot.disclosure.expandedTrailingInset;
3091
+ if (inset !== undefined && (!Number.isFinite(inset) || inset < 0))
3092
+ fail(
3093
+ 'snapshot.disclosure.expandedTrailingInset',
3094
+ 'must be finite and nonnegative'
3095
+ );
3096
+ }
3097
+ if (snapshot.structuralTransition) {
3098
+ protocolObject(
3099
+ snapshot.structuralTransition,
3100
+ 'snapshot.structuralTransition'
3101
+ );
3102
+ protocolKey(
3103
+ snapshot.structuralTransition.id,
3104
+ 'snapshot.structuralTransition.id'
3105
+ );
3106
+ if (snapshot.structuralTransition.anchorKey !== undefined)
3107
+ protocolKey(
3108
+ snapshot.structuralTransition.anchorKey,
3109
+ 'snapshot.structuralTransition.anchorKey'
3110
+ );
3111
+ const duration = snapshot.structuralTransition.durationMs;
3112
+ if (
3113
+ duration !== undefined &&
3114
+ (!Number.isFinite(duration) || duration < 0 || duration > 2000)
3115
+ )
3116
+ fail(
3117
+ 'snapshot.structuralTransition.durationMs',
3118
+ 'must be finite within 0...2000'
3119
+ );
3120
+ }
3121
+ if (
3122
+ snapshot.theme?.successBackground !== undefined &&
3123
+ (typeof snapshot.theme.successBackground !== 'string' ||
3124
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.successBackground))
3125
+ )
3126
+ fail('theme.successBackground', 'must be a hex color');
3127
+ if (
3128
+ snapshot.theme?.rowHoverBackground !== undefined &&
3129
+ (typeof snapshot.theme.rowHoverBackground !== 'string' ||
3130
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.rowHoverBackground))
3131
+ )
3132
+ fail('theme.rowHoverBackground', 'must be a hex color');
3133
+ if (snapshot.schemaVersion !== 1) fail('snapshot.schemaVersion', 'must be 1');
3134
+ if (!Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0)
3135
+ fail('snapshot.generation', 'must be a non-negative safe integer');
3136
+ protocolObject(snapshot.layout, 'snapshot.layout');
3137
+ assertProtocolFields(snapshot.layout, 'snapshot.layout');
3138
+ if (
3139
+ snapshot.layout.orientation !== undefined &&
3140
+ !['vertical', 'horizontal'].includes(snapshot.layout.orientation)
3141
+ )
3142
+ fail('snapshot.layout.orientation', 'is not supported');
3143
+ if (!['linear', 'sectioned', 'grid', 'table'].includes(snapshot.layout.kind))
3144
+ fail('snapshot.layout.kind', 'is not supported');
3145
+ if (!Array.isArray(snapshot.rows)) fail('snapshot.rows', 'must be an array');
3146
+ if (
3147
+ snapshot.layout.kind === 'grid' &&
3148
+ (!Number.isInteger(snapshot.layout.gridColumns) ||
3149
+ (snapshot.layout.gridColumns ?? 0) < 1 ||
3150
+ (snapshot.layout.gridColumns ?? 0) > 7)
3151
+ )
3152
+ fail('snapshot.layout.gridColumns', 'must be an integer from 1 to 7');
3153
+ const keys = new Set<string>();
3154
+ for (const [index, row] of snapshot.rows.entries()) {
3155
+ assertRowProtocol(row, `rows[${index}]`);
3156
+ if (keys.has(row.key)) fail(`rows[${index}].key`, 'duplicate row identity');
3157
+ keys.add(row.key);
3158
+ }
3159
+ if (snapshot.emptyState) assertRowProtocol(snapshot.emptyState, 'emptyState');
3160
+ if (snapshot.fixedFooter)
3161
+ assertRowProtocol(snapshot.fixedFooter, 'fixedFooter');
3162
+ if (snapshot.selection) {
3163
+ if (!Array.isArray(snapshot.selection.selectedKeys))
3164
+ fail('snapshot.selection.selectedKeys', 'must be an array');
3165
+ snapshot.selection.selectedKeys.forEach((key) => {
3166
+ if (!keys.has(key))
3167
+ fail('snapshot.selection.selectedKeys', 'unknown row identity');
3168
+ });
3169
+ }
3170
+ }
3171
+
3172
+ function isRecord(value: unknown): value is Record<string, unknown> {
3173
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
3174
+ }
3175
+
3176
+ function isAllowedImageUri(value: unknown): value is string {
3177
+ // Keep native file, content, Photos and bundled-resource URIs alongside web images.
3178
+ // Android Release uses android.resource: instead of Metro's HTTP asset URLs.
3179
+ return (
3180
+ typeof value === 'string' &&
3181
+ value.trim().length > 0 &&
3182
+ (!/^[a-z][a-z\d+.-]*:/i.test(value) ||
3183
+ /^(https?|file|content|ph|assets-library|asset|res|android\.resource|blob|onekey-avatar):/i.test(
3184
+ value
3185
+ ) ||
3186
+ /^data:image\//i.test(value))
3187
+ );
3188
+ }
3189
+
3190
+ const IMAGE_FIELDS = [
3191
+ 'uri',
3192
+ 'width',
3193
+ 'height',
3194
+ 'headers',
3195
+ 'contentFit',
3196
+ 'cachePolicy',
3197
+ 'autoplay',
3198
+ 'optimizeTos',
3199
+ 'overscan',
3200
+ 'loadingStrategy',
3201
+ 'fallbackUri',
3202
+ 'fallbackUris',
3203
+ 'retryTimes',
3204
+ ];
3205
+ const ICON_FIELDS = [
3206
+ 'name',
3207
+ 'tintColor',
3208
+ 'backgroundColor',
3209
+ 'size',
3210
+ 'accessibilityLabel',
3211
+ 'hoverActionKey',
3212
+ ];
3213
+ const VISUAL_FIELDS = [
3214
+ 'kind',
3215
+ 'name',
3216
+ 'image',
3217
+ 'images',
3218
+ 'networkImage',
3219
+ 'shape',
3220
+ 'tintColor',
3221
+ 'backgroundColor',
3222
+ 'fallbackIcon',
3223
+ 'fallbackText',
3224
+ 'fallbackTextColor',
3225
+ 'overlays',
3226
+ 'borderStyle',
3227
+ 'borderColor',
3228
+ 'cornerIcon',
3229
+ ];
3230
+ const TEXT_STYLE_FIELDS = [
3231
+ 'token',
3232
+ 'fontSize',
3233
+ 'fontWeight',
3234
+ 'color',
3235
+ 'lineHeight',
3236
+ 'lines',
3237
+ 'truncate',
3238
+ 'alignment',
3239
+ 'verticalAlignment',
3240
+ 'offsetY',
3241
+ ];
3242
+ const ACCESSORY_FIELDS: Readonly<Record<string, readonly string[]>> = {
3243
+ value: ['kind', 'text', 'secondary', 'textSegments'],
3244
+ valuePair: [
3245
+ 'kind',
3246
+ 'primary',
3247
+ 'secondary',
3248
+ 'primaryFontWeight',
3249
+ 'primaryHelp',
3250
+ 'primaryTextSegments',
3251
+ 'secondaryTextSegments',
3252
+ 'primaryTone',
3253
+ 'secondaryTone',
3254
+ ],
3255
+ button: [
3256
+ 'kind',
3257
+ 'label',
3258
+ 'actionKey',
3259
+ 'disabled',
3260
+ 'testID',
3261
+ 'accessibilityLabel',
3262
+ 'textColor',
3263
+ 'backgroundColor',
3264
+ 'pressedBackgroundColor',
3265
+ 'hoverBackgroundColor',
3266
+ 'focusRingColor',
3267
+ ],
3268
+ icon: [
3269
+ 'kind',
3270
+ 'name',
3271
+ 'tintColor',
3272
+ 'buttonStyle',
3273
+ 'disabled',
3274
+ 'actionKey',
3275
+ 'testID',
3276
+ 'hoverActionKey',
3277
+ 'accessibilityLabel',
3278
+ ],
3279
+ checkbox: ['kind', 'state', 'disabled', 'loading', 'target', 'actionKey'],
3280
+ radio: ['kind', 'checked', 'disabled', 'actionKey'],
3281
+ switch: ['kind', 'value', 'disabled', 'actionKey'],
3282
+ chevron: ['kind', 'actionKey'],
3283
+ menu: ['kind', 'actionKey'],
3284
+ drag: ['kind', 'actionKey'],
3285
+ spinner: ['kind'],
3286
+ progress: ['kind', 'value'],
3287
+ };
3288
+
3289
+ const REQUIRED_ROW_FIELDS: Readonly<Record<string, readonly string[]>> = {
3290
+ identity: ['title', 'leading'],
3291
+ walletGroup: ['parent', 'children'],
3292
+ rail: ['title', 'visual'],
3293
+ activity: ['title', 'leading'],
3294
+ message: ['title', 'body', 'time'],
3295
+ dataRow: ['columns'],
3296
+ market: ['title', 'leading', 'variant', 'price', 'change'],
3297
+ mediaTile: ['title', 'variant'],
3298
+ metricCard: ['title', 'value'],
3299
+ sectionHeader: ['title', 'sectionKey'],
3300
+ action: ['title', 'actionKey'],
3301
+ buttonGroup: ['buttons'],
3302
+ system: ['variant'],
3303
+ };
3304
+
3305
+ function assertCoreRow(row: RowModel, path: string): void {
3306
+ const object = row as unknown as Record<string, unknown>;
3307
+ for (const key of REQUIRED_ROW_FIELDS[row.type]) {
3308
+ const value = object[key];
3309
+ if (value === undefined || value === null)
3310
+ fail(`${path}.${key}`, 'required field');
3311
+ if (
3312
+ ['title', 'body', 'time', 'price', 'value', 'variant'].includes(key) &&
3313
+ typeof value !== 'string'
3314
+ )
3315
+ fail(`${path}.${key}`, 'must be a string');
3316
+ }
3317
+ if (row.type === 'market') {
3318
+ if (!row.price.trim()) fail(`${path}.price`, 'must be nonblank');
3319
+ if (typeof row.change?.text !== 'string')
3320
+ fail(`${path}.change.text`, 'must be a string');
3321
+ }
3322
+ if (row.type === 'activity') {
3323
+ row.amounts?.forEach((amount, index) => {
3324
+ protocolKey(amount.key, `${path}.amounts[${index}].key`);
3325
+ if (typeof amount.text !== 'string')
3326
+ fail(`${path}.amounts[${index}].text`, 'required financial text');
3327
+ });
3328
+ if (row.fee && typeof row.fee.primary !== 'string')
3329
+ fail(`${path}.fee.primary`, 'required financial text');
3330
+ row.footerActions?.forEach((action, index) => {
3331
+ protocolKey(action.key, `${path}.footerActions[${index}].key`);
3332
+ protocolKey(action.label, `${path}.footerActions[${index}].label`);
3333
+ });
3334
+ }
3335
+ if (row.type === 'action') protocolKey(row.actionKey, `${path}.actionKey`);
3336
+ if (row.type === 'sectionHeader')
3337
+ protocolKey(row.sectionKey, `${path}.sectionKey`);
3338
+ if (
3339
+ row.type === 'system' &&
3340
+ ['retry', 'warning', 'noMatch'].includes(row.variant)
3341
+ ) {
3342
+ if (typeof object.message !== 'string')
3343
+ fail(`${path}.message`, 'must be a string');
3344
+ if (row.variant === 'retry')
3345
+ protocolKey(row.actionKey, `${path}.actionKey`);
3346
+ }
3347
+ if (row.type === 'dataRow') {
3348
+ if (!Array.isArray(row.columns) || row.columns.length === 0)
3349
+ fail(`${path}.columns`, 'required columns');
3350
+ row.columns.forEach((column, index) => {
3351
+ protocolObject(column, `${path}.columns[${index}]`);
3352
+ protocolKey(column.key, `${path}.columns[${index}].key`);
3353
+ if (typeof column.text !== 'string')
3354
+ fail(`${path}.columns[${index}].text`, 'must be a string');
3355
+ });
3356
+ }
3357
+ if (row.type === 'buttonGroup') {
3358
+ if (!Array.isArray(row.buttons) || row.buttons.length === 0)
3359
+ fail(`${path}.buttons`, 'required buttons');
3360
+ const keys = new Set<string>();
3361
+ row.buttons.forEach((button, index) => {
3362
+ const field = `${path}.buttons[${index}]`;
3363
+ protocolObject(button, field);
3364
+ protocolKey(button.key, `${field}.key`);
3365
+ protocolKey(button.actionKey, `${field}.actionKey`);
3366
+ protocolKey(button.label, `${field}.label`);
3367
+ if (keys.has(button.key)) fail(field, 'duplicate button identity');
3368
+ keys.add(button.key);
3369
+ });
3370
+ }
3371
+ for (const field of [
3372
+ 'trailing',
3373
+ 'leadingAction',
3374
+ 'titleIcon',
3375
+ 'valueIcon',
3376
+ ] as const) {
3377
+ const value = object[field];
3378
+ if (value === undefined) continue;
3379
+ // Identity title icons are decorative descriptors, not trailing controls.
3380
+ if (field === 'titleIcon' && row.type !== 'sectionHeader') continue;
3381
+ const accessories = field === 'trailing' ? value : [value];
3382
+ if (!Array.isArray(accessories))
3383
+ fail(`${path}.${field}`, 'must be an array');
3384
+ accessories.forEach((accessory, index) => {
3385
+ const entry = protocolObject(accessory, `${path}.${field}[${index}]`);
3386
+ for (const key of entry.kind === 'value'
3387
+ ? ['text']
3388
+ : entry.kind === 'valuePair'
3389
+ ? ['primary', 'secondary']
3390
+ : []) {
3391
+ if (typeof entry[key] !== 'string')
3392
+ fail(`${path}.${field}[${index}].${key}`, 'required financial text');
3393
+ }
3394
+ if (
3395
+ ['button', 'menu', 'switch'].includes(entry.kind as string) ||
3396
+ 'actionKey' in entry
3397
+ ) {
3398
+ protocolKey(entry.actionKey, `${path}.${field}[${index}].actionKey`);
3399
+ if (entry.kind === 'button')
3400
+ protocolKey(entry.label, `${path}.${field}[${index}].label`);
3401
+ }
3402
+ if (entry.kind === 'icon')
3403
+ protocolKey(entry.name, `${path}.${field}[${index}].name`);
3404
+ });
3405
+ }
3406
+ }
3407
+
3408
+ function pickFields(
3409
+ object: Record<string, unknown>,
3410
+ fields: readonly string[]
3411
+ ): Record<string, unknown> {
3412
+ return Object.fromEntries(
3413
+ Object.entries(object).filter(([key]) => fields.includes(key))
3414
+ );
3415
+ }
3416
+
3417
+ function sanitizeImage(value: unknown): Record<string, unknown> | undefined {
3418
+ if (
3419
+ !isRecord(value) ||
3420
+ !isAllowedImageUri(value.uri) ||
3421
+ typeof value.width !== 'number' ||
3422
+ !Number.isFinite(value.width) ||
3423
+ value.width <= 0 ||
3424
+ typeof value.height !== 'number' ||
3425
+ !Number.isFinite(value.height) ||
3426
+ value.height <= 0
3427
+ )
3428
+ return undefined;
3429
+ const next = pickFields(value, IMAGE_FIELDS);
3430
+ next.width = Math.min(MAX_IMAGE_EDGE, value.width);
3431
+ next.height = Math.min(MAX_IMAGE_EDGE, value.height);
3432
+ if (next.headers !== undefined) {
3433
+ if (!isRecord(next.headers)) delete next.headers;
3434
+ else
3435
+ next.headers = Object.fromEntries(
3436
+ Object.entries(next.headers)
3437
+ .filter(
3438
+ ([key, item]) =>
3439
+ key.trim() &&
3440
+ key.length <= MAX_HEADER_LENGTH &&
3441
+ typeof item === 'string' &&
3442
+ item.length <= MAX_HEADER_LENGTH
3443
+ )
3444
+ .slice(0, MAX_IMAGE_HEADERS)
3445
+ );
3446
+ }
3447
+ if (next.fallbackUris !== undefined) {
3448
+ if (Array.isArray(next.fallbackUris))
3449
+ next.fallbackUris = next.fallbackUris.filter(isAllowedImageUri);
3450
+ else delete next.fallbackUris;
3451
+ }
3452
+ if (next.fallbackUri !== undefined && !isAllowedImageUri(next.fallbackUri))
3453
+ delete next.fallbackUri;
3454
+ if (
3455
+ next.overscan !== undefined &&
3456
+ (typeof next.overscan !== 'number' ||
3457
+ !Number.isFinite(next.overscan) ||
3458
+ next.overscan < 1 ||
3459
+ next.overscan > 4)
3460
+ )
3461
+ delete next.overscan;
3462
+ if (
3463
+ next.retryTimes !== undefined &&
3464
+ (typeof next.retryTimes !== 'number' ||
3465
+ !Number.isFinite(next.retryTimes) ||
3466
+ next.retryTimes < 0)
3467
+ )
3468
+ delete next.retryTimes;
3469
+ const options: Readonly<Record<string, readonly string[]>> = {
3470
+ contentFit: ['cover', 'contain', 'fill', 'center'],
3471
+ cachePolicy: ['memory-disk', 'memory', 'disk', 'none'],
3472
+ loadingStrategy: ['static', 'skeleton', 'none'],
3473
+ };
3474
+ for (const [key, allowed] of Object.entries(options))
3475
+ if (next[key] !== undefined && !allowed.includes(next[key] as string))
3476
+ delete next[key];
3477
+ for (const key of ['autoplay', 'optimizeTos'])
3478
+ if (next[key] !== undefined && typeof next[key] !== 'boolean')
3479
+ delete next[key];
3480
+ return next;
3481
+ }
3482
+
3483
+ const NESTED_DECORATION_FIELDS: Readonly<Record<string, readonly string[]>> = {
3484
+ webTable: ['columns', 'cells', 'testID', 'draggable', 'contextMenuActionKey'],
3485
+ columns: [
3486
+ 'key',
3487
+ 'text',
3488
+ 'textSegments',
3489
+ 'titleIcon',
3490
+ 'secondaryTitleIcon',
3491
+ 'secondaryLeadingText',
3492
+ 'secondaryText',
3493
+ 'secondaryTextSegments',
3494
+ 'weight',
3495
+ 'alignment',
3496
+ 'tone',
3497
+ 'secondaryTone',
3498
+ 'width',
3499
+ 'minWidth',
3500
+ 'flex',
3501
+ 'paddingStart',
3502
+ 'paddingEnd',
3503
+ ],
3504
+ cells: [
3505
+ 'key',
3506
+ 'kind',
3507
+ 'active',
3508
+ 'disabled',
3509
+ 'testID',
3510
+ 'hoverActionKey',
3511
+ 'actionKey',
3512
+ 'accessibilityLabel',
3513
+ 'leading',
3514
+ 'title',
3515
+ 'secondary',
3516
+ 'lineGap',
3517
+ 'secondaryBadges',
3518
+ 'hoverImages',
3519
+ 'hoverSecondary',
3520
+ 'hoverActionLabel',
3521
+ 'badges',
3522
+ 'primary',
3523
+ 'partGap',
3524
+ 'points',
3525
+ 'width',
3526
+ 'height',
3527
+ 'strokeColor',
3528
+ 'fillColor',
3529
+ ],
3530
+ badges: [
3531
+ 'key',
3532
+ 'text',
3533
+ 'tone',
3534
+ 'iconName',
3535
+ 'icon',
3536
+ 'textColor',
3537
+ 'backgroundColor',
3538
+ 'actionKey',
3539
+ 'accessibilityLabel',
3540
+ 'style',
3541
+ ],
3542
+ overlays: [
3543
+ 'position',
3544
+ 'size',
3545
+ 'width',
3546
+ 'height',
3547
+ 'padding',
3548
+ 'offset',
3549
+ 'offsetX',
3550
+ 'offsetY',
3551
+ 'image',
3552
+ 'fallbackIcon',
3553
+ 'name',
3554
+ 'text',
3555
+ 'fontWeight',
3556
+ 'tintColor',
3557
+ 'backgroundColor',
3558
+ ],
3559
+ primaryHelp: ['actionKey', 'presentation', 'underline'],
3560
+ valueHelp: ['actionKey', 'presentation', 'underline'],
3561
+ };
3562
+
3563
+ function sanitizeDecoration(value: unknown, field: string): unknown {
3564
+ if (value === undefined || value === null) return undefined;
3565
+ if (
3566
+ !Array.isArray(value) &&
3567
+ [
3568
+ 'image',
3569
+ 'networkImage',
3570
+ 'thumbnail',
3571
+ 'source',
3572
+ 'images',
3573
+ 'hoverImages',
3574
+ ].includes(field)
3575
+ )
3576
+ return sanitizeImage(value);
3577
+ if (
3578
+ [
3579
+ 'titleImage',
3580
+ 'titleIcon',
3581
+ 'secondaryTitleIcon',
3582
+ 'fallbackIcon',
3583
+ 'cornerIcon',
3584
+ 'media',
3585
+ ].includes(field) &&
3586
+ !isRecord(value)
3587
+ )
3588
+ return undefined;
3589
+ if (field === 'style' && typeof value !== 'string' && !isRecord(value))
3590
+ return undefined;
3591
+ if (
3592
+ ['badges', 'overlays'].includes(field) &&
3593
+ !Array.isArray(value) &&
3594
+ !isRecord(value)
3595
+ )
3596
+ return undefined;
3597
+ if (field === 'style' && typeof value === 'string')
3598
+ return value === 'subscript' ? value : undefined;
3599
+ if (Array.isArray(value)) {
3600
+ const items = value.map((item) => sanitizeDecoration(item, field));
3601
+ return field === 'hoverImages'
3602
+ ? items.map((item) => item ?? null)
3603
+ : items.filter((item) => item !== undefined);
3604
+ }
3605
+ if (!isRecord(value)) return value;
3606
+ let object = value;
3607
+ if (field === 'titleImage') {
3608
+ const image = sanitizeImage(value.image);
3609
+ if (!image) return undefined;
3610
+ const edge = Math.min(
3611
+ 40,
3612
+ Math.max(
3613
+ 1,
3614
+ Math.round(Math.min(image.width as number, image.height as number))
3615
+ )
3616
+ );
3617
+ object = {
3618
+ ...pickFields(value, ['image', 'accessibilityLabel', 'hoverActionKey']),
3619
+ image: { ...image, width: edge, height: edge },
3620
+ };
3621
+ } else if (
3622
+ ['titleIcon', 'secondaryTitleIcon', 'fallbackIcon', 'cornerIcon'].includes(
3623
+ field
3624
+ ) &&
3625
+ value.kind === undefined
3626
+ ) {
3627
+ if (typeof value.name !== 'string' || !value.name.trim()) return undefined;
3628
+ object = pickFields(value, ICON_FIELDS);
3629
+ } else if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
3630
+ object = pickFields(value, VISUAL_FIELDS);
3631
+ } else if (field === 'media') {
3632
+ object = pickFields(value, ['source', 'probeOrder']);
3633
+ }
3634
+ if (
3635
+ field === 'trailing' ||
3636
+ (['leadingAction', 'titleIcon', 'valueIcon'].includes(field) &&
3637
+ object.kind !== undefined)
3638
+ ) {
3639
+ const fields = ACCESSORY_FIELDS[object.kind as string];
3640
+ if (fields) object = pickFields(object, fields);
3641
+ } else if (field === 'buttons')
3642
+ object = pickFields(object, [
3643
+ 'key',
3644
+ 'label',
3645
+ 'actionKey',
3646
+ 'disabled',
3647
+ 'loading',
3648
+ 'testID',
3649
+ 'accessibilityLabel',
3650
+ ]);
3651
+ else if (field === 'container')
3652
+ object = pickFields(object, [
3653
+ 'height',
3654
+ 'backgroundColor',
3655
+ 'opacity',
3656
+ 'cornerRadius',
3657
+ 'borderWidth',
3658
+ 'borderColor',
3659
+ 'contentVerticalAlignment',
3660
+ ]);
3661
+ else if (field === 'imageStyle')
3662
+ object = pickFields(object, [
3663
+ 'width',
3664
+ 'height',
3665
+ 'shape',
3666
+ 'cornerRadius',
3667
+ 'contentFit',
3668
+ ]);
3669
+ else if (field === 'style')
3670
+ object = pickFields(object, [
3671
+ ...TEXT_STYLE_FIELDS,
3672
+ 'container',
3673
+ ...new Set(Object.values(ROW_BOX_STYLE_KEYS_BY_TYPE).flat()),
3674
+ ...new Set(Object.values(TEXT_STYLE_KEYS_BY_ROW_TYPE).flat()),
3675
+ ...new Set(Object.values(EXTRA_STYLE_KEYS_BY_ROW_TYPE).flat()),
3676
+ 'height',
3677
+ ]);
3678
+ else if (
3679
+ [
3680
+ 'title',
3681
+ 'subtitle',
3682
+ 'tertiary',
3683
+ 'body',
3684
+ 'time',
3685
+ 'price',
3686
+ 'change',
3687
+ 'value',
3688
+ 'valueSecondary',
3689
+ 'columnSecondary',
3690
+ 'primaryAmount',
3691
+ 'secondaryAmount',
3692
+ 'description',
3693
+ 'status',
3694
+ 'trend',
3695
+ 'message',
3696
+ 'actionText',
3697
+ ].includes(field) &&
3698
+ !('text' in object)
3699
+ ) {
3700
+ object = pickFields(object, TEXT_STYLE_FIELDS);
3701
+ }
3702
+ if (NESTED_DECORATION_FIELDS[field])
3703
+ object = pickFields(object, NESTED_DECORATION_FIELDS[field]);
3704
+ if (
3705
+ [
3706
+ 'textSegments',
3707
+ 'primaryTextSegments',
3708
+ 'secondaryTextSegments',
3709
+ 'priceSegments',
3710
+ 'segments',
3711
+ ].includes(field)
3712
+ )
3713
+ object = pickFields(object, ['text', 'style']);
3714
+ if (field === 'subtitleSegments')
3715
+ object = pickFields(object, [
3716
+ 'text',
3717
+ 'style',
3718
+ 'textSegments',
3719
+ 'tone',
3720
+ 'separatorBefore',
3721
+ ]);
3722
+ const styleObject =
3723
+ ['style', 'imageStyle', 'container'].includes(field) ||
3724
+ TEXT_STYLE_FIELDS.some((key) => key in object);
3725
+ const next: Record<string, unknown> = {};
3726
+ for (const [key, item] of Object.entries(object)) {
3727
+ if (item === undefined || item === null) continue;
3728
+ if (
3729
+ (/color$/i.test(key) || /background$/i.test(key)) &&
3730
+ (typeof item !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(item))
3731
+ )
3732
+ continue;
3733
+ if (
3734
+ /TextSegments$/.test(key) ||
3735
+ [
3736
+ 'textSegments',
3737
+ 'priceSegments',
3738
+ 'subtitleSegments',
3739
+ 'segments',
3740
+ ].includes(key)
3741
+ ) {
3742
+ if (
3743
+ !Array.isArray(item) ||
3744
+ item.some(
3745
+ (segment) => !isRecord(segment) || typeof segment.text !== 'string'
3746
+ )
3747
+ )
3748
+ continue;
3749
+ }
3750
+ if (
3751
+ styleObject &&
3752
+ PROTOCOL_NUMBER_FIELDS.has(key) &&
3753
+ typeof item !== 'number'
3754
+ )
3755
+ continue;
3756
+ if (
3757
+ key === 'token' &&
3758
+ (typeof item !== 'string' || !Object.hasOwn(TYPOGRAPHY_TOKENS, item))
3759
+ )
3760
+ continue;
3761
+ if (
3762
+ key === 'fontWeight' &&
3763
+ !['regular', 'medium', 'semibold', 'bold'].includes(item as string)
3764
+ )
3765
+ continue;
3766
+ if (
3767
+ [
3768
+ 'disabled',
3769
+ 'loading',
3770
+ 'checked',
3771
+ 'selected',
3772
+ 'separator',
3773
+ 'hideLeading',
3774
+ 'pressDisabled',
3775
+ 'draggable',
3776
+ 'active',
3777
+ 'autoplay',
3778
+ ].includes(key) &&
3779
+ typeof item !== 'boolean'
3780
+ )
3781
+ continue;
3782
+ if (key === 'primaryFontWeight' && item !== 'medium') continue;
3783
+ if (key === 'buttonStyle' && item !== 'tertiary') continue;
3784
+ if (key === 'hoverActionKey' && (typeof item !== 'string' || !item.trim()))
3785
+ continue;
3786
+ if (key === 'accessibilityLabel' && typeof item !== 'string') continue;
3787
+ if (
3788
+ (field === 'style' || PROTOCOL_NUMBER_FIELDS.has(key)) &&
3789
+ typeof item !== 'object' &&
3790
+ typeof item === 'number' &&
3791
+ (!Number.isFinite(item) ||
3792
+ (item < 0 && !['offsetX', 'offsetY'].includes(key)))
3793
+ )
3794
+ continue;
3795
+ if (
3796
+ field === 'style' &&
3797
+ PROTOCOL_NUMBER_FIELDS.has(key) &&
3798
+ typeof item !== 'number'
3799
+ )
3800
+ continue;
3801
+ if (
3802
+ key === 'leadingContentMaxWidthRatio' &&
3803
+ (typeof item !== 'number' || item <= 0 || item > 1)
3804
+ )
3805
+ continue;
3806
+ const normalized = sanitizeDecoration(
3807
+ item,
3808
+ field === 'style' && key === 'image' ? 'imageStyle' : key
3809
+ );
3810
+ if (normalized !== undefined) next[key] = normalized;
3811
+ }
3812
+ if (field === 'titleImage') {
3813
+ // The nested image was already normalized with title-specific geometry.
3814
+ if (!next.image) return undefined;
3815
+ }
3816
+ if (field === 'media' && (!next.source || !Array.isArray(next.probeOrder)))
3817
+ return undefined;
3818
+ if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
3819
+ if (next.kind === 'image' && !next.image)
3820
+ return {
3821
+ kind: 'token',
3822
+ ...pickFields(next, [
3823
+ 'fallbackIcon',
3824
+ 'fallbackText',
3825
+ 'fallbackTextColor',
3826
+ ]),
3827
+ };
3828
+ if (
3829
+ next.kind === 'stackedImages' &&
3830
+ (!Array.isArray(next.images) || next.images.length < 2)
3831
+ )
3832
+ return { kind: 'token' };
3833
+ if (
3834
+ next.kind === 'icon' &&
3835
+ (typeof next.name !== 'string' || !next.name.trim())
3836
+ )
3837
+ return { kind: 'token' };
3838
+ if (
3839
+ ![
3840
+ 'token',
3841
+ 'account',
3842
+ 'wallet',
3843
+ 'network',
3844
+ 'image',
3845
+ 'icon',
3846
+ 'stackedImages',
3847
+ ].includes(next.kind as string)
3848
+ )
3849
+ return { kind: 'token' };
3850
+ }
3851
+ if (
3852
+ field === 'overlays' &&
3853
+ (!['topLeft', 'bottomRight'].includes(next.position as string) ||
3854
+ (!next.image && !next.name && !next.text))
3855
+ )
3856
+ return undefined;
3857
+ if (
3858
+ field === 'trailing' &&
3859
+ next.kind === 'icon' &&
3860
+ !('actionKey' in value) &&
3861
+ (typeof next.name !== 'string' || !next.name.trim())
3862
+ )
3863
+ return undefined;
3864
+ if (
3865
+ field === 'trailing' &&
3866
+ ![
3867
+ 'value',
3868
+ 'valuePair',
3869
+ 'button',
3870
+ 'checkbox',
3871
+ 'radio',
3872
+ 'switch',
3873
+ 'chevron',
3874
+ 'menu',
3875
+ 'drag',
3876
+ 'icon',
3877
+ 'spinner',
3878
+ 'progress',
3879
+ ].includes(next.kind as string) &&
3880
+ !('actionKey' in value)
3881
+ )
3882
+ return undefined;
3883
+ if (
3884
+ field === 'badges' &&
3885
+ (typeof next.key !== 'string' ||
3886
+ (!next.text && !next.iconName && !next.icon))
3887
+ )
3888
+ return undefined;
3889
+ if (next.kind === 'sparkline') {
3890
+ const points = Array.isArray(value.points)
3891
+ ? value.points
3892
+ .filter(
3893
+ (point) => typeof point === 'number' && Number.isFinite(point)
3894
+ )
3895
+ .slice(0, 256)
3896
+ : [];
3897
+ // Preserve the table's column identity even when its optional drawing fails.
3898
+ return points.length < 2
3899
+ ? { key: next.key, kind: 'text', primary: [] }
3900
+ : { ...next, points };
3901
+ }
3902
+ return next;
3903
+ }
3904
+
3905
+ function sanitizeMarketMetrics(value: unknown): unknown {
3906
+ if (!Array.isArray(value)) return value;
3907
+ return value.map((metric) => {
3908
+ const next = pickFields(
3909
+ metric as Record<string, unknown>,
3910
+ MARKET_METRIC_FIELDS
3911
+ );
3912
+ for (const field of ['textSegments', 'secondaryTextSegments'] as const) {
3913
+ if (next[field] !== undefined)
3914
+ next[field] = sanitizeDecoration(next[field], field);
3915
+ }
3916
+ return next;
3917
+ });
3918
+ }
3919
+
3920
+ function sanitizeRowForProduction(row: RowModel): RowModel {
3921
+ const object = protocolObject(row, 'row');
3922
+ const fields = ROW_FIELDS[row.type];
3923
+ if (!fields) return row;
3924
+ const next = pickFields(object, fields);
3925
+ for (const [field, value] of Object.entries(next)) {
3926
+ if (
3927
+ (/color$/i.test(field) || /background$/i.test(field)) &&
3928
+ (typeof value !== 'string' ||
3929
+ !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))
3930
+ ) {
3931
+ delete next[field];
3932
+ continue;
3933
+ }
3934
+ if (field === 'parent' && isRecord(value))
3935
+ next[field] = sanitizeRowForProduction(value as unknown as RowModel);
3936
+ else if (field === 'children' && Array.isArray(value))
3937
+ next[field] = value.map((child) =>
3938
+ sanitizeRowForProduction(child as RowModel)
3939
+ );
3940
+ else {
3941
+ const normalized =
3942
+ row.type === 'market' && field === 'metrics'
3943
+ ? sanitizeMarketMetrics(value)
3944
+ : sanitizeDecoration(value, field);
3945
+ if (normalized === undefined) delete next[field];
3946
+ else next[field] = normalized;
3947
+ }
3948
+ }
3949
+ if (isRecord(next.style))
3950
+ next.style = pickFields(next.style, [
3951
+ 'container',
3952
+ ...ROW_BOX_STYLE_KEYS_BY_TYPE[row.type],
3953
+ ...(TEXT_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? []),
3954
+ ...(EXTRA_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? []),
3955
+ ]);
3956
+ return sameJsonValue(row, next) ? row : (next as unknown as RowModel);
3957
+ }
3958
+
3959
+ /** Empty images and optional nulls share one meaning before strict assertions. */
3960
+ function normalizeEmptyImages(value: unknown, field = ''): unknown {
3961
+ if (value === null || value === undefined || typeof value !== 'object')
3962
+ return value;
3963
+ if (Array.isArray(value)) {
3964
+ const next = value.map((item) => normalizeEmptyImages(item, field));
3965
+ return next.every((item, index) => item === value[index])
3966
+ ? value
3967
+ : next.filter((item) => item !== undefined);
3968
+ }
3969
+ const object = value as Record<string, unknown>;
3970
+ if (
3971
+ typeof object.uri === 'string' &&
3972
+ !object.uri.trim() &&
3973
+ 'width' in object &&
3974
+ 'height' in object
3975
+ )
3976
+ return undefined;
3977
+ let changed = false;
3978
+ const next: Record<string, unknown> = {};
3979
+ for (const [key, item] of Object.entries(object)) {
3980
+ const optional =
3981
+ object.type &&
3982
+ ![
3983
+ 'key',
3984
+ 'type',
3985
+ ...(REQUIRED_ROW_FIELDS[object.type as string] ?? []),
3986
+ ].includes(key);
3987
+ if (
3988
+ item === undefined ||
3989
+ (item === null &&
3990
+ optional &&
3991
+ !(object.type === 'market' && key === 'metrics')) ||
3992
+ (['priceSegments', 'subtitleSegments'].includes(key) &&
3993
+ Array.isArray(item) &&
3994
+ item.length === 0)
3995
+ ) {
3996
+ changed = true;
3997
+ continue;
3998
+ }
3999
+ const normalized =
4000
+ field === 'headers' ? item : normalizeEmptyImages(item, key);
4001
+ if (normalized !== undefined) next[key] = normalized;
4002
+ if (normalized !== item) changed = true;
4003
+ }
4004
+ if (
4005
+ (field === 'media' &&
4006
+ object.source !== undefined &&
4007
+ next.source === undefined) ||
4008
+ (field === 'titleImage' &&
4009
+ object.image !== undefined &&
4010
+ next.image === undefined)
4011
+ )
4012
+ return undefined;
4013
+ if (
4014
+ ['leading', 'visual', 'secondaryLeading'].includes(field) &&
4015
+ next.kind === 'image' &&
4016
+ !next.image
4017
+ )
4018
+ return { kind: 'token' };
4019
+ if (field === 'overlays' && object.image !== undefined && !next.image)
4020
+ return undefined;
4021
+ return changed ? next : value;
4022
+ }
4023
+
4024
+ function normalizeSnapshotForProduction(
4025
+ snapshot: NativeListSnapshot
4026
+ ): NativeListSnapshot {
4027
+ if (!Array.isArray(snapshot.rows)) return snapshot;
4028
+ let rows = snapshot.rows.map(sanitizeRowForProduction);
4029
+ rows = rows.map((row, index) => {
4030
+ if (!row.groupId) return row;
4031
+ const previous = rows[index - 1]?.groupId === row.groupId;
4032
+ const following = rows[index + 1]?.groupId === row.groupId;
4033
+ return {
4034
+ ...row,
4035
+ groupPosition: previous
4036
+ ? following
4037
+ ? 'middle'
4038
+ : 'last'
4039
+ : following
4040
+ ? 'first'
4041
+ : 'single',
4042
+ };
4043
+ });
4044
+ const next = {
4045
+ ...snapshot,
4046
+ rows,
4047
+ ...(snapshot.emptyState
4048
+ ? {
4049
+ emptyState: sanitizeRowForProduction(
4050
+ snapshot.emptyState
4051
+ ) as NativeListSnapshot['emptyState'],
4052
+ }
4053
+ : {}),
4054
+ ...(snapshot.fixedFooter
4055
+ ? {
4056
+ fixedFooter: sanitizeRowForProduction(
4057
+ snapshot.fixedFooter
4058
+ ) as NativeListSnapshot['fixedFooter'],
4059
+ }
4060
+ : {}),
4061
+ };
4062
+ if (snapshot.theme)
4063
+ next.theme = sanitizeDecoration(
4064
+ snapshot.theme,
4065
+ 'theme'
4066
+ ) as NativeListSnapshot['theme'];
4067
+ if (snapshot.listStyle)
4068
+ next.listStyle = sanitizeDecoration(
4069
+ snapshot.listStyle,
4070
+ 'style'
4071
+ ) as NativeListSnapshot['listStyle'];
4072
+ if (snapshot.selection && Array.isArray(snapshot.selection.selectedKeys)) {
4073
+ const selectable = new Set(
4074
+ rows
4075
+ .filter(
4076
+ (row) =>
4077
+ !row.disabled &&
4078
+ ![
4079
+ 'sectionHeader',
4080
+ 'action',
4081
+ 'system',
4082
+ 'buttonGroup',
4083
+ 'market',
4084
+ 'walletGroup',
4085
+ ].includes(row.type)
4086
+ )
4087
+ .map((row) => row.key)
4088
+ );
4089
+ const selectedKeys = [
4090
+ ...new Set(
4091
+ snapshot.selection.selectedKeys.filter((key) => selectable.has(key))
4092
+ ),
4093
+ ];
4094
+ next.selection = {
4095
+ ...snapshot.selection,
4096
+ selectedKeys:
4097
+ snapshot.selection.mode === 'none'
4098
+ ? []
4099
+ : snapshot.selection.mode === 'single'
4100
+ ? selectedKeys.slice(0, 1)
4101
+ : selectedKeys,
4102
+ };
4103
+ }
4104
+ return sameJsonValue(snapshot, next) ? snapshot : next;
4105
+ }
4106
+
4107
+ export function validateSnapshot(
4108
+ snapshot: NativeListSnapshot
4109
+ ): NativeListSnapshot {
4110
+ assertPlainSerializable(snapshot, 'snapshot', new Set<object>(), false);
4111
+ protocolObject(snapshot, 'snapshot');
4112
+ const normalized = normalizeEmptyImages(snapshot) as NativeListSnapshot;
4113
+ if (Array.isArray(normalized.rows)) {
4114
+ normalized.rows.forEach((row, index) => {
4115
+ if (row.type === 'market')
4116
+ assertMarketMetrics(row.metrics, `snapshot.rows[${index}].metrics`);
4117
+ });
4118
+ }
4119
+ const canonical = isDevelopment()
4120
+ ? normalized
4121
+ : normalizeSnapshotForProduction(normalized);
4122
+ assertPlainSerializable(canonical, 'snapshot', new Set<object>());
4123
+ if (isDevelopment()) assertSnapshotContract(canonical);
4124
+ assertSnapshotProtocol(canonical);
4125
+ return normalizeSnapshotStyles(canonical);
4126
+ }
4127
+
4128
+ const ownedNativeSnapshots = new WeakMap<
4129
+ NativeListSnapshot,
4130
+ ReadonlyMap<string, number>
4131
+ >();
4132
+
4133
+ function capturePlainData<T>(value: T, seen = new Map<object, object>()): T {
4134
+ if (value === null || typeof value !== 'object') return value;
4135
+ const previous = seen.get(value);
4136
+ if (previous) return previous as T;
4137
+ const copy: Record<string, unknown> | unknown[] = Array.isArray(value)
4138
+ ? new Array(value.length)
4139
+ : Object.create(Object.getPrototypeOf(value));
4140
+ seen.set(value, copy);
4141
+ const captureKey = (key: string) => {
4142
+ Object.defineProperty(copy, key, {
4143
+ value: capturePlainData((value as Record<string, unknown>)[key], seen),
4144
+ enumerable: true,
4145
+ writable: true,
4146
+ configurable: true,
4147
+ });
4148
+ };
4149
+ if (Array.isArray(value)) {
4150
+ for (let index = 0; index < value.length; index += 1) {
4151
+ if (index in value) captureKey(String(index));
4152
+ }
4153
+ Object.keys(value).forEach((key) => {
4154
+ const index = Number(key);
4155
+ if (
4156
+ Number.isInteger(index) &&
4157
+ index >= 0 &&
4158
+ index < value.length &&
4159
+ String(index) === key
4160
+ )
4161
+ return;
4162
+ captureKey(key);
4163
+ });
4164
+ } else {
4165
+ Object.keys(value).forEach(captureKey);
4166
+ }
4167
+ return copy as T;
4168
+ }
4169
+
4170
+ function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
4171
+ if (value === null || typeof value !== 'object' || seen.has(value))
4172
+ return value;
4173
+ seen.add(value);
4174
+ Object.values(value).forEach((item) => deepFreeze(item, seen));
4175
+ return Object.freeze(value);
4176
+ }
4177
+
4178
+ /** Capture caller data once before validation, including accessor values. */
4179
+ export function captureNativeListInput<T>(value: T): T {
4180
+ return capturePlainData(value);
4181
+ }
4182
+
4183
+ /** Private native-wrapper ownership; exported validators keep their public identity. */
4184
+ export function ownValidatedNativeSnapshot(
4185
+ snapshot: NativeListSnapshot
4186
+ ): NativeListSnapshot {
4187
+ const owned = deepFreeze(snapshot);
4188
+ ownedNativeSnapshots.set(
4189
+ owned,
4190
+ new Map(owned.rows.map((row, index) => [row.key, index]))
4191
+ );
4192
+ return owned;
4193
+ }
4194
+
4195
+ /**
4196
+ * Resolves typography tokens to numbers. Returns the original snapshot when
4197
+ * nothing needs resolving, so the common no-style path keeps object identity.
4198
+ */
4199
+ function normalizeSnapshotStyles(
4200
+ snapshot: NativeListSnapshot
4201
+ ): NativeListSnapshot {
4202
+ let changed = false;
4203
+ const rows = snapshot.rows.map((row) => {
4204
+ const next = normalizeRowStyles(row);
4205
+ if (next !== row) changed = true;
4206
+ return next;
4207
+ });
4208
+ const emptyState = snapshot.emptyState
4209
+ ? normalizeRowStyles(snapshot.emptyState)
4210
+ : snapshot.emptyState;
4211
+ const fixedFooter = snapshot.fixedFooter
4212
+ ? normalizeRowStyles(snapshot.fixedFooter)
4213
+ : snapshot.fixedFooter;
4214
+ if (
4215
+ !changed &&
4216
+ emptyState === snapshot.emptyState &&
4217
+ fixedFooter === snapshot.fixedFooter
4218
+ ) {
4219
+ return snapshot;
4220
+ }
4221
+ return {
4222
+ ...snapshot,
4223
+ rows,
4224
+ ...(emptyState !== undefined ? { emptyState } : {}),
4225
+ ...(fixedFooter !== undefined ? { fixedFooter } : {}),
4226
+ };
4227
+ }
4228
+
4229
+ type PatchValues<Patch = RowPatch> = Patch extends RowPatch
4230
+ ? Omit<Patch, 'changes'> & {
4231
+ changes: {
4232
+ [Key in keyof Patch['changes']]: Exclude<Patch['changes'][Key], null>;
4233
+ };
4234
+ }
4235
+ : never;
4236
+
4237
+ function assertPatchChanges(patch: PatchValues, index: number): void {
4238
+ const path = `patches[${index}].changes`;
4239
+ const patchedStyle = (patch.changes as { style?: unknown }).style;
4240
+ if (patchedStyle !== undefined) {
4241
+ assertRowStyle({ type: patch.type, style: patchedStyle } as RowModel, path);
4242
+ }
4243
+ // OneKey patch: partial balance updates retain a valid, current accessibility label.
4244
+ if ('accessibilityLabel' in patch.changes) {
4245
+ assertText(patch.changes.accessibilityLabel, `${path}.accessibilityLabel`);
4246
+ }
4247
+ // OneKey patch: partial updates may refer to an existing height but still require a valid policy.
4248
+ if (
4249
+ 'heightRounding' in patch.changes &&
4250
+ patch.changes.heightRounding !== undefined &&
4251
+ !['floor', 'nearest'].includes(patch.changes.heightRounding)
4252
+ )
4253
+ fail(`${path}.heightRounding`, 'must be floor or nearest');
4254
+ if (
4255
+ patch.changes.revision !== undefined &&
4256
+ (!Number.isSafeInteger(patch.changes.revision) ||
4257
+ patch.changes.revision < 0)
4258
+ ) {
4259
+ fail(`${path}.revision`, 'must be a non-negative safe integer');
4260
+ }
4261
+
4262
+ switch (patch.type) {
4263
+ case 'identity':
4264
+ if (
4265
+ patch.changes.contentHeight !== undefined &&
4266
+ patch.changes.contentHeight !== 'auto'
4267
+ ) {
4268
+ fail(`${path}.contentHeight`, 'must be auto');
4269
+ }
4270
+ if (
4271
+ patch.changes.subtitleLines !== undefined &&
4272
+ ![0, 1, 2].includes(patch.changes.subtitleLines)
4273
+ ) {
4274
+ fail(`${path}.subtitleLines`, 'must be 0, 1, or 2');
4275
+ }
4276
+ if (patch.changes.longPressActionKey !== undefined) {
4277
+ assertKey(
4278
+ patch.changes.longPressActionKey,
4279
+ `${path}.longPressActionKey`
4280
+ );
4281
+ }
4282
+ assertText(patch.changes.title, `${path}.title`);
4283
+ if ((patch.changes.titleSuffixes?.length ?? 0) > 3)
4284
+ fail(`${path}.titleSuffixes`, 'supports at most 3 suffixes');
4285
+ patch.changes.titleSuffixes?.forEach((suffix, index) => {
4286
+ assertText(suffix.text, `${path}.titleSuffixes[${index}].text`);
4287
+ if (!['secondary', 'disabled'].includes(suffix.tone))
4288
+ fail(
4289
+ `${path}.titleSuffixes[${index}].tone`,
4290
+ 'must be secondary or disabled'
4291
+ );
4292
+ if (
4293
+ suffix.maxWidth !== undefined &&
4294
+ (!Number.isFinite(suffix.maxWidth) ||
4295
+ suffix.maxWidth < 0 ||
4296
+ suffix.maxWidth > 4096)
4297
+ )
4298
+ fail(
4299
+ `${path}.titleSuffixes[${index}].maxWidth`,
4300
+ 'must be finite within 0...4096'
4301
+ );
4302
+ });
4303
+ assertIdentityExtras(patch.changes, path);
4304
+ assertText(patch.changes.subtitle, `${path}.subtitle`);
4305
+ assertText(patch.changes.tertiary, `${path}.tertiary`);
4306
+ if (
4307
+ patch.changes.tertiaryTone !== undefined &&
4308
+ !['secondary', 'info'].includes(patch.changes.tertiaryTone)
4309
+ ) {
4310
+ fail(`${path}.tertiaryTone`, 'must be secondary or info');
4311
+ }
4312
+ assertLeadingVisual(patch.changes.leading, `${path}.leading`);
4313
+ assertTrailingAccessories(
4314
+ patch.changes.leadingAction ? [patch.changes.leadingAction] : undefined,
4315
+ `${path}.leadingAction`
4316
+ );
4317
+ if ((patch.changes.badges?.length ?? 0) > MAX_BADGES) {
4318
+ fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
4319
+ }
4320
+ if ((patch.changes.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
4321
+ fail(
4322
+ `${path}.trailing`,
4323
+ `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
4324
+ );
4325
+ }
4326
+ assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
4327
+ break;
4328
+ case 'rail':
4329
+ assertText(patch.changes.title, `${path}.title`);
4330
+ assertLeadingVisual(patch.changes.visual, `${path}.visual`);
4331
+ break;
4332
+ case 'activity':
4333
+ assertActivity(patch.changes, path);
4334
+ assertText(patch.changes.title, `${path}.title`);
4335
+ assertText(patch.changes.description, `${path}.description`);
4336
+ assertText(patch.changes.status, `${path}.status`);
4337
+ assertText(patch.changes.primaryAmount, `${path}.primaryAmount`);
4338
+ assertText(patch.changes.secondaryAmount, `${path}.secondaryAmount`);
4339
+ assertLeadingVisual(patch.changes.leading, `${path}.leading`);
1925
4340
  assertLeadingVisual(
1926
4341
  patch.changes.secondaryLeading,
1927
4342
  `${path}.secondaryLeading`
@@ -1934,14 +4349,20 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
1934
4349
  }
1935
4350
  break;
1936
4351
  case 'message':
4352
+ if (
4353
+ patch.changes.presentation !== undefined &&
4354
+ patch.changes.presentation !== 'inlineWarning'
4355
+ ) {
4356
+ fail(`${path}.presentation`, 'must be inlineWarning');
4357
+ }
1937
4358
  assertText(patch.changes.title, `${path}.title`);
1938
4359
  assertText(patch.changes.body, `${path}.body`);
1939
4360
  assertText(patch.changes.time, `${path}.time`);
1940
4361
  if (
1941
4362
  patch.changes.bodyLines !== undefined &&
1942
- ![1, 2, 3].includes(patch.changes.bodyLines)
4363
+ ![0, 1, 2, 3].includes(patch.changes.bodyLines)
1943
4364
  ) {
1944
- fail(`${path}.bodyLines`, 'must be 1, 2, or 3');
4365
+ fail(`${path}.bodyLines`, 'must be 0, 1, 2, or 3');
1945
4366
  }
1946
4367
  assertImage(patch.changes.thumbnail, `${path}.thumbnail`);
1947
4368
  break;
@@ -1955,6 +4376,23 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
1955
4376
  patch.changes.columns?.forEach((column, columnIndex) => {
1956
4377
  assertKey(column.key, `${path}.columns[${columnIndex}].key`);
1957
4378
  assertText(column.text, `${path}.columns[${columnIndex}].text`);
4379
+ assertIdentityExtras(column, `${path}.columns[${columnIndex}]`);
4380
+ for (const field of [
4381
+ 'textSegments',
4382
+ 'secondaryTextSegments',
4383
+ ] as const) {
4384
+ column[field]?.forEach((segment, segmentIndex) => {
4385
+ assertText(
4386
+ segment.text,
4387
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].text`
4388
+ );
4389
+ if (segment.style !== undefined && segment.style !== 'subscript')
4390
+ fail(
4391
+ `${path}.columns[${columnIndex}].${field}[${segmentIndex}].style`,
4392
+ 'must be subscript'
4393
+ );
4394
+ });
4395
+ }
1958
4396
  assertText(
1959
4397
  column.secondaryText,
1960
4398
  `${path}.columns[${columnIndex}].secondaryText`
@@ -1967,6 +4405,13 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
1967
4405
  if ((patch.changes.badges?.length ?? 0) > MAX_BADGES) {
1968
4406
  fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
1969
4407
  }
4408
+ if ((patch.changes.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
4409
+ fail(
4410
+ `${path}.trailing`,
4411
+ `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`
4412
+ );
4413
+ }
4414
+ assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
1970
4415
  break;
1971
4416
  case 'market':
1972
4417
  assertMarketRow(
@@ -2041,6 +4486,14 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
2041
4486
  assertText(patch.changes.title, `${path}.title`);
2042
4487
  assertText(patch.changes.subtitle, `${path}.subtitle`);
2043
4488
  assertText(patch.changes.value, `${path}.value`);
4489
+ if (patch.changes.leadingBadge) {
4490
+ assertKey(patch.changes.leadingBadge.key, `${path}.leadingBadge.key`);
4491
+ assertText(
4492
+ patch.changes.leadingBadge.text,
4493
+ `${path}.leadingBadge.text`
4494
+ );
4495
+ }
4496
+ assertTextHelp(patch.changes.valueHelp, `${path}.valueHelp`);
2044
4497
  if (patch.changes.valueActionKey !== undefined) {
2045
4498
  assertKey(patch.changes.valueActionKey, `${path}.valueActionKey`);
2046
4499
  }
@@ -2063,6 +4516,10 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
2063
4516
  }
2064
4517
  assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
2065
4518
  break;
4519
+ case 'buttonGroup':
4520
+ if (patch.changes.buttons !== undefined)
4521
+ assertButtonGroup({ buttons: patch.changes.buttons }, path);
4522
+ break;
2066
4523
  case 'system':
2067
4524
  assertText(patch.changes.message, `${path}.message`);
2068
4525
  break;
@@ -2071,22 +4528,167 @@ function assertPatchChanges(patch: RowPatch, index: number): void {
2071
4528
  }
2072
4529
  }
2073
4530
 
4531
+ function normalizePatch(patch: RowPatch, index: number): RowPatch | undefined {
4532
+ const path = `patches[${index}]`;
4533
+ protocolObject(patch, path);
4534
+ protocolKey(patch.key, `${path}.key`);
4535
+ if (isDevelopment()) assertKey(patch.key, `${path}.key`);
4536
+ assertRowType(patch.type, path);
4537
+ const raw = protocolObject(patch.changes, `${path}.changes`);
4538
+ assertPlainSerializable(raw, `${path}.changes`, new Set<object>(), false);
4539
+ const fields = PATCH_FIELDS[patch.type];
4540
+ const changes: Record<string, unknown> = {};
4541
+ for (const [field, value] of Object.entries(raw)) {
4542
+ if (value === undefined) continue;
4543
+ if (!fields?.includes(field)) {
4544
+ if (isDevelopment())
4545
+ fail(`${path}.changes.${field}`, 'unsupported patch field');
4546
+ continue;
4547
+ }
4548
+ if (value === null) {
4549
+ if (patch.type === 'market' && field === 'metrics')
4550
+ fail(
4551
+ `${path}.changes.metrics`,
4552
+ 'use a full snapshot to remove metrics'
4553
+ );
4554
+ if (
4555
+ REQUIRED_ROW_FIELDS[patch.type].includes(field) ||
4556
+ (patch.type === 'system' && field === 'message')
4557
+ ) {
4558
+ // The concrete system variant is checked after merging with its baseline.
4559
+ if (patch.type !== 'system')
4560
+ fail(`${path}.changes.${field}`, 'required field cannot be cleared');
4561
+ }
4562
+ changes[field] = null;
4563
+ continue;
4564
+ }
4565
+ if (patch.type === 'market' && field === 'metrics')
4566
+ assertMarketMetrics(
4567
+ value as MarketRow['metrics'],
4568
+ `${path}.changes.metrics`
4569
+ );
4570
+ if (
4571
+ ['priceSegments', 'subtitleSegments'].includes(field) &&
4572
+ Array.isArray(value) &&
4573
+ value.length === 0
4574
+ ) {
4575
+ changes[field] = null;
4576
+ continue;
4577
+ }
4578
+ const normalized = normalizeEmptyImages(value, field);
4579
+ if (normalized === undefined) {
4580
+ if (!REQUIRED_ROW_FIELDS[patch.type].includes(field))
4581
+ changes[field] = null;
4582
+ continue;
4583
+ }
4584
+ const canonical = isDevelopment()
4585
+ ? normalized
4586
+ : patch.type === 'market' && field === 'metrics'
4587
+ ? sanitizeMarketMetrics(normalized)
4588
+ : sanitizeDecoration(normalized, field);
4589
+ if (canonical !== undefined) changes[field] = canonical;
4590
+ else if (field === 'titleImage') changes[field] = null;
4591
+ }
4592
+ if (
4593
+ patch.type === 'market' &&
4594
+ Array.isArray(changes.priceSegments) &&
4595
+ changes.priceSegments.length > 0 &&
4596
+ (typeof changes.price !== 'string' || !changes.price.trim())
4597
+ )
4598
+ fail(`${path}.changes.price`, 'is required when priceSegments is updated');
4599
+ if (!isDevelopment()) {
4600
+ const sanitized = sanitizeRowForProduction({
4601
+ type: patch.type,
4602
+ ...changes,
4603
+ } as unknown as RowModel) as unknown as Record<string, unknown>;
4604
+ for (const [field, value] of Object.entries(changes)) {
4605
+ if (value === null) continue;
4606
+ if (sanitized[field] === undefined) delete changes[field];
4607
+ else changes[field] = sanitized[field];
4608
+ }
4609
+ }
4610
+ const values = Object.fromEntries(
4611
+ Object.entries(changes).filter(([, value]) => value !== null)
4612
+ );
4613
+ if (patch.type === 'market' && 'metrics' in changes)
4614
+ assertMarketMetrics(
4615
+ changes.metrics as MarketRow['metrics'],
4616
+ `${path}.changes.metrics`
4617
+ );
4618
+ assertPlainSerializable(values, `${path}.changes`, new Set<object>());
4619
+ assertProtocolFields(values, `${path}.changes`);
4620
+ if (isDevelopment())
4621
+ assertPatchChanges({ ...patch, changes: values } as PatchValues, index);
4622
+ const normalizedPatch = {
4623
+ type: patch.type,
4624
+ key: patch.key,
4625
+ changes,
4626
+ } as RowPatch;
4627
+ return Object.keys(changes).length > 0
4628
+ ? normalizePatchStyles([normalizedPatch])[0]
4629
+ : undefined;
4630
+ }
4631
+
4632
+ function reportRejectedPatch(index: number): void {
4633
+ console.warn(`NativeList rejected invalid patch unit at patches[${index}]`);
4634
+ }
4635
+
2074
4636
  export function validatePatches(
2075
4637
  patches: readonly RowPatch[]
2076
4638
  ): readonly RowPatch[] {
2077
- assertPlainSerializable(patches, 'patches', new Set<object>());
2078
- const keys = new Set<string>();
2079
- patches.forEach((patch, index) => {
2080
- assertKey(patch.key, `patches[${index}].key`);
2081
- if (keys.has(patch.key))
2082
- fail(`patches[${index}].key`, `duplicate key "${patch.key}"`);
2083
- keys.add(patch.key);
2084
- if (Object.keys(patch.changes).length === 0) {
2085
- fail(`patches[${index}].changes`, 'must contain at least one field');
4639
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
4640
+ const units = new Map<string, { patch: RowPatch; index: number }>();
4641
+ const rejectedKeys = new Set<string>();
4642
+ const reject = (key: string, index: number, error: unknown) => {
4643
+ if (isDevelopment()) throw error;
4644
+ rejectedKeys.add(key);
4645
+ reportRejectedPatch(index);
4646
+ };
4647
+ patches.forEach((input, index) => {
4648
+ const key =
4649
+ isRecord(input) && typeof input.key === 'string' ? input.key : '';
4650
+ try {
4651
+ protocolObject(input, `patches[${index}]`);
4652
+ protocolKey(input.key, `patches[${index}].key`);
4653
+ assertRowType(input.type, `patches[${index}]`);
4654
+ const changes = capturePlainData(
4655
+ protocolObject(input.changes, `patches[${index}].changes`)
4656
+ );
4657
+ assertPlainSerializable(
4658
+ changes,
4659
+ `patches[${index}].changes`,
4660
+ new Set<object>(),
4661
+ false
4662
+ );
4663
+ const previous = units.get(key);
4664
+ if (previous && previous.patch.type !== input.type)
4665
+ fail(`patches[${index}].type`, 'conflicting row types');
4666
+ const defined = Object.fromEntries(
4667
+ Object.entries(changes).filter(([, value]) => value !== undefined)
4668
+ );
4669
+ units.set(key, {
4670
+ index,
4671
+ patch: {
4672
+ key,
4673
+ type: input.type,
4674
+ changes: { ...previous?.patch.changes, ...defined },
4675
+ } as RowPatch,
4676
+ });
4677
+ } catch (error) {
4678
+ reject(key, index, error);
2086
4679
  }
2087
- assertPatchChanges(patch, index);
2088
4680
  });
2089
- return normalizePatchStyles(patches);
4681
+ const accepted: RowPatch[] = [];
4682
+ for (const [key, unit] of units) {
4683
+ if (rejectedKeys.has(key)) continue;
4684
+ try {
4685
+ const patch = normalizePatch(unit.patch, unit.index);
4686
+ if (patch) accepted.push(patch);
4687
+ } catch (error) {
4688
+ reject(key, unit.index, error);
4689
+ }
4690
+ }
4691
+ return accepted;
2090
4692
  }
2091
4693
 
2092
4694
  /** Patches reach the native side without passing through a snapshot. */
@@ -2108,44 +4710,303 @@ function normalizePatchStyles(
2108
4710
  return changed ? next : patches;
2109
4711
  }
2110
4712
 
2111
- export function applyRowPatches(
2112
- snapshot: NativeListSnapshot,
2113
- patches: readonly RowPatch[]
2114
- ): NativeListSnapshot {
2115
- validatePatches(patches);
2116
- const patchByKey = new Map(patches.map((patch) => [patch.key, patch]));
2117
- const knownKeys = new Set(snapshot.rows.map((row) => row.key));
2118
- patches.forEach((patch) => {
2119
- if (!knownKeys.has(patch.key))
2120
- fail('patches', `unknown row key "${patch.key}"`);
2121
- });
2122
- const rows = snapshot.rows.map((row): RowModel => {
2123
- const patch = patchByKey.get(row.key);
2124
- if (!patch) return row;
2125
- if (patch.type !== row.type) {
2126
- fail('patches', `row "${row.key}" is ${row.type}, not ${patch.type}`);
4713
+ const EMPTY_ROW_PATCHES: readonly RowPatch[] = Object.freeze([]);
4714
+
4715
+ function sameJsonValue(left: unknown, right: unknown): boolean {
4716
+ if (left === right) return true;
4717
+ if (left === null || right === null) return false;
4718
+ if (typeof left !== 'object' || typeof right !== 'object') return false;
4719
+ if (Array.isArray(left) || Array.isArray(right)) {
4720
+ return (
4721
+ Array.isArray(left) &&
4722
+ Array.isArray(right) &&
4723
+ left.length === right.length &&
4724
+ left.every((value, index) => sameJsonValue(value, right[index]))
4725
+ );
4726
+ }
4727
+ const leftObject = left as Record<string, unknown>;
4728
+ const rightObject = right as Record<string, unknown>;
4729
+ const leftKeys = Object.keys(leftObject).filter(
4730
+ (key) => leftObject[key] !== undefined
4731
+ );
4732
+ const rightKeys = Object.keys(rightObject).filter(
4733
+ (key) => rightObject[key] !== undefined
4734
+ );
4735
+ return (
4736
+ leftKeys.length === rightKeys.length &&
4737
+ leftKeys.every((key) => sameJsonValue(leftObject[key], rightObject[key]))
4738
+ );
4739
+ }
4740
+
4741
+ function sameOptionalPresence(left: unknown, right: unknown): boolean {
4742
+ return (left === undefined) === (right === undefined);
4743
+ }
4744
+
4745
+ /** Plan value-only patches; callers own valid immutable snapshots and commit state. */
4746
+ export function planNativeListPatches(
4747
+ previous: NativeListSnapshot,
4748
+ next: NativeListSnapshot
4749
+ ): readonly RowPatch[] | undefined {
4750
+ if (previous === next) return EMPTY_ROW_PATCHES;
4751
+ const { rows: previousRows, ...previousMetadata } = previous;
4752
+ const { rows: nextRows, ...nextMetadata } = next;
4753
+ if (
4754
+ previousRows.length !== nextRows.length ||
4755
+ !sameJsonValue(previousMetadata, nextMetadata)
4756
+ )
4757
+ return undefined;
4758
+ if (previousRows === nextRows) return EMPTY_ROW_PATCHES;
4759
+
4760
+ const patches: RowPatch[] = [];
4761
+ for (let index = 0; index < nextRows.length; index += 1) {
4762
+ const oldRow = previousRows[index];
4763
+ const row = nextRows[index];
4764
+ if (oldRow.key !== row.key || oldRow.type !== row.type) return undefined;
4765
+ if (oldRow === row) continue;
4766
+
4767
+ if (oldRow.type === 'identity' && row.type === 'identity') {
4768
+ const {
4769
+ subtitle: oldSubtitle,
4770
+ subtitleSegments: oldSubtitleSegments,
4771
+ trailing: oldTrailing,
4772
+ ...oldMetadata
4773
+ } = oldRow;
4774
+ const { subtitle, subtitleSegments, trailing, ...metadata } = row;
4775
+ if (
4776
+ !sameOptionalPresence(oldSubtitle, subtitle) ||
4777
+ !sameOptionalPresence(oldSubtitleSegments, subtitleSegments) ||
4778
+ !sameOptionalPresence(oldTrailing, trailing) ||
4779
+ !sameJsonValue(oldMetadata, metadata)
4780
+ )
4781
+ return undefined;
4782
+ if (
4783
+ !sameJsonValue(oldSubtitle, subtitle) ||
4784
+ !sameJsonValue(oldSubtitleSegments, subtitleSegments) ||
4785
+ !sameJsonValue(oldTrailing, trailing)
4786
+ ) {
4787
+ patches.push({
4788
+ type: 'identity',
4789
+ key: row.key,
4790
+ changes: { subtitle, subtitleSegments, trailing },
4791
+ });
4792
+ }
4793
+ } else if (oldRow.type === 'dataRow' && row.type === 'dataRow') {
4794
+ const {
4795
+ columns: oldColumns,
4796
+ trailing: oldTrailing,
4797
+ ...oldMetadata
4798
+ } = oldRow;
4799
+ const { columns, trailing, ...metadata } = row;
4800
+ if (
4801
+ !sameOptionalPresence(oldTrailing, trailing) ||
4802
+ !sameJsonValue(oldMetadata, metadata) ||
4803
+ !sameJsonValue(oldColumns[0], columns[0])
4804
+ )
4805
+ return undefined;
4806
+ if (
4807
+ !sameJsonValue(oldColumns.slice(1), columns.slice(1)) ||
4808
+ !sameJsonValue(oldTrailing, trailing)
4809
+ ) {
4810
+ patches.push({
4811
+ type: 'dataRow',
4812
+ key: row.key,
4813
+ changes: { columns, trailing },
4814
+ });
4815
+ }
4816
+ } else if (!sameJsonValue(oldRow, row)) {
4817
+ return undefined;
2127
4818
  }
4819
+ }
4820
+ return patches.length === 0 ? EMPTY_ROW_PATCHES : patches;
4821
+ }
4822
+
4823
+ function mergeAndValidateSingleRow(
4824
+ previous: RowModel,
4825
+ patch: RowPatch,
4826
+ index: number
4827
+ ): { row: RowModel; patch: RowPatch } {
4828
+ if (previous.key !== patch.key)
4829
+ fail(`patches[${index}].key`, 'does not match row identity');
4830
+ if (previous.type !== patch.type)
4831
+ fail(`patches[${index}].type`, 'does not match row type');
4832
+ const changes = { ...patch.changes } as Record<string, unknown>;
4833
+ if (previous.type === 'market') {
4834
+ if (
4835
+ typeof changes.price === 'string' &&
4836
+ !('priceSegments' in changes) &&
4837
+ previous.priceSegments !== undefined
4838
+ )
4839
+ changes.priceSegments = null;
2128
4840
  if (
2129
- row.type === 'market' &&
2130
- row.webTable &&
2131
- patch.type === 'market' &&
2132
- (patch.changes.price !== undefined ||
2133
- patch.changes.priceSegments !== undefined ||
2134
- patch.changes.change !== undefined) &&
2135
- patch.changes.webTable === undefined
4841
+ (previous.webTable !== undefined || 'webTable' in changes) &&
4842
+ ['price', 'priceSegments', 'change'].some((field) => field in changes) &&
4843
+ changes.webTable === undefined
2136
4844
  )
2137
4845
  fail(
2138
- 'patches',
2139
- 'table quote changes must include the visible table cells'
4846
+ `patches[${index}].changes.webTable`,
4847
+ 'table quote changes require visible table cells'
2140
4848
  );
2141
- return {
2142
- ...row,
2143
- ...patch.changes,
2144
- key: row.key,
2145
- type: row.type,
2146
- } as RowModel;
4849
+ }
4850
+ if (previous.type === 'identity' || previous.type === 'market') {
4851
+ if (
4852
+ typeof changes.subtitle === 'string' &&
4853
+ !('subtitleSegments' in changes) &&
4854
+ previous.subtitleSegments !== undefined
4855
+ )
4856
+ changes.subtitleSegments = null;
4857
+ if (
4858
+ Array.isArray(changes.subtitleSegments) &&
4859
+ changes.subtitleSegments.length > 0 &&
4860
+ !('subtitle' in changes) &&
4861
+ previous.subtitle !== undefined
4862
+ )
4863
+ changes.subtitle = null;
4864
+ }
4865
+ const merged = { ...previous } as unknown as Record<string, unknown>;
4866
+ for (const [field, value] of Object.entries(changes)) {
4867
+ if (value === null) delete merged[field];
4868
+ else if (value !== undefined) merged[field] = value;
4869
+ }
4870
+ const next = normalizeRowStyles(merged as unknown as RowModel);
4871
+ assertPlainSerializable(next, `rows[${index}]`, new Set<object>());
4872
+ if (isDevelopment()) assertRow(next, index);
4873
+ assertRowProtocol(next, `rows[${index}]`);
4874
+ return {
4875
+ row: next,
4876
+ patch: { type: patch.type, key: patch.key, changes } as RowPatch,
4877
+ };
4878
+ }
4879
+
4880
+ /** One canonical batch owns both accepted rows and the native wire payload. */
4881
+ export function applyValidatedRowPatches(
4882
+ snapshot: NativeListSnapshot,
4883
+ patches: readonly RowPatch[]
4884
+ ): {
4885
+ patches: readonly RowPatch[];
4886
+ snapshot: NativeListSnapshot;
4887
+ json: string;
4888
+ } {
4889
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
4890
+ const owned = ownedNativeSnapshots.has(snapshot);
4891
+ const rowIndexes =
4892
+ ownedNativeSnapshots.get(snapshot) ??
4893
+ validatedRowIndexes.get(snapshot) ??
4894
+ new Map(snapshot.rows.map((row, index) => [row.key, index]));
4895
+ validatedRowIndexes.set(snapshot, rowIndexes);
4896
+ const units = new Map<
4897
+ string,
4898
+ { index: number; changes: Record<string, unknown>; type: RowPatch['type'] }
4899
+ >();
4900
+ const rejected = new Set<string>();
4901
+ const rejectedGroups = new Set<string>();
4902
+ const reject = (key: string, index: number, error: unknown) => {
4903
+ if (isDevelopment()) throw error;
4904
+ rejected.add(key);
4905
+ const rowIndex = rowIndexes.get(key);
4906
+ const group =
4907
+ rowIndex === undefined ? undefined : snapshot.rows[rowIndex].groupId;
4908
+ if (group) rejectedGroups.add(group);
4909
+ reportRejectedPatch(index);
4910
+ };
4911
+ patches.forEach((input, index) => {
4912
+ const key =
4913
+ isRecord(input) && typeof input.key === 'string' ? input.key : '';
4914
+ try {
4915
+ protocolObject(input, `patches[${index}]`);
4916
+ protocolKey(input.key, `patches[${index}].key`);
4917
+ const rowIndex = rowIndexes.get(input.key);
4918
+ if (rowIndex === undefined)
4919
+ fail(`patches[${index}].key`, 'unknown row identity');
4920
+ if (snapshot.rows[rowIndex].type !== input.type)
4921
+ fail(`patches[${index}].type`, 'does not match row type');
4922
+ const changes = protocolObject(
4923
+ input.changes,
4924
+ `patches[${index}].changes`
4925
+ );
4926
+ const captured = capturePlainData(changes);
4927
+ assertPlainSerializable(
4928
+ captured,
4929
+ `patches[${index}].changes`,
4930
+ new Set<object>(),
4931
+ false
4932
+ );
4933
+ const previous = units.get(input.key);
4934
+ // Undefined is omitted at every merge, so it cannot overwrite an earlier change.
4935
+ const defined = Object.fromEntries(
4936
+ Object.entries(captured).filter(([, value]) => value !== undefined)
4937
+ );
4938
+ units.set(input.key, {
4939
+ index,
4940
+ type: input.type,
4941
+ changes: { ...previous?.changes, ...defined },
4942
+ });
4943
+ } catch (error) {
4944
+ reject(key, index, error);
4945
+ }
2147
4946
  });
2148
- return validateSnapshot({ ...snapshot, rows });
4947
+ const pending = new Map<string, { row: RowModel; patch: RowPatch }>();
4948
+ for (const [key, unit] of units) {
4949
+ if (rejected.has(key)) continue;
4950
+ try {
4951
+ const patch = normalizePatch(
4952
+ { key, type: unit.type, changes: unit.changes } as RowPatch,
4953
+ unit.index
4954
+ );
4955
+ if (!patch) continue;
4956
+ const merged = mergeAndValidateSingleRow(
4957
+ snapshot.rows[rowIndexes.get(key)!],
4958
+ patch,
4959
+ rowIndexes.get(key)!
4960
+ );
4961
+ if (merged.row.disabled && snapshot.selection?.selectedKeys.includes(key))
4962
+ fail(`patches[${unit.index}]`, 'cannot disable a selected row');
4963
+ pending.set(key, merged);
4964
+ } catch (error) {
4965
+ reject(key, unit.index, error);
4966
+ }
4967
+ }
4968
+ const accepted: RowPatch[] = [];
4969
+ let rows: RowModel[] | undefined;
4970
+ for (const [key, value] of pending) {
4971
+ const index = rowIndexes.get(key)!;
4972
+ const group = snapshot.rows[index].groupId;
4973
+ if (rejected.has(key) || (group && rejectedGroups.has(group))) continue;
4974
+ if (!rows) rows = snapshot.rows.slice();
4975
+ rows[index] = owned ? deepFreeze(value.row) : value.row;
4976
+ accepted.push(owned ? deepFreeze(value.patch) : value.patch);
4977
+ }
4978
+ if (!rows) return { patches: EMPTY_ROW_PATCHES, snapshot, json: '[]' };
4979
+ const next = owned
4980
+ ? Object.freeze({ ...snapshot, rows: Object.freeze(rows) })
4981
+ : { ...snapshot, rows };
4982
+ if (owned) ownedNativeSnapshots.set(next, rowIndexes);
4983
+ else validatedRowIndexes.set(next, rowIndexes);
4984
+ return { patches: accepted, snapshot: next, json: JSON.stringify(accepted) };
4985
+ }
4986
+
4987
+ const validatedRowIndexes = new WeakMap<
4988
+ NativeListSnapshot,
4989
+ ReadonlyMap<string, number>
4990
+ >();
4991
+
4992
+ export function applyOwnedNativePatches(
4993
+ snapshot: NativeListSnapshot,
4994
+ patches: readonly RowPatch[]
4995
+ ) {
4996
+ const owned = ownedNativeSnapshots.has(snapshot)
4997
+ ? snapshot
4998
+ : ownValidatedNativeSnapshot(validateSnapshot(capturePlainData(snapshot)));
4999
+ return applyValidatedRowPatches(owned, patches);
5000
+ }
5001
+
5002
+ export function applyRowPatches(
5003
+ snapshot: NativeListSnapshot,
5004
+ patches: readonly RowPatch[]
5005
+ ): NativeListSnapshot {
5006
+ const baseline = ownedNativeSnapshots.has(snapshot)
5007
+ ? snapshot
5008
+ : validateSnapshot(snapshot);
5009
+ return applyValidatedRowPatches(baseline, patches).snapshot;
2149
5010
  }
2150
5011
 
2151
5012
  export function serializeSnapshot(snapshot: NativeListSnapshot): string {