@onekeyfe/react-native-native-list 6.7.0-6 → 6.7.0-60

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 (216) hide show
  1. package/README.md +312 -375
  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 +50 -13
  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 +209 -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 +8 -3
  23. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  24. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +130 -1
  25. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +1978 -136
  26. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListActivityHostClipPolicyTest.kt +35 -0
  27. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt +153 -0
  28. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListIdentityTrailingAxisTest.kt +36 -0
  29. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingSlotFrameTest.kt +68 -0
  30. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  31. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +10 -0
  32. package/docs/ROW_TEMPLATES.md +78 -14
  33. package/docs/SPEC.md +1318 -16
  34. package/docs/STYLE_SPEC.md +18 -0
  35. package/ios/HybridNativeList.swift +21 -2
  36. package/ios/NativeListAccessoryStack.swift +237 -51
  37. package/ios/NativeListActivityDetailsView.swift +43 -16
  38. package/ios/NativeListActivityRenderer.swift +8 -2
  39. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  40. package/ios/NativeListDataRowRenderer.swift +167 -30
  41. package/ios/NativeListDesignAssets.swift +13 -75
  42. package/ios/NativeListGeneratedIcons.swift +55 -0
  43. package/ios/NativeListIconBinding.swift +171 -0
  44. package/ios/NativeListIdentityRenderer.swift +256 -39
  45. package/ios/NativeListLeadingVisual.swift +127 -28
  46. package/ios/NativeListMarketRenderer.swift +120 -31
  47. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  48. package/ios/NativeListMediaPreviewSlot.swift +122 -61
  49. package/ios/NativeListMediaTileRenderer.swift +15 -11
  50. package/ios/NativeListMessageRenderer.swift +34 -1
  51. package/ios/NativeListMetricCardRenderer.swift +4 -2
  52. package/ios/NativeListModels.swift +42 -2
  53. package/ios/NativeListRendererRegistry.swift +1 -0
  54. package/ios/NativeListResolvedText.swift +17 -5
  55. package/ios/NativeListRowHost.swift +14 -0
  56. package/ios/NativeListSectionHeaderRenderer.swift +100 -4
  57. package/ios/NativeListTextLabel.swift +106 -0
  58. package/ios/RNCNativeListView.swift +1097 -60
  59. package/ios/tests/NativeListAccessoryStackTests.swift +101 -0
  60. package/ios/tests/NativeListAccountSelectorLayoutTests.swift +96 -0
  61. package/ios/tests/NativeListActivityPresentationTests.swift +423 -0
  62. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +81 -0
  63. package/ios/tests/NativeListLeadingVisualPairBackdropTests.swift +50 -0
  64. package/ios/tests/NativeListLifecycleTests.swift +2959 -4
  65. package/ios/tests/NativeListMarketMetricsTests.swift +117 -0
  66. package/ios/tests/NativeListMediaVisibilityTests.swift +27 -1
  67. package/ios/tests/NativeListSharedIconTests.swift +236 -0
  68. package/lib/module/NativeList.js +236 -38
  69. package/lib/module/NativeList.web.js +163 -45
  70. package/lib/module/index.js +1 -1
  71. package/lib/module/models.js +3 -0
  72. package/lib/module/selection.js +1 -1
  73. package/lib/module/validation.js +1263 -48
  74. package/lib/module/web/NativeListGeneratedIcons.js +31 -0
  75. package/lib/module/web/NativeListWebEngine.js +513 -275
  76. package/lib/module/web/templates/ActivityRowRenderer.js +41 -54
  77. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  78. package/lib/module/web/templates/DataRowRenderer.js +56 -5
  79. package/lib/module/web/templates/IdentityRowRenderer.js +161 -7
  80. package/lib/module/web/templates/MarketTableRowRenderer.js +36 -19
  81. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -25
  82. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  83. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  84. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  85. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  86. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  87. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  88. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  89. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  90. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  91. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  92. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  93. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  94. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  95. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  96. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  97. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  98. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  99. package/lib/typescript/src/NativeList.d.ts +3 -3
  100. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  101. package/lib/typescript/src/NativeList.types.d.ts +20 -2
  102. package/lib/typescript/src/index.d.ts +2 -2
  103. package/lib/typescript/src/models.d.ts +134 -17
  104. package/lib/typescript/src/validation.d.ts +20 -0
  105. package/lib/typescript/src/web/NativeListGeneratedIcons.d.ts +2 -0
  106. package/lib/typescript/src/web/NativeListWebEngine.d.ts +32 -1
  107. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  108. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  109. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  110. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  111. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  112. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  113. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  114. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  115. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  116. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  117. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  118. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  119. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  120. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  121. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  122. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  123. package/package.json +16 -10
  124. package/react-native-native-list.podspec +2 -6
  125. package/scripts/generate-icons.mjs +150 -0
  126. package/scripts/generate-icons.test.mjs +288 -0
  127. package/scripts/native-list-icons.json +260 -0
  128. package/src/NativeList.nitro.ts +2 -0
  129. package/src/NativeList.tsx +439 -91
  130. package/src/NativeList.types.ts +24 -2
  131. package/src/NativeList.web.tsx +286 -88
  132. package/src/index.ts +2 -0
  133. package/src/models.ts +272 -144
  134. package/src/selection.ts +1 -0
  135. package/src/validation.ts +3041 -146
  136. package/src/web/NativeListGeneratedIcons.ts +28 -0
  137. package/src/web/NativeListWebEngine.ts +818 -343
  138. package/src/web/templates/ActivityRowRenderer.ts +71 -91
  139. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  140. package/src/web/templates/DataRowRenderer.ts +121 -20
  141. package/src/web/templates/IdentityRowRenderer.ts +234 -9
  142. package/src/web/templates/MarketTableRowRenderer.ts +53 -33
  143. package/src/web/templates/MediaTileRowRenderer.ts +90 -28
  144. package/src/web/templates/MessageRowRenderer.ts +23 -7
  145. package/src/web/templates/RowContainerStyle.ts +2 -0
  146. package/src/web/templates/RowRendererRegistry.ts +11 -1
  147. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
  148. package/ios/Resources/NativeListIcons.xcassets/Contents.json +0 -1
  149. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/Contents.json +0 -1
  150. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/icon.svg +0 -1
  151. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/Contents.json +0 -1
  152. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/icon.svg +0 -1
  153. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/Contents.json +0 -1
  154. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/icon.svg +0 -1
  155. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/Contents.json +0 -1
  156. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/icon.svg +0 -1
  157. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/Contents.json +0 -1
  158. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/icon.svg +0 -1
  159. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/Contents.json +0 -1
  160. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/icon.svg +0 -1
  161. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/Contents.json +0 -1
  162. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/icon.svg +0 -1
  163. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/Contents.json +0 -1
  164. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/icon.svg +0 -1
  165. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/Contents.json +0 -1
  166. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/icon.svg +0 -1
  167. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/Contents.json +0 -1
  168. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/icon.svg +0 -1
  169. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/Contents.json +0 -1
  170. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/icon.svg +0 -1
  171. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/Contents.json +0 -1
  172. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/icon.svg +0 -1
  173. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/Contents.json +0 -1
  174. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/icon.svg +0 -1
  175. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/Contents.json +0 -1
  176. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/icon.svg +0 -1
  177. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/Contents.json +0 -1
  178. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/icon.svg +0 -1
  179. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/Contents.json +0 -1
  180. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/icon.svg +0 -1
  181. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/Contents.json +0 -1
  182. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/icon.svg +0 -1
  183. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/Contents.json +0 -1
  184. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/icon.svg +0 -1
  185. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/Contents.json +0 -1
  186. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/icon.svg +0 -1
  187. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/Contents.json +0 -1
  188. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/icon.svg +0 -1
  189. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/Contents.json +0 -1
  190. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/icon.svg +0 -1
  191. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/Contents.json +0 -15
  192. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/icon.svg +0 -14
  193. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/Contents.json +0 -15
  194. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/icon.svg +0 -12
  195. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/Contents.json +0 -15
  196. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/icon.svg +0 -6
  197. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/Contents.json +0 -15
  198. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/icon.svg +0 -15
  199. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/Contents.json +0 -15
  200. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/icon.svg +0 -3
  201. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/Contents.json +0 -15
  202. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/icon.svg +0 -7
  203. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/Contents.json +0 -15
  204. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/icon.svg +0 -18
  205. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/Contents.json +0 -15
  206. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/icon.svg +0 -7
  207. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/Contents.json +0 -1
  208. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/icon.svg +0 -1
  209. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/Contents.json +0 -1
  210. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/icon.svg +0 -1
  211. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/Contents.json +0 -1
  212. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/icon.svg +0 -1
  213. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/Contents.json +0 -1
  214. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/icon.svg +0 -1
  215. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/Contents.json +0 -1
  216. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/icon.svg +0 -1
@@ -12,15 +12,48 @@ const MAX_HEADER_LENGTH = 4096;
12
12
  const MAX_SPACER_HEIGHT = 512;
13
13
  const MAX_SECTION_INDEX_TITLE_LENGTH = 8;
14
14
  const MAX_MARKET_BADGES = 3;
15
+ const MARKET_METRIC_FIELDS = ['key', 'text', 'textSegments', 'secondaryText', 'secondaryTextSegments', 'weight', 'alignment', 'tone', 'secondaryTone'];
16
+ function isDevelopment() {
17
+ return typeof __DEV__ !== 'undefined' && __DEV__;
18
+ }
19
+ class NativeListInputError extends Error {
20
+ constructor(path, reason) {
21
+ super(`NativeList ${path}: ${reason}`);
22
+ this.path = path;
23
+ this.reason = reason;
24
+ }
25
+ }
15
26
  function fail(path, message) {
16
- throw new Error(`NativeList ${path}: ${message}`);
27
+ throw new NativeListInputError(path, message);
28
+ }
29
+
30
+ /** Component boundaries report locations, never caller-controlled payload values. */
31
+ export function containNativeListInput(operation) {
32
+ try {
33
+ return operation();
34
+ } catch (error) {
35
+ const path = error instanceof NativeListInputError ? error.path : 'input';
36
+ const reason = isDevelopment() && error instanceof NativeListInputError ? `: ${error.reason.split('"')[0].trim()}` : '';
37
+ console.warn(`NativeList rejected invalid input at ${path}${reason}`);
38
+ return undefined;
39
+ }
17
40
  }
18
- function assertPlainSerializable(value, path, seen) {
41
+ export function emptyNativeListSnapshot() {
42
+ return {
43
+ schemaVersion: 1,
44
+ generation: 0,
45
+ layout: {
46
+ kind: 'linear'
47
+ },
48
+ rows: []
49
+ };
50
+ }
51
+ function assertPlainSerializable(value, path, seen, requireFinite = true) {
19
52
  if (value === null || value === undefined) return;
20
53
  const valueType = typeof value;
21
54
  if (valueType === 'string' || valueType === 'boolean') return;
22
55
  if (valueType === 'number') {
23
- if (!Number.isFinite(value)) fail(path, 'numbers must be finite');
56
+ if (requireFinite && !Number.isFinite(value)) fail(path, 'numbers must be finite');
24
57
  return;
25
58
  }
26
59
  if (valueType !== 'object') fail(path, 'must contain only plain serializable data');
@@ -28,21 +61,23 @@ function assertPlainSerializable(value, path, seen) {
28
61
  if (seen.has(objectValue)) fail(path, 'must not contain circular references');
29
62
  seen.add(objectValue);
30
63
  if (Array.isArray(value)) {
31
- value.forEach((item, index) => assertPlainSerializable(item, `${path}[${index}]`, seen));
64
+ value.forEach((item, index) => assertPlainSerializable(item, `${path}[${index}]`, seen, requireFinite));
32
65
  } else {
33
66
  const prototype = Object.getPrototypeOf(value);
34
67
  if (prototype !== Object.prototype && prototype !== null) {
35
68
  fail(path, 'must contain plain objects only');
36
69
  }
37
- Object.entries(value).forEach(([key, item]) => assertPlainSerializable(item, `${path}.${key}`, seen));
70
+ Object.entries(value).forEach(([key, item]) => {
71
+ if (key === '__proto__' || key === 'constructor' && typeof item === 'object') fail(path, 'unsafe object key');
72
+ assertPlainSerializable(item, `${path}.${key}`, seen, requireFinite);
73
+ });
38
74
  }
39
75
  seen.delete(objectValue);
40
76
  }
41
77
  function assertKey(key, path) {
42
- if (typeof key !== 'string' || key.length === 0 || key.length > MAX_KEY_LENGTH) {
43
- fail(path, `must be a non-empty string no longer than ${MAX_KEY_LENGTH} characters`);
78
+ if (typeof key !== 'string' || key.trim().length === 0 || key.length > MAX_KEY_LENGTH) {
79
+ fail(path, `must be a non-blank string no longer than ${MAX_KEY_LENGTH} characters`);
44
80
  }
45
- if (key.trim() !== key) fail(path, 'must not have leading or trailing whitespace');
46
81
  }
47
82
  function assertText(text, path) {
48
83
  if (text === undefined) return;
@@ -136,10 +171,13 @@ const TEXT_STYLE_KEYS_BY_ROW_TYPE = {
136
171
  metricCard: ['title', 'value', 'subtitle', 'trend'],
137
172
  sectionHeader: ['title', 'subtitle', 'value'],
138
173
  action: ['title', 'value'],
174
+ buttonGroup: [],
139
175
  system: ['title', 'message', 'actionText']
140
176
  };
141
177
  const EXTRA_STYLE_KEYS_BY_ROW_TYPE = {
142
- market: ['titleBadgeLayout', 'contentTrailingGap', 'subtitleTrailingPadding', 'changeWidth', 'changeHeight', 'changeCornerRadius']
178
+ identity: ['leadingContentMaxWidthRatio'],
179
+ market: ['titleBadgeLayout', 'contentTrailingGap', 'subtitleTrailingPadding', 'changeWidth', 'changeHeight', 'changeCornerRadius'],
180
+ sectionHeader: ['valuePlacement', 'titleDecoration']
143
181
  };
144
182
  function assertTextStyle(style, path, additionalKeys = []) {
145
183
  if (style === undefined) return;
@@ -252,6 +290,15 @@ function assertRowStyle(row, path) {
252
290
  // Market keeps its own richer assertions, driven from assertMarketRow.
253
291
  if (row.type === 'market') return;
254
292
  assertBoxStyle(style, `${path}.style`);
293
+ if (row.type === 'identity') {
294
+ const ratio = style?.leadingContentMaxWidthRatio;
295
+ if (ratio !== undefined && (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1)) fail(`${path}.style.leadingContentMaxWidthRatio`, 'must be within (0, 1]');
296
+ }
297
+ if (row.type === 'sectionHeader') {
298
+ const sectionStyle = style;
299
+ if (sectionStyle?.valuePlacement !== undefined && sectionStyle.valuePlacement !== 'afterTitle') fail(`${path}.style.valuePlacement`, 'must be afterTitle');
300
+ if (sectionStyle?.titleDecoration !== undefined && !['none', 'dashed'].includes(sectionStyle.titleDecoration)) fail(`${path}.style.titleDecoration`, 'must be none or dashed');
301
+ }
255
302
  const slots = style;
256
303
  textKeys.forEach(key => assertTextStyle(slots[key], `${path}.style.${key}`));
257
304
  }
@@ -478,8 +525,56 @@ function assertWebMarketTable(table, path) {
478
525
  }
479
526
  });
480
527
  }
528
+ function assertMarketMetrics(metrics, path) {
529
+ if (metrics === undefined) return;
530
+ if (!Array.isArray(metrics) || ![2, 3].includes(metrics.length)) fail(path, 'must contain 2 or 3 columns');
531
+ const keys = new Set();
532
+ metrics.forEach((column, index) => {
533
+ const columnPath = `${path}[${index}]`;
534
+ const value = protocolObject(column, columnPath);
535
+ protocolKey(value.key, `${columnPath}.key`);
536
+ if (keys.has(column.key)) fail(`${columnPath}.key`, 'must be unique');
537
+ keys.add(column.key);
538
+ if (typeof value.text !== 'string') fail(`${columnPath}.text`, 'must be a string');
539
+ for (const field of ['textSegments', 'secondaryTextSegments']) {
540
+ const segments = column[field];
541
+ if (segments !== undefined && !Array.isArray(segments)) fail(`${columnPath}.${field}`, 'must be an array');
542
+ segments?.forEach((segment, segmentIndex) => {
543
+ const segmentPath = `${columnPath}.${field}[${segmentIndex}]`;
544
+ protocolObject(segment, segmentPath);
545
+ if (typeof segment.text !== 'string') fail(`${segmentPath}.text`, 'must be a string');
546
+ if (segment.style !== undefined && segment.style !== 'subscript') fail(`${segmentPath}.style`, 'must be subscript');
547
+ });
548
+ }
549
+ if (value.weight !== undefined && ![1, 2, 3].includes(value.weight)) fail(`${columnPath}.weight`, 'must be 1, 2, or 3');
550
+ if (value.alignment !== undefined && !['start', 'center', 'end'].includes(value.alignment)) fail(`${columnPath}.alignment`, 'must be start, center, or end');
551
+ if (value.secondaryText !== undefined && typeof value.secondaryText !== 'string') fail(`${columnPath}.secondaryText`, 'must be a string');
552
+ assertTextTone(value.tone, `${columnPath}.tone`);
553
+ assertTextTone(value.secondaryTone, `${columnPath}.secondaryTone`);
554
+ });
555
+ }
481
556
  function assertMarketRow(row, path) {
482
557
  assertWebMarketTable(row.webTable, `${path}.webTable`);
558
+ assertMarketMetrics(row.metrics, `${path}.metrics`);
559
+ if (row.metrics !== undefined) {
560
+ row.metrics.forEach((column, index) => {
561
+ const columnPath = `${path}.metrics[${index}]`;
562
+ const value = protocolObject(column, columnPath);
563
+ assertUnknownKeys(value, MARKET_METRIC_FIELDS, columnPath, 'Market metric key');
564
+ assertKey(column.key, `${columnPath}.key`);
565
+ assertText(column.text, `${columnPath}.text`);
566
+ assertText(column.secondaryText, `${columnPath}.secondaryText`);
567
+ assertTextTone(column.tone, `${columnPath}.tone`);
568
+ assertTextTone(column.secondaryTone, `${columnPath}.secondaryTone`);
569
+ for (const field of ['textSegments', 'secondaryTextSegments']) {
570
+ column[field]?.forEach((segment, segmentIndex) => {
571
+ const segmentPath = `${columnPath}.${field}[${segmentIndex}]`;
572
+ assertText(segment.text, `${segmentPath}.text`);
573
+ if (segment.style !== undefined && segment.style !== 'subscript') fail(`${segmentPath}.style`, 'must be subscript');
574
+ });
575
+ }
576
+ });
577
+ }
483
578
  if (!['token', 'stock', 'perp'].includes(row.variant)) {
484
579
  fail(`${path}.variant`, 'must be token, stock, or perp');
485
580
  }
@@ -541,17 +636,106 @@ function assertVisualShape(shape, path) {
541
636
  function assertTrailingAccessories(accessories, path) {
542
637
  accessories?.forEach((accessory, index) => {
543
638
  const accessoryPath = `${path}[${index}]`;
639
+ if (accessory.kind === 'button') {
640
+ assertUnknownKeys(accessory, ['kind', 'label', 'actionKey', 'disabled', 'testID', 'accessibilityLabel', 'textColor', 'backgroundColor', 'pressedBackgroundColor', 'hoverBackgroundColor', 'focusRingColor'], accessoryPath, 'button key');
641
+ if (typeof accessory.label !== 'string' || !accessory.label.trim()) fail(`${accessoryPath}.label`, 'must be non-blank');
642
+ assertKey(accessory.actionKey, `${accessoryPath}.actionKey`);
643
+ if (accessory.disabled !== undefined && typeof accessory.disabled !== 'boolean') fail(`${accessoryPath}.disabled`, 'must be boolean');
644
+ for (const field of ['textColor', 'backgroundColor', 'pressedBackgroundColor', 'hoverBackgroundColor', 'focusRingColor']) {
645
+ const value = accessory[field];
646
+ if (value !== undefined && (typeof value !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))) fail(`${accessoryPath}.${field}`, 'must be #RRGGBB or #RRGGBBAA');
647
+ }
648
+ }
649
+ if (accessory.kind === 'icon' && accessory.buttonStyle !== undefined && accessory.buttonStyle !== 'tertiary') fail(`${accessoryPath}.buttonStyle`, 'must be tertiary');
544
650
  if (accessory.kind === 'progress' && (accessory.value < 0 || accessory.value > 1)) {
545
651
  fail(`${accessoryPath}.value`, 'must be within 0...1');
546
652
  }
547
653
  if (accessory.kind === 'valuePair') {
654
+ if (accessory.primaryFontWeight !== undefined && accessory.primaryFontWeight !== 'medium') fail(`${accessoryPath}.primaryFontWeight`, 'must be medium when provided');
655
+ assertTextHelp(accessory.primaryHelp, `${accessoryPath}.primaryHelp`);
548
656
  assertTextTone(accessory.primaryTone, `${accessoryPath}.primaryTone`);
549
657
  assertTextTone(accessory.secondaryTone, `${accessoryPath}.secondaryTone`);
658
+ for (const field of ['primaryTextSegments', 'secondaryTextSegments']) {
659
+ const segments = accessory[field];
660
+ if (segments === undefined) continue;
661
+ const segmentPath = `${accessoryPath}.${field}`;
662
+ if (!Array.isArray(segments) || segments.length > 64) fail(segmentPath, 'must be an array of at most 64 segments');
663
+ let textLength = 0;
664
+ segments.forEach((segment, segmentIndex) => {
665
+ const path = `${segmentPath}[${segmentIndex}]`;
666
+ const entry = protocolObject(segment, path);
667
+ assertUnknownKeys(entry, ['text', 'style'], path, 'segment key');
668
+ if (typeof entry.text !== 'string' || entry.text.length > MAX_TEXT_LENGTH) fail(`${path}.text`, `must be a string no longer than ${MAX_TEXT_LENGTH} characters`);
669
+ if (entry.style !== undefined && entry.style !== 'subscript') fail(`${path}.style`, 'must be subscript when provided');
670
+ textLength += entry.text.length;
671
+ });
672
+ if (textLength > MAX_TEXT_LENGTH) fail(segmentPath, `total text must be at most ${MAX_TEXT_LENGTH} characters`);
673
+ }
674
+ }
675
+ });
676
+ }
677
+ function assertTextHelp(help, path) {
678
+ if (help === undefined) return;
679
+ const object = protocolObject(help, path);
680
+ assertUnknownKeys(object, ['actionKey', 'presentation', 'underline'], path, 'help key');
681
+ assertKey(help.actionKey, `${path}.actionKey`);
682
+ if (!['tooltip', 'popover'].includes(help.presentation)) fail(`${path}.presentation`, 'must be tooltip or popover');
683
+ if (help.underline !== undefined && help.underline !== 'dashed') fail(`${path}.underline`, 'must be dashed');
684
+ }
685
+ function assertButtonGroup(row, path) {
686
+ if (!Array.isArray(row.buttons) || row.buttons.length === 0) fail(`${path}.buttons`, 'must contain at least one button');
687
+ const keys = new Set();
688
+ row.buttons.forEach((button, index) => {
689
+ const itemPath = `${path}.buttons[${index}]`;
690
+ const object = protocolObject(button, itemPath);
691
+ assertUnknownKeys(object, ['key', 'label', 'actionKey', 'disabled', 'loading', 'testID', 'accessibilityLabel'], itemPath, 'button key');
692
+ assertKey(button.key, `${itemPath}.key`);
693
+ if (keys.has(button.key)) fail(`${itemPath}.key`, 'duplicate button key');
694
+ keys.add(button.key);
695
+ if (typeof button.label !== 'string' || !button.label.trim() || button.label.length > MAX_TEXT_LENGTH) fail(`${itemPath}.label`, 'must be non-blank bounded text');
696
+ assertKey(button.actionKey, `${itemPath}.actionKey`);
697
+ for (const field of ['disabled', 'loading']) {
698
+ if (button[field] !== undefined && typeof button[field] !== 'boolean') fail(`${itemPath}.${field}`, 'must be boolean');
699
+ }
700
+ for (const field of ['testID', 'accessibilityLabel']) {
701
+ if (button[field] !== undefined && typeof button[field] !== 'string') fail(`${itemPath}.${field}`, 'must be a string');
550
702
  }
551
703
  });
552
704
  }
705
+ function assertIdentityExtras(row, path) {
706
+ for (const field of ['titleIcon', 'secondaryTitleIcon']) {
707
+ const titleIcon = row[field];
708
+ if (titleIcon === undefined) continue;
709
+ const iconPath = `${path}.${field}`;
710
+ const icon = protocolObject(titleIcon, iconPath);
711
+ assertUnknownKeys(icon, ['name', 'tintColor', 'accessibilityLabel', 'hoverActionKey'], iconPath, 'title icon key');
712
+ if (typeof titleIcon.name !== 'string' || !titleIcon.name.trim()) fail(`${iconPath}.name`, 'must be non-blank');
713
+ if (titleIcon.tintColor !== undefined && (typeof titleIcon.tintColor !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(titleIcon.tintColor))) fail(`${iconPath}.tintColor`, 'must be #RRGGBB or #RRGGBBAA');
714
+ if (titleIcon.accessibilityLabel !== undefined && typeof titleIcon.accessibilityLabel !== 'string') fail(`${iconPath}.accessibilityLabel`, 'must be a string');
715
+ if (titleIcon.hoverActionKey !== undefined) assertKey(titleIcon.hoverActionKey, `${iconPath}.hoverActionKey`);
716
+ }
717
+ if (row.titleImage !== undefined) {
718
+ const imagePath = `${path}.titleImage`;
719
+ const descriptor = protocolObject(row.titleImage, imagePath);
720
+ assertUnknownKeys(descriptor, ['image', 'accessibilityLabel', 'hoverActionKey'], imagePath, 'title image key');
721
+ protocolObject(row.titleImage.image, `${imagePath}.image`);
722
+ if (typeof row.titleImage.image.uri !== 'string') fail(`${imagePath}.image.uri`, 'must be a string');
723
+ assertImage(row.titleImage.image, `${imagePath}.image`);
724
+ const {
725
+ width,
726
+ height
727
+ } = row.titleImage.image;
728
+ if (width !== height || width < 1 || width > 40) fail(`${imagePath}.image`, 'must be square within 1...40');
729
+ if (row.titleImage.accessibilityLabel !== undefined && typeof row.titleImage.accessibilityLabel !== 'string') fail(`${imagePath}.accessibilityLabel`, 'must be a string');
730
+ if (row.titleImage.hoverActionKey !== undefined) assertKey(row.titleImage.hoverActionKey, `${imagePath}.hoverActionKey`);
731
+ }
732
+ const ratio = row.style?.leadingContentMaxWidthRatio;
733
+ if (ratio !== undefined && (typeof ratio !== 'number' || !Number.isFinite(ratio) || ratio <= 0 || ratio > 1)) fail(`${path}.style.leadingContentMaxWidthRatio`, 'must be within (0, 1]');
734
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
735
+ }
553
736
  function assertImage(image, path) {
554
737
  if (!image) return;
738
+ if (!isAllowedImageUri(image.uri)) fail(`${path}.uri`, 'unsupported image URI');
555
739
  if (!image.uri.trim()) fail(`${path}.uri`, 'must not be empty');
556
740
  if (image.fallbackUris !== undefined) {
557
741
  if (!Array.isArray(image.fallbackUris)) fail(`${path}.fallbackUris`, 'must be an array');
@@ -594,6 +778,9 @@ function assertLeadingVisual(visual, path) {
594
778
  assertText(visual.cornerIcon?.name, `${path}.cornerIcon.name`);
595
779
  // OneKey patch: validate optional selector overlays at the JSON boundary.
596
780
  assertText(visual.fallbackIcon?.name, `${path}.fallbackIcon.name`);
781
+ if (visual.fallbackTextColor !== undefined && (typeof visual.fallbackTextColor !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(visual.fallbackTextColor))) fail(`${path}.fallbackTextColor`, 'must be a hex color');
782
+ if (visual.fallbackIcon?.size !== undefined && (!Number.isFinite(visual.fallbackIcon.size) || visual.fallbackIcon.size <= 0 || visual.fallbackIcon.size > 40)) fail(`${path}.fallbackIcon.size`, 'must be within (0, 40]');
783
+ if (visual.fallbackIcon?.backgroundColor !== undefined && !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(visual.fallbackIcon.backgroundColor)) fail(`${path}.fallbackIcon.backgroundColor`, 'must be a hex color');
597
784
  if ((visual.overlays?.length ?? 0) > 2) fail(`${path}.overlays`, 'supports at most two overlays');
598
785
  visual.overlays?.forEach((overlay, index) => {
599
786
  if (!['topLeft', 'bottomRight'].includes(overlay.position)) fail(`${path}.overlays[${index}].position`, 'must be topLeft or bottomRight');
@@ -610,7 +797,11 @@ function assertLeadingVisual(visual, path) {
610
797
  }
611
798
  if (overlay.padding !== undefined && overlay.padding * 2 >= Math.min(overlay.width ?? overlay.size ?? 20, overlay.height ?? overlay.size ?? 20)) fail(`${path}.overlays[${index}].padding`, 'must fit inside the overlay');
612
799
  assertImage(overlay.image, `${path}.overlays[${index}].image`);
800
+ if (overlay.fallbackIcon !== undefined && !overlay.image) fail(`${path}.overlays[${index}].fallbackIcon`, 'requires image');
801
+ if (overlay.fallbackIcon !== undefined && (typeof overlay.fallbackIcon.name !== 'string' || !overlay.fallbackIcon.name.trim())) fail(`${path}.overlays[${index}].fallbackIcon.name`, 'must be non-blank');
802
+ if (overlay.fallbackIcon?.tintColor !== undefined && !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(overlay.fallbackIcon.tintColor)) fail(`${path}.overlays[${index}].fallbackIcon.tintColor`, 'must be a hex color');
613
803
  assertText(overlay.text, `${path}.overlays[${index}].text`);
804
+ if (overlay.fontWeight !== undefined && !['regular', 'medium', 'semibold', 'bold'].includes(overlay.fontWeight)) fail(`${path}.overlays[${index}].fontWeight`, 'must be regular, medium, semibold, or bold');
614
805
  });
615
806
  if (visual.kind === 'token') {
616
807
  assertImage(visual.networkImage, `${path}.networkImage`);
@@ -623,11 +814,18 @@ function assertVisual(row, path) {
623
814
  assertLeadingVisual(visual, `${path}.visual[${index}]`);
624
815
  });
625
816
  }
817
+
818
+ /** The type half of the `descriptionActionStart` contract; the range needs the row. */
819
+ function isDescriptionActionStart(value) {
820
+ return Number.isSafeInteger(value) && value >= 0;
821
+ }
626
822
  function assertActivity(row, path) {
823
+ if (row.hideLeading !== undefined && typeof row.hideLeading !== 'boolean') fail(`${path}.hideLeading`, 'must be boolean');
627
824
  assertText(row.title, `${path}.title`);
628
825
  assertText(row.description, `${path}.description`);
629
826
  if (row.presentation !== undefined && !['stacked', 'table'].includes(row.presentation)) fail(`${path}.presentation`, 'must be stacked or table');
630
827
  if (row.descriptionActionKey !== undefined) assertKey(row.descriptionActionKey, `${path}.descriptionActionKey`);
828
+ if (row.descriptionActionStart !== undefined && !isDescriptionActionStart(row.descriptionActionStart)) fail(`${path}.descriptionActionStart`, 'must be a non-negative integer');
631
829
  if ((row.amounts?.length ?? 0) > 32) fail(`${path}.amounts`, 'supports at most 32 amount lines');
632
830
  const amountKeys = new Set();
633
831
  row.amounts?.forEach((amount, index) => {
@@ -702,6 +900,7 @@ function assertRowType(type, path) {
702
900
  }
703
901
  function assertRow(row, index, path = `rows[${index}]`) {
704
902
  assertRowType(row.type, path);
903
+ assertUnknownKeys(row, ROW_FIELDS[row.type], path, 'row key');
705
904
  assertKey(row.key, `${path}.key`);
706
905
  // OneKey patch: explicit dimensions and opacity cannot corrupt list layout.
707
906
  if (row.height !== undefined && (row.height < 0 || row.height > 4096)) fail(`${path}.height`, 'must be within 0...4096');
@@ -720,10 +919,26 @@ function assertRow(row, index, path = `rows[${index}]`) {
720
919
  assertWalletGroup(row, path);
721
920
  break;
722
921
  case 'identity':
922
+ if (row.contentHeight !== undefined && row.contentHeight !== 'auto') {
923
+ fail(`${path}.contentHeight`, 'must be auto');
924
+ }
925
+ if (row.subtitleLines !== undefined && ![0, 1, 2].includes(row.subtitleLines)) {
926
+ fail(`${path}.subtitleLines`, 'must be 0, 1, or 2');
927
+ }
928
+ if (row.longPressActionKey !== undefined) {
929
+ assertKey(row.longPressActionKey, `${path}.longPressActionKey`);
930
+ }
723
931
  if (row.presentation !== undefined && row.presentation !== 'walletSidebar' && row.presentation !== 'accountSelector' && row.presentation !== 'networkSelector') {
724
932
  fail(`${path}.presentation`, 'must be walletSidebar, accountSelector, or networkSelector when provided');
725
933
  }
726
934
  assertText(row.title, `${path}.title`);
935
+ if ((row.titleSuffixes?.length ?? 0) > 3) fail(`${path}.titleSuffixes`, 'supports at most 3 suffixes');
936
+ row.titleSuffixes?.forEach((suffix, index) => {
937
+ assertText(suffix.text, `${path}.titleSuffixes[${index}].text`);
938
+ if (!['secondary', 'disabled'].includes(suffix.tone)) fail(`${path}.titleSuffixes[${index}].tone`, 'must be secondary or disabled');
939
+ if (suffix.maxWidth !== undefined && (!Number.isFinite(suffix.maxWidth) || suffix.maxWidth < 0 || suffix.maxWidth > 4096)) fail(`${path}.titleSuffixes[${index}].maxWidth`, 'must be finite within 0...4096');
940
+ });
941
+ assertIdentityExtras(row, path);
727
942
  assertText(row.subtitle, `${path}.subtitle`);
728
943
  // OneKey patch: selector text segments truncate independently.
729
944
  row.subtitleSegments?.forEach((segment, segmentIndex) => {
@@ -753,12 +968,18 @@ function assertRow(row, index, path = `rows[${index}]`) {
753
968
  break;
754
969
  case 'activity':
755
970
  assertActivity(row, path);
971
+ // Checked on the complete row only: a patch may carry the offset
972
+ // without the description it points into.
973
+ if ((row.descriptionActionStart ?? 0) > (row.description?.length ?? 0)) fail(`${path}.descriptionActionStart`, 'must not exceed the description length');
756
974
  break;
757
975
  case 'message':
976
+ if (row.presentation !== undefined && row.presentation !== 'inlineWarning') {
977
+ fail(`${path}.presentation`, 'must be inlineWarning');
978
+ }
758
979
  assertText(row.title, `${path}.title`);
759
980
  assertText(row.body, `${path}.body`);
760
- if (![1, 2, 3].includes(row.bodyLines ?? 3)) {
761
- fail(`${path}.bodyLines`, 'must be 1, 2, or 3');
981
+ if (![0, 1, 2, 3].includes(row.bodyLines ?? 3)) {
982
+ fail(`${path}.bodyLines`, 'must be 0, 1, 2, or 3');
762
983
  }
763
984
  assertImage(row.thumbnail, `${path}.thumbnail`);
764
985
  break;
@@ -769,6 +990,13 @@ function assertRow(row, index, path = `rows[${index}]`) {
769
990
  row.columns.forEach((column, columnIndex) => {
770
991
  assertKey(column.key, `${path}.columns[${columnIndex}].key`);
771
992
  assertText(column.text, `${path}.columns[${columnIndex}].text`);
993
+ assertIdentityExtras(column, `${path}.columns[${columnIndex}]`);
994
+ for (const field of ['textSegments', 'secondaryTextSegments']) {
995
+ column[field]?.forEach((segment, segmentIndex) => {
996
+ assertText(segment.text, `${path}.columns[${columnIndex}].${field}[${segmentIndex}].text`);
997
+ if (segment.style !== undefined && segment.style !== 'subscript') fail(`${path}.columns[${columnIndex}].${field}[${segmentIndex}].style`, 'must be subscript');
998
+ });
999
+ }
772
1000
  assertText(column.secondaryLeadingText, `${path}.columns[${columnIndex}].secondaryLeadingText`);
773
1001
  assertText(column.secondaryText, `${path}.columns[${columnIndex}].secondaryText`);
774
1002
  assertTextTone(column.secondaryTone, `${path}.columns[${columnIndex}].secondaryTone`);
@@ -776,6 +1004,10 @@ function assertRow(row, index, path = `rows[${index}]`) {
776
1004
  if ((row.badges?.length ?? 0) > MAX_BADGES) {
777
1005
  fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
778
1006
  }
1007
+ if ((row.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
1008
+ fail(`${path}.trailing`, `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`);
1009
+ }
1010
+ assertTrailingAccessories(row.trailing, `${path}.trailing`);
779
1011
  break;
780
1012
  case 'market':
781
1013
  assertMarketRow(row, path);
@@ -826,6 +1058,11 @@ function assertRow(row, index, path = `rows[${index}]`) {
826
1058
  assertText(row.title, `${path}.title`);
827
1059
  assertText(row.subtitle, `${path}.subtitle`);
828
1060
  assertText(row.value, `${path}.value`);
1061
+ if (row.leadingBadge) {
1062
+ assertKey(row.leadingBadge.key, `${path}.leadingBadge.key`);
1063
+ assertText(row.leadingBadge.text, `${path}.leadingBadge.text`);
1064
+ }
1065
+ assertTextHelp(row.valueHelp, `${path}.valueHelp`);
829
1066
  if (row.valueActionKey !== undefined) {
830
1067
  assertKey(row.valueActionKey, `${path}.valueActionKey`);
831
1068
  }
@@ -846,6 +1083,9 @@ function assertRow(row, index, path = `rows[${index}]`) {
846
1083
  }
847
1084
  assertTrailingAccessories(row.trailing, `${path}.trailing`);
848
1085
  break;
1086
+ case 'buttonGroup':
1087
+ assertButtonGroup(row, path);
1088
+ break;
849
1089
  case 'system':
850
1090
  const presentation = 'presentation' in row ? row.presentation : undefined;
851
1091
  if (presentation !== undefined && presentation !== 'market') {
@@ -906,10 +1146,23 @@ function assertMediaPreview(value, path) {
906
1146
  fail(`${path}.probeOrder`, 'must contain one or two distinct image/video candidates');
907
1147
  }
908
1148
  }
909
- export function validateSnapshot(snapshot) {
1149
+ function assertSnapshotContract(snapshot) {
1150
+ if (snapshot.disclosure !== undefined) {
1151
+ if (typeof snapshot.disclosure.expanded !== 'boolean') fail('snapshot.disclosure.expanded', 'must be a boolean');
1152
+ const inset = snapshot.disclosure.expandedTrailingInset;
1153
+ if (inset !== undefined && (!Number.isFinite(inset) || inset < 0)) fail('snapshot.disclosure.expandedTrailingInset', 'must be finite and nonnegative');
1154
+ }
1155
+ if (snapshot.structuralTransition) {
1156
+ assertKey(snapshot.structuralTransition.id, 'snapshot.structuralTransition.id');
1157
+ if (snapshot.structuralTransition.anchorKey !== undefined) assertKey(snapshot.structuralTransition.anchorKey, 'snapshot.structuralTransition.anchorKey');
1158
+ const duration = snapshot.structuralTransition.durationMs;
1159
+ if (duration !== undefined && (!Number.isFinite(duration) || duration < 0 || duration > 2000)) fail('snapshot.structuralTransition.durationMs', 'must be finite within 0...2000');
1160
+ }
910
1161
  if (snapshot.capabilities?.refreshTriggerDistance !== undefined && (!Number.isFinite(snapshot.capabilities.refreshTriggerDistance) || snapshot.capabilities.refreshTriggerDistance <= 0)) fail('capabilities.refreshTriggerDistance', 'must be a positive finite number');
911
1162
  assertPlainSerializable(snapshot, 'snapshot', new Set());
912
1163
  assertText(snapshot.theme?.imageFallbackBackground, 'theme.imageFallbackBackground');
1164
+ if (snapshot.theme?.successBackground !== undefined && (typeof snapshot.theme.successBackground !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.successBackground))) fail('theme.successBackground', 'must be a hex color');
1165
+ if (snapshot.theme?.rowHoverBackground !== undefined && (typeof snapshot.theme.rowHoverBackground !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.rowHoverBackground))) fail('theme.rowHoverBackground', 'must be a hex color');
913
1166
  if (snapshot.schemaVersion !== 1) fail('snapshot.schemaVersion', 'must be 1');
914
1167
  if (!Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0) {
915
1168
  fail('snapshot.generation', 'must be a non-negative safe integer');
@@ -978,7 +1231,626 @@ export function validateSnapshot(snapshot) {
978
1231
  if (snapshot.selection?.mode === 'single' && selectedKeys.size > 1) {
979
1232
  fail('snapshot.selection.selectedKeys', 'supports at most one key in single mode');
980
1233
  }
981
- return normalizeSnapshotStyles(snapshot);
1234
+ return snapshot;
1235
+ }
1236
+ const COMMON_ROW_FIELDS = ['height', 'heightRounding', 'testID', 'opacity', 'backgroundColor', 'backgroundFullWidth', 'pressDisabled', 'key', 'revision', 'sectionKey', 'groupId', 'groupPosition', 'size', 'density', 'disabled', 'selected', 'accessibilityLabel', 'separator', 'type', 'style'];
1237
+ const ROW_FIELDS = {
1238
+ identity: [...COMMON_ROW_FIELDS, 'contentHeight', 'longPressActionKey', 'titleMatch', 'titleActionKey', 'titleActionOnHover', 'subtitleSegments', 'presentation', 'leading', 'leadingAction', 'title', 'titleSuffixes', 'titleIcon', 'secondaryTitleIcon', 'titleImage', 'subtitle', 'tertiary', 'tertiaryTone', 'titleLines', 'subtitleLines', 'badges', 'trailing', 'draggable'],
1239
+ walletGroup: [...COMMON_ROW_FIELDS, 'parent', 'children', 'draggable'],
1240
+ rail: [...COMMON_ROW_FIELDS, 'visual', 'title', 'status', 'badge', 'draggable'],
1241
+ activity: [...COMMON_ROW_FIELDS, 'leading', 'hideLeading', 'secondaryLeading', 'title', 'description', 'status', 'primaryAmount', 'secondaryAmount', 'amounts', 'badges', 'presentation', 'fee', 'descriptionActionKey', 'descriptionActionStart', 'footerActions'],
1242
+ message: [...COMMON_ROW_FIELDS, 'presentation', 'unread', 'leading', 'title', 'body', 'bodyLines', 'time', 'thumbnail'],
1243
+ dataRow: [...COMMON_ROW_FIELDS, 'leading', 'columns', 'trailing', 'checkbox', 'index', 'badge', 'badges', 'favorite', 'favoriteActive'],
1244
+ market: [...COMMON_ROW_FIELDS, 'variant', 'webTable', 'metrics', 'leadingAction', 'leading', 'title', 'subtitle', 'subtitlePrefix', 'subtitleSegments', 'price', 'priceSegments', 'change', 'badges', 'pressActionKey', 'pressInActionKey', 'longPressActionKey', 'diagnostics'],
1245
+ mediaTile: [...COMMON_ROW_FIELDS, 'variant', 'media', 'image', 'imageState', 'networkImage', 'title', 'subtitle', 'badge', 'closeActionKey'],
1246
+ metricCard: [...COMMON_ROW_FIELDS, 'variant', 'title', 'value', 'subtitle', 'trend', 'trendTone', 'visual', 'badge', 'metrics', 'progress'],
1247
+ sectionHeader: [...COMMON_ROW_FIELDS, 'sticky', 'valueActionTestID', 'valueSegments', 'titleActionKey', 'titleActionOnHover', 'presentation', 'indexTitle', 'variant', 'title', 'leadingBadge', 'titleLoading', 'subtitle', 'value', 'valueHelp', 'valueActionKey', 'titleIcon', 'valueIcon', 'checkbox'],
1248
+ action: [...COMMON_ROW_FIELDS, 'presentation', 'title', 'actionKey', 'tone', 'icon', 'checkbox', 'trailing'],
1249
+ buttonGroup: [...COMMON_ROW_FIELDS, 'buttons'],
1250
+ system: [...COMMON_ROW_FIELDS, 'variant', 'presentation', 'loadingStyle', 'message', 'actionKey', 'actionText', 'title', 'borderColor']
1251
+ };
1252
+ const COMMON_PATCH_FIELDS = ['height', 'heightRounding', 'opacity', 'pressDisabled', 'revision', 'disabled', 'selected', 'accessibilityLabel', 'separator', 'style'];
1253
+ const PATCH_FIELDS = {
1254
+ identity: [...COMMON_PATCH_FIELDS, 'contentHeight', 'longPressActionKey', 'titleMatch', 'titleActionKey', 'titleActionOnHover', 'subtitleSegments', 'leading', 'leadingAction', 'title', 'titleSuffixes', 'titleIcon', 'secondaryTitleIcon', 'titleImage', 'subtitle', 'tertiary', 'tertiaryTone', 'subtitleLines', 'badges', 'trailing'],
1255
+ rail: [...COMMON_PATCH_FIELDS, 'title', 'visual', 'status', 'badge'],
1256
+ activity: [...COMMON_PATCH_FIELDS, 'presentation', 'leading', 'title', 'badges', 'status', 'hideLeading', 'secondaryLeading', 'description', 'primaryAmount', 'secondaryAmount', 'amounts', 'fee', 'descriptionActionKey', 'descriptionActionStart', 'footerActions'],
1257
+ message: [...COMMON_PATCH_FIELDS, 'presentation', 'title', 'unread', 'body', 'bodyLines', 'time', 'thumbnail'],
1258
+ dataRow: [...COMMON_PATCH_FIELDS, 'leading', 'badges', 'trailing', 'badge', 'columns', 'checkbox', 'index', 'favorite', 'favoriteActive'],
1259
+ market: [...COMMON_PATCH_FIELDS, 'longPressActionKey', 'subtitleSegments', 'leading', 'leadingAction', 'title', 'subtitle', 'badges', 'webTable', 'metrics', 'price', 'priceSegments', 'change', 'pressActionKey', 'pressInActionKey', 'diagnostics'],
1260
+ mediaTile: [...COMMON_PATCH_FIELDS, 'title', 'subtitle', 'badge', 'media', 'image', 'imageState', 'networkImage', 'closeActionKey'],
1261
+ metricCard: [...COMMON_PATCH_FIELDS, 'title', 'subtitle', 'visual', 'badge', 'variant', 'value', 'trend', 'trendTone', 'metrics', 'progress'],
1262
+ sectionHeader: [...COMMON_PATCH_FIELDS, 'titleActionKey', 'titleActionOnHover', 'title', 'titleIcon', 'subtitle', 'checkbox', 'variant', 'value', 'leadingBadge', 'titleLoading', 'valueHelp', 'valueActionKey', 'valueIcon'],
1263
+ action: [...COMMON_PATCH_FIELDS, 'title', 'trailing', 'checkbox', 'tone', 'icon'],
1264
+ buttonGroup: [...COMMON_PATCH_FIELDS, 'buttons'],
1265
+ system: ['revision', 'disabled', 'message']
1266
+ };
1267
+ function protocolObject(value, path) {
1268
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail(path, 'must be an object');
1269
+ return value;
1270
+ }
1271
+ function protocolKey(value, path) {
1272
+ if (typeof value !== 'string' || value.trim().length === 0) fail(path, 'must be a non-blank string');
1273
+ }
1274
+ const PROTOCOL_ARRAY_FIELDS = new Set(['columns', 'titleSuffixes', 'cells', 'points', 'images', 'overlays', 'badges', 'trailing', 'footerActions', 'buttons', 'amounts', 'metrics', 'children', 'subtitleSegments', 'titleMatch', 'selectedKeys', 'segments', 'hoverSecondary', 'hoverImages', 'secondaryBadges', 'fallbackUris', 'probeOrder', 'priceSegments', 'textSegments', 'secondaryTextSegments', 'primaryTextSegments']);
1275
+ const PROTOCOL_NUMBER_FIELDS = new Set(['leadingContentMaxWidthRatio', 'height', 'width', 'fontSize', 'lineHeight', 'opacity', 'offsetY', 'offsetX', 'cornerRadius', 'borderWidth', 'horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'titleBadgeGap', 'trailingGap', 'start', 'end', 'padding', 'offset', 'overscan', 'minWidth', 'flex', 'paddingStart', 'paddingEnd', 'changeWidth', 'changeHeight', 'changeCornerRadius', 'contentTrailingGap', 'subtitleTrailingPadding', 'partGap', 'contentPadding', 'contentPaddingHorizontal', 'contentPaddingTop', 'contentPaddingBottom', 'itemSpacing', 'gridColumns']);
1276
+
1277
+ /** Validate only shapes that renderers dereference, not display budgets. */
1278
+ function assertProtocolFields(value, path, parentField = '') {
1279
+ if (value === undefined || value === null || typeof value !== 'object') return;
1280
+ if (Array.isArray(value)) {
1281
+ for (const [index, item] of value.entries()) {
1282
+ const itemPath = `${path}[${index}]`;
1283
+ if (['selectedKeys', 'fallbackUris', 'probeOrder'].includes(parentField)) {
1284
+ if (typeof item !== 'string') fail(itemPath, 'must be a string');
1285
+ } else if (parentField === 'points') {
1286
+ if (typeof item !== 'number') fail(itemPath, 'must be a finite number');
1287
+ } else if (parentField === 'hoverImages' && item === null) continue;else protocolObject(item, itemPath);
1288
+ assertProtocolFields(item, itemPath, parentField);
1289
+ }
1290
+ return;
1291
+ }
1292
+ const object = value;
1293
+ if (parentField === 'fallbackIcon') {
1294
+ protocolKey(object.name, `${path}.name`);
1295
+ if (object.size !== undefined && (typeof object.size !== 'number' || !Number.isFinite(object.size) || object.size <= 0 || object.size > 40)) fail(`${path}.size`, 'must be within (0, 40]');
1296
+ for (const field of ['tintColor', 'backgroundColor']) {
1297
+ const color = object[field];
1298
+ if (color !== undefined && (typeof color !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(color))) fail(`${path}.${field}`, 'must be a hex color');
1299
+ }
1300
+ }
1301
+ if (parentField === 'overlays' && object.fallbackIcon !== undefined && !object.image) fail(`${path}.fallbackIcon`, 'requires image');
1302
+ if (!path.includes('.style.') && ['image', 'networkImage', 'thumbnail', 'images', 'hoverImages'].includes(parentField) && typeof object.uri !== 'string') fail(`${path}.uri`, 'must be a string');
1303
+ Object.entries(value).forEach(([field, item]) => {
1304
+ if (item === undefined) return;
1305
+ if (field === 'headers') {
1306
+ const headers = protocolObject(item, `${path}.headers`);
1307
+ for (const [name, headerValue] of Object.entries(headers)) {
1308
+ if (!name.trim() || typeof headerValue !== 'string') fail(`${path}.headers`, 'must contain string headers');
1309
+ }
1310
+ return;
1311
+ }
1312
+ const fieldPath = `${path}.${field}`;
1313
+ if (!path.endsWith('.style') && PROTOCOL_ARRAY_FIELDS.has(field) && !Array.isArray(item)) fail(fieldPath, 'must be an array');
1314
+ if (PROTOCOL_NUMBER_FIELDS.has(field) && typeof item !== 'number') fail(fieldPath, 'must be a finite number');
1315
+ if (PROTOCOL_NUMBER_FIELDS.has(field) && typeof item === 'number' && item < 0 && !['offsetX', 'offsetY'].includes(field)) fail(fieldPath, 'must be non-negative');
1316
+ if (parentField === 'overlays' && field === 'fontWeight' && !['regular', 'medium', 'semibold', 'bold'].includes(item)) fail(fieldPath, 'must be regular, medium, semibold, or bold');
1317
+ if (field === 'buttonStyle' && item !== 'tertiary') fail(fieldPath, 'must be tertiary');
1318
+ if (field === 'hideLeading' && typeof item !== 'boolean') fail(fieldPath, 'must be boolean');
1319
+ if (field === 'key' || field === 'sectionKey' || field === 'groupId' || field === 'actionKey' || field.endsWith('ActionKey')) protocolKey(item, fieldPath);
1320
+ if ((field === 'uri' || field === 'fallbackUri') && typeof item !== 'string') fail(fieldPath, 'must be a string');
1321
+ if (field === 'style' && !(item === 'subscript' && /[Ss]egments\[/.test(path)) || field === 'container') protocolObject(item, fieldPath);
1322
+ if (path.endsWith('.style') && ['title', 'subtitle', 'tertiary', 'body', 'time', 'price', 'change', 'columns', 'columnSecondary', 'value', 'valueSecondary', 'badge', 'description', 'status', 'primaryAmount', 'secondaryAmount', 'trend', 'message', 'actionText'].includes(field)) protocolObject(item, fieldPath);
1323
+ assertProtocolFields(item, fieldPath, field);
1324
+ });
1325
+ }
1326
+ function assertRowProtocol(row, path) {
1327
+ protocolObject(row, path);
1328
+ assertRowType(row.type, path);
1329
+ protocolKey(row.key, `${path}.key`);
1330
+ assertCoreRow(row, path);
1331
+ assertProtocolFields(row, path);
1332
+ for (const field of ['leading', 'visual', 'secondaryLeading']) {
1333
+ const visual = row[field];
1334
+ if (visual !== undefined || field === 'leading' && (row.type === 'identity' || row.type === 'market')) {
1335
+ const object = protocolObject(visual, `${path}.${field}`);
1336
+ if (object.kind === 'stackedImages' && !Array.isArray(object.images)) fail(`${path}.${field}.images`, 'must be an array');
1337
+ }
1338
+ }
1339
+ for (const field of ['title', 'subtitle', 'tertiary', 'body', 'time', 'price', 'indexTitle']) {
1340
+ const value = row[field];
1341
+ if (value !== undefined && typeof value !== 'string') fail(`${path}.${field}`, 'must be a string');
1342
+ }
1343
+ if (row.height !== undefined && row.height < 0) fail(`${path}.height`, 'must be non-negative');
1344
+ if (row.type === 'identity') {
1345
+ if (isDevelopment()) assertIdentityExtras(row, path);
1346
+ if (row.titleSuffixes !== undefined && !Array.isArray(row.titleSuffixes)) fail(`${path}.titleSuffixes`, 'must be an array');
1347
+ row.titleSuffixes?.forEach((suffix, index) => {
1348
+ protocolObject(suffix, `${path}.titleSuffixes[${index}]`);
1349
+ if (typeof suffix.text !== 'string' || !['secondary', 'disabled'].includes(suffix.tone)) fail(`${path}.titleSuffixes[${index}]`, 'invalid title suffix');
1350
+ if (suffix.maxWidth !== undefined && (!Number.isFinite(suffix.maxWidth) || suffix.maxWidth < 0 || suffix.maxWidth > 4096)) fail(`${path}.titleSuffixes[${index}].maxWidth`, 'must be finite within 0...4096');
1351
+ });
1352
+ let end = 0;
1353
+ row.titleMatch?.forEach(match => {
1354
+ if (!Number.isInteger(match.start) || !Number.isInteger(match.end) || match.start < end || match.end <= match.start || match.end > row.title.length) fail(`${path}.titleMatch`, 'invalid text range');
1355
+ end = match.end;
1356
+ });
1357
+ }
1358
+ if (row.type === 'buttonGroup' && isDevelopment()) assertButtonGroup(row, path);
1359
+ if (row.type === 'sectionHeader' && isDevelopment()) assertTextHelp(row.valueHelp, `${path}.valueHelp`);
1360
+ if (row.type === 'mediaTile' && row.media) {
1361
+ protocolObject(row.media.source, `${path}.media.source`);
1362
+ if (!Array.isArray(row.media.probeOrder)) fail(`${path}.media.probeOrder`, 'must be an array');
1363
+ }
1364
+ if (row.type === 'walletGroup') {
1365
+ protocolObject(row.parent, `${path}.parent`);
1366
+ if (!Array.isArray(row.children)) fail(`${path}.children`, 'must be an array');
1367
+ const members = [row.parent, ...row.children];
1368
+ const keys = new Set();
1369
+ if (row.parent.key !== row.key) fail(`${path}.parent.key`, 'must match its group');
1370
+ members.forEach((member, index) => {
1371
+ assertRowProtocol(member, `${path}.members[${index}]`);
1372
+ if (member.type !== 'identity' || keys.has(member.key)) fail(path, 'invalid wallet member identity');
1373
+ keys.add(member.key);
1374
+ });
1375
+ }
1376
+ if (row.type === 'dataRow') {
1377
+ if (!Array.isArray(row.columns)) fail(`${path}.columns`, 'must be an array');
1378
+ row.columns.forEach((column, index) => {
1379
+ const columnPath = `${path}.columns[${index}]`;
1380
+ protocolObject(column, columnPath);
1381
+ if (isDevelopment()) assertIdentityExtras(column, columnPath);
1382
+ });
1383
+ if (isDevelopment()) assertTrailingAccessories(row.trailing, `${path}.trailing`);
1384
+ }
1385
+ if (row.type === 'market') {
1386
+ protocolObject(row.change, `${path}.change`);
1387
+ assertMarketMetrics(row.metrics, `${path}.metrics`);
1388
+ if (row.webTable) {
1389
+ const {
1390
+ columns,
1391
+ cells
1392
+ } = row.webTable;
1393
+ if (!Array.isArray(columns) || !Array.isArray(cells) || columns.length !== cells.length) fail(`${path}.webTable`, 'columns and cells must match');
1394
+ const keys = new Set();
1395
+ columns.forEach((column, index) => {
1396
+ protocolKey(column.key, `${path}.webTable.columns[${index}].key`);
1397
+ if (keys.has(column.key) || cells[index]?.key !== column.key) fail(`${path}.webTable`, 'invalid column identity');
1398
+ keys.add(column.key);
1399
+ const cell = cells[index];
1400
+ if (!['favorite', 'asset', 'text', 'sparkline'].includes(cell.kind)) fail(`${path}.webTable.cells[${index}]`, 'unsupported cell kind');
1401
+ if (cell.kind === 'asset') protocolObject(cell.title, `${path}.webTable.cells[${index}].title`);
1402
+ if ((cell.kind === 'asset' || cell.kind === 'text') && cell.secondary !== undefined && !Array.isArray(cell.secondary)) fail(`${path}.webTable.cells[${index}].secondary`, 'must be an array');
1403
+ if (cell.kind === 'text' && !Array.isArray(cell.primary)) fail(`${path}.webTable.cells[${index}].primary`, 'must be an array');
1404
+ // The Web renderer spreads samples into Math.min/Math.max.
1405
+ if (cell.kind === 'sparkline' && (!Array.isArray(cell.points) || cell.points.length > 256)) fail(`${path}.webTable.cells[${index}].points`, 'must be an array of at most 256 samples');
1406
+ });
1407
+ }
1408
+ }
1409
+ }
1410
+ function assertSnapshotProtocol(snapshot) {
1411
+ protocolObject(snapshot, 'snapshot');
1412
+ if (snapshot.disclosure !== undefined) {
1413
+ protocolObject(snapshot.disclosure, 'snapshot.disclosure');
1414
+ if (typeof snapshot.disclosure.expanded !== 'boolean') fail('snapshot.disclosure.expanded', 'must be a boolean');
1415
+ const inset = snapshot.disclosure.expandedTrailingInset;
1416
+ if (inset !== undefined && (!Number.isFinite(inset) || inset < 0)) fail('snapshot.disclosure.expandedTrailingInset', 'must be finite and nonnegative');
1417
+ }
1418
+ if (snapshot.structuralTransition) {
1419
+ protocolObject(snapshot.structuralTransition, 'snapshot.structuralTransition');
1420
+ protocolKey(snapshot.structuralTransition.id, 'snapshot.structuralTransition.id');
1421
+ if (snapshot.structuralTransition.anchorKey !== undefined) protocolKey(snapshot.structuralTransition.anchorKey, 'snapshot.structuralTransition.anchorKey');
1422
+ const duration = snapshot.structuralTransition.durationMs;
1423
+ if (duration !== undefined && (!Number.isFinite(duration) || duration < 0 || duration > 2000)) fail('snapshot.structuralTransition.durationMs', 'must be finite within 0...2000');
1424
+ }
1425
+ if (snapshot.theme?.successBackground !== undefined && (typeof snapshot.theme.successBackground !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.successBackground))) fail('theme.successBackground', 'must be a hex color');
1426
+ if (snapshot.theme?.rowHoverBackground !== undefined && (typeof snapshot.theme.rowHoverBackground !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(snapshot.theme.rowHoverBackground))) fail('theme.rowHoverBackground', 'must be a hex color');
1427
+ if (snapshot.schemaVersion !== 1) fail('snapshot.schemaVersion', 'must be 1');
1428
+ if (!Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0) fail('snapshot.generation', 'must be a non-negative safe integer');
1429
+ protocolObject(snapshot.layout, 'snapshot.layout');
1430
+ assertProtocolFields(snapshot.layout, 'snapshot.layout');
1431
+ if (snapshot.layout.orientation !== undefined && !['vertical', 'horizontal'].includes(snapshot.layout.orientation)) fail('snapshot.layout.orientation', 'is not supported');
1432
+ if (!['linear', 'sectioned', 'grid', 'table'].includes(snapshot.layout.kind)) fail('snapshot.layout.kind', 'is not supported');
1433
+ if (!Array.isArray(snapshot.rows)) fail('snapshot.rows', 'must be an array');
1434
+ if (snapshot.layout.kind === 'grid' && (!Number.isInteger(snapshot.layout.gridColumns) || (snapshot.layout.gridColumns ?? 0) < 1 || (snapshot.layout.gridColumns ?? 0) > 7)) fail('snapshot.layout.gridColumns', 'must be an integer from 1 to 7');
1435
+ const keys = new Set();
1436
+ for (const [index, row] of snapshot.rows.entries()) {
1437
+ assertRowProtocol(row, `rows[${index}]`);
1438
+ if (keys.has(row.key)) fail(`rows[${index}].key`, 'duplicate row identity');
1439
+ keys.add(row.key);
1440
+ }
1441
+ if (snapshot.emptyState) assertRowProtocol(snapshot.emptyState, 'emptyState');
1442
+ if (snapshot.fixedFooter) assertRowProtocol(snapshot.fixedFooter, 'fixedFooter');
1443
+ if (snapshot.selection) {
1444
+ if (!Array.isArray(snapshot.selection.selectedKeys)) fail('snapshot.selection.selectedKeys', 'must be an array');
1445
+ snapshot.selection.selectedKeys.forEach(key => {
1446
+ if (!keys.has(key)) fail('snapshot.selection.selectedKeys', 'unknown row identity');
1447
+ });
1448
+ }
1449
+ }
1450
+ function isRecord(value) {
1451
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
1452
+ }
1453
+ function isAllowedImageUri(value) {
1454
+ // Keep native file, content, Photos and bundled-resource URIs alongside web images.
1455
+ // Android Release uses android.resource: instead of Metro's HTTP asset URLs.
1456
+ return typeof value === 'string' && value.trim().length > 0 && (!/^[a-z][a-z\d+.-]*:/i.test(value) || /^(https?|file|content|ph|assets-library|asset|res|android\.resource|blob|onekey-avatar):/i.test(value) || /^data:image\//i.test(value));
1457
+ }
1458
+ const IMAGE_FIELDS = ['uri', 'width', 'height', 'headers', 'contentFit', 'cachePolicy', 'autoplay', 'optimizeTos', 'overscan', 'loadingStrategy', 'fallbackUri', 'fallbackUris', 'retryTimes'];
1459
+ const ICON_FIELDS = ['name', 'tintColor', 'backgroundColor', 'size', 'accessibilityLabel', 'hoverActionKey'];
1460
+ const VISUAL_FIELDS = ['kind', 'name', 'image', 'images', 'networkImage', 'shape', 'tintColor', 'backgroundColor', 'fallbackIcon', 'fallbackText', 'fallbackTextColor', 'overlays', 'borderStyle', 'borderColor', 'cornerIcon'];
1461
+ const TEXT_STYLE_FIELDS = ['token', 'fontSize', 'fontWeight', 'color', 'lineHeight', 'lines', 'truncate', 'alignment', 'verticalAlignment', 'offsetY'];
1462
+ const ACCESSORY_FIELDS = {
1463
+ value: ['kind', 'text', 'secondary', 'textSegments'],
1464
+ valuePair: ['kind', 'primary', 'secondary', 'primaryFontWeight', 'primaryHelp', 'primaryTextSegments', 'secondaryTextSegments', 'primaryTone', 'secondaryTone'],
1465
+ button: ['kind', 'label', 'actionKey', 'disabled', 'testID', 'accessibilityLabel', 'textColor', 'backgroundColor', 'pressedBackgroundColor', 'hoverBackgroundColor', 'focusRingColor'],
1466
+ icon: ['kind', 'name', 'tintColor', 'buttonStyle', 'disabled', 'actionKey', 'testID', 'hoverActionKey', 'accessibilityLabel'],
1467
+ checkbox: ['kind', 'state', 'disabled', 'loading', 'target', 'actionKey'],
1468
+ radio: ['kind', 'checked', 'disabled', 'actionKey'],
1469
+ switch: ['kind', 'value', 'disabled', 'actionKey'],
1470
+ chevron: ['kind', 'actionKey'],
1471
+ menu: ['kind', 'actionKey'],
1472
+ drag: ['kind', 'actionKey'],
1473
+ spinner: ['kind'],
1474
+ progress: ['kind', 'value']
1475
+ };
1476
+ const REQUIRED_ROW_FIELDS = {
1477
+ identity: ['title', 'leading'],
1478
+ walletGroup: ['parent', 'children'],
1479
+ rail: ['title', 'visual'],
1480
+ activity: ['title', 'leading'],
1481
+ message: ['title', 'body', 'time'],
1482
+ dataRow: ['columns'],
1483
+ market: ['title', 'leading', 'variant', 'price', 'change'],
1484
+ mediaTile: ['title', 'variant'],
1485
+ metricCard: ['title', 'value'],
1486
+ sectionHeader: ['title', 'sectionKey'],
1487
+ action: ['title', 'actionKey'],
1488
+ buttonGroup: ['buttons'],
1489
+ system: ['variant']
1490
+ };
1491
+ function assertCoreRow(row, path) {
1492
+ const object = row;
1493
+ for (const key of REQUIRED_ROW_FIELDS[row.type]) {
1494
+ const value = object[key];
1495
+ if (value === undefined || value === null) fail(`${path}.${key}`, 'required field');
1496
+ if (['title', 'body', 'time', 'price', 'value', 'variant'].includes(key) && typeof value !== 'string') fail(`${path}.${key}`, 'must be a string');
1497
+ }
1498
+ if (row.type === 'market') {
1499
+ if (!row.price.trim()) fail(`${path}.price`, 'must be nonblank');
1500
+ if (typeof row.change?.text !== 'string') fail(`${path}.change.text`, 'must be a string');
1501
+ }
1502
+ if (row.type === 'activity') {
1503
+ row.amounts?.forEach((amount, index) => {
1504
+ protocolKey(amount.key, `${path}.amounts[${index}].key`);
1505
+ if (typeof amount.text !== 'string') fail(`${path}.amounts[${index}].text`, 'required financial text');
1506
+ });
1507
+ if (row.fee && typeof row.fee.primary !== 'string') fail(`${path}.fee.primary`, 'required financial text');
1508
+ row.footerActions?.forEach((action, index) => {
1509
+ protocolKey(action.key, `${path}.footerActions[${index}].key`);
1510
+ protocolKey(action.label, `${path}.footerActions[${index}].label`);
1511
+ });
1512
+ }
1513
+ if (row.type === 'action') protocolKey(row.actionKey, `${path}.actionKey`);
1514
+ if (row.type === 'sectionHeader') protocolKey(row.sectionKey, `${path}.sectionKey`);
1515
+ if (row.type === 'system' && ['retry', 'warning', 'noMatch'].includes(row.variant)) {
1516
+ if (typeof object.message !== 'string') fail(`${path}.message`, 'must be a string');
1517
+ if (row.variant === 'retry') protocolKey(row.actionKey, `${path}.actionKey`);
1518
+ }
1519
+ if (row.type === 'dataRow') {
1520
+ if (!Array.isArray(row.columns) || row.columns.length === 0) fail(`${path}.columns`, 'required columns');
1521
+ row.columns.forEach((column, index) => {
1522
+ protocolObject(column, `${path}.columns[${index}]`);
1523
+ protocolKey(column.key, `${path}.columns[${index}].key`);
1524
+ if (typeof column.text !== 'string') fail(`${path}.columns[${index}].text`, 'must be a string');
1525
+ });
1526
+ }
1527
+ if (row.type === 'buttonGroup') {
1528
+ if (!Array.isArray(row.buttons) || row.buttons.length === 0) fail(`${path}.buttons`, 'required buttons');
1529
+ const keys = new Set();
1530
+ row.buttons.forEach((button, index) => {
1531
+ const field = `${path}.buttons[${index}]`;
1532
+ protocolObject(button, field);
1533
+ protocolKey(button.key, `${field}.key`);
1534
+ protocolKey(button.actionKey, `${field}.actionKey`);
1535
+ protocolKey(button.label, `${field}.label`);
1536
+ if (keys.has(button.key)) fail(field, 'duplicate button identity');
1537
+ keys.add(button.key);
1538
+ });
1539
+ }
1540
+ for (const field of ['trailing', 'leadingAction', 'titleIcon', 'valueIcon']) {
1541
+ const value = object[field];
1542
+ if (value === undefined) continue;
1543
+ // Identity title icons are decorative descriptors, not trailing controls.
1544
+ if (field === 'titleIcon' && row.type !== 'sectionHeader') continue;
1545
+ const accessories = field === 'trailing' ? value : [value];
1546
+ if (!Array.isArray(accessories)) fail(`${path}.${field}`, 'must be an array');
1547
+ accessories.forEach((accessory, index) => {
1548
+ const entry = protocolObject(accessory, `${path}.${field}[${index}]`);
1549
+ for (const key of entry.kind === 'value' ? ['text'] : entry.kind === 'valuePair' ? ['primary', 'secondary'] : []) {
1550
+ if (typeof entry[key] !== 'string') fail(`${path}.${field}[${index}].${key}`, 'required financial text');
1551
+ }
1552
+ if (['button', 'menu', 'switch'].includes(entry.kind) || 'actionKey' in entry) {
1553
+ protocolKey(entry.actionKey, `${path}.${field}[${index}].actionKey`);
1554
+ if (entry.kind === 'button') protocolKey(entry.label, `${path}.${field}[${index}].label`);
1555
+ }
1556
+ if (entry.kind === 'icon') protocolKey(entry.name, `${path}.${field}[${index}].name`);
1557
+ });
1558
+ }
1559
+ }
1560
+ function pickFields(object, fields) {
1561
+ return Object.fromEntries(Object.entries(object).filter(([key]) => fields.includes(key)));
1562
+ }
1563
+ function sanitizeImage(value) {
1564
+ if (!isRecord(value) || !isAllowedImageUri(value.uri) || typeof value.width !== 'number' || !Number.isFinite(value.width) || value.width <= 0 || typeof value.height !== 'number' || !Number.isFinite(value.height) || value.height <= 0) return undefined;
1565
+ const next = pickFields(value, IMAGE_FIELDS);
1566
+ next.width = Math.min(MAX_IMAGE_EDGE, value.width);
1567
+ next.height = Math.min(MAX_IMAGE_EDGE, value.height);
1568
+ if (next.headers !== undefined) {
1569
+ if (!isRecord(next.headers)) delete next.headers;else next.headers = Object.fromEntries(Object.entries(next.headers).filter(([key, item]) => key.trim() && key.length <= MAX_HEADER_LENGTH && typeof item === 'string' && item.length <= MAX_HEADER_LENGTH).slice(0, MAX_IMAGE_HEADERS));
1570
+ }
1571
+ if (next.fallbackUris !== undefined) {
1572
+ if (Array.isArray(next.fallbackUris)) next.fallbackUris = next.fallbackUris.filter(isAllowedImageUri);else delete next.fallbackUris;
1573
+ }
1574
+ if (next.fallbackUri !== undefined && !isAllowedImageUri(next.fallbackUri)) delete next.fallbackUri;
1575
+ if (next.overscan !== undefined && (typeof next.overscan !== 'number' || !Number.isFinite(next.overscan) || next.overscan < 1 || next.overscan > 4)) delete next.overscan;
1576
+ if (next.retryTimes !== undefined && (typeof next.retryTimes !== 'number' || !Number.isFinite(next.retryTimes) || next.retryTimes < 0)) delete next.retryTimes;
1577
+ const options = {
1578
+ contentFit: ['cover', 'contain', 'fill', 'center'],
1579
+ cachePolicy: ['memory-disk', 'memory', 'disk', 'none'],
1580
+ loadingStrategy: ['static', 'skeleton', 'none']
1581
+ };
1582
+ for (const [key, allowed] of Object.entries(options)) if (next[key] !== undefined && !allowed.includes(next[key])) delete next[key];
1583
+ for (const key of ['autoplay', 'optimizeTos']) if (next[key] !== undefined && typeof next[key] !== 'boolean') delete next[key];
1584
+ return next;
1585
+ }
1586
+ const NESTED_DECORATION_FIELDS = {
1587
+ webTable: ['columns', 'cells', 'testID', 'draggable', 'contextMenuActionKey'],
1588
+ columns: ['key', 'text', 'textSegments', 'titleIcon', 'secondaryTitleIcon', 'secondaryLeadingText', 'secondaryText', 'secondaryTextSegments', 'weight', 'alignment', 'tone', 'secondaryTone', 'width', 'minWidth', 'flex', 'paddingStart', 'paddingEnd'],
1589
+ cells: ['key', 'kind', 'active', 'disabled', 'testID', 'hoverActionKey', 'actionKey', 'accessibilityLabel', 'leading', 'title', 'secondary', 'lineGap', 'secondaryBadges', 'hoverImages', 'hoverSecondary', 'hoverActionLabel', 'badges', 'primary', 'partGap', 'points', 'width', 'height', 'strokeColor', 'fillColor'],
1590
+ badges: ['key', 'text', 'tone', 'iconName', 'icon', 'textColor', 'backgroundColor', 'actionKey', 'accessibilityLabel', 'style'],
1591
+ overlays: ['position', 'size', 'width', 'height', 'padding', 'offset', 'offsetX', 'offsetY', 'image', 'fallbackIcon', 'name', 'text', 'fontWeight', 'tintColor', 'backgroundColor'],
1592
+ primaryHelp: ['actionKey', 'presentation', 'underline'],
1593
+ valueHelp: ['actionKey', 'presentation', 'underline']
1594
+ };
1595
+ function sanitizeDecoration(value, field) {
1596
+ if (value === undefined || value === null) return undefined;
1597
+ if (!Array.isArray(value) && ['image', 'networkImage', 'thumbnail', 'source', 'images', 'hoverImages'].includes(field)) return sanitizeImage(value);
1598
+ if (['titleImage', 'titleIcon', 'secondaryTitleIcon', 'fallbackIcon', 'cornerIcon', 'media'].includes(field) && !isRecord(value)) return undefined;
1599
+ if (field === 'style' && typeof value !== 'string' && !isRecord(value)) return undefined;
1600
+ if (['badges', 'overlays'].includes(field) && !Array.isArray(value) && !isRecord(value)) return undefined;
1601
+ if (field === 'style' && typeof value === 'string') return value === 'subscript' ? value : undefined;
1602
+ if (Array.isArray(value)) {
1603
+ const items = value.map(item => sanitizeDecoration(item, field));
1604
+ return field === 'hoverImages' ? items.map(item => item ?? null) : items.filter(item => item !== undefined);
1605
+ }
1606
+ if (!isRecord(value)) return value;
1607
+ let object = value;
1608
+ if (field === 'titleImage') {
1609
+ const image = sanitizeImage(value.image);
1610
+ if (!image) return undefined;
1611
+ const edge = Math.min(40, Math.max(1, Math.round(Math.min(image.width, image.height))));
1612
+ object = {
1613
+ ...pickFields(value, ['image', 'accessibilityLabel', 'hoverActionKey']),
1614
+ image: {
1615
+ ...image,
1616
+ width: edge,
1617
+ height: edge
1618
+ }
1619
+ };
1620
+ } else if (['titleIcon', 'secondaryTitleIcon', 'fallbackIcon', 'cornerIcon'].includes(field) && value.kind === undefined) {
1621
+ if (typeof value.name !== 'string' || !value.name.trim()) return undefined;
1622
+ object = pickFields(value, ICON_FIELDS);
1623
+ } else if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
1624
+ object = pickFields(value, VISUAL_FIELDS);
1625
+ } else if (field === 'media') {
1626
+ object = pickFields(value, ['source', 'probeOrder']);
1627
+ }
1628
+ if (field === 'trailing' || ['leadingAction', 'titleIcon', 'valueIcon'].includes(field) && object.kind !== undefined) {
1629
+ const fields = ACCESSORY_FIELDS[object.kind];
1630
+ if (fields) object = pickFields(object, fields);
1631
+ } else if (field === 'buttons') object = pickFields(object, ['key', 'label', 'actionKey', 'disabled', 'loading', 'testID', 'accessibilityLabel']);else if (field === 'container') object = pickFields(object, ['height', 'backgroundColor', 'opacity', 'cornerRadius', 'borderWidth', 'borderColor', 'contentVerticalAlignment']);else if (field === 'imageStyle') object = pickFields(object, ['width', 'height', 'shape', 'cornerRadius', 'contentFit']);else if (field === 'style') object = pickFields(object, [...TEXT_STYLE_FIELDS, 'container', ...new Set(Object.values(ROW_BOX_STYLE_KEYS_BY_TYPE).flat()), ...new Set(Object.values(TEXT_STYLE_KEYS_BY_ROW_TYPE).flat()), ...new Set(Object.values(EXTRA_STYLE_KEYS_BY_ROW_TYPE).flat()), 'height']);else if (['title', 'subtitle', 'tertiary', 'body', 'time', 'price', 'change', 'value', 'valueSecondary', 'columnSecondary', 'primaryAmount', 'secondaryAmount', 'description', 'status', 'trend', 'message', 'actionText'].includes(field) && !('text' in object)) {
1632
+ object = pickFields(object, TEXT_STYLE_FIELDS);
1633
+ }
1634
+ if (NESTED_DECORATION_FIELDS[field]) object = pickFields(object, NESTED_DECORATION_FIELDS[field]);
1635
+ if (['textSegments', 'primaryTextSegments', 'secondaryTextSegments', 'priceSegments', 'segments'].includes(field)) object = pickFields(object, ['text', 'style']);
1636
+ if (field === 'subtitleSegments') object = pickFields(object, ['text', 'style', 'textSegments', 'tone', 'separatorBefore']);
1637
+ const styleObject = ['style', 'imageStyle', 'container'].includes(field) || TEXT_STYLE_FIELDS.some(key => key in object);
1638
+ const next = {};
1639
+ for (const [key, item] of Object.entries(object)) {
1640
+ if (item === undefined || item === null) continue;
1641
+ if ((/color$/i.test(key) || /background$/i.test(key)) && (typeof item !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(item))) continue;
1642
+ if (/TextSegments$/.test(key) || ['textSegments', 'priceSegments', 'subtitleSegments', 'segments'].includes(key)) {
1643
+ if (!Array.isArray(item) || item.some(segment => !isRecord(segment) || typeof segment.text !== 'string')) continue;
1644
+ }
1645
+ if (styleObject && PROTOCOL_NUMBER_FIELDS.has(key) && typeof item !== 'number') continue;
1646
+ if (key === 'token' && (typeof item !== 'string' || !Object.hasOwn(TYPOGRAPHY_TOKENS, item))) continue;
1647
+ if (key === 'fontWeight' && !['regular', 'medium', 'semibold', 'bold'].includes(item)) continue;
1648
+ if (['disabled', 'loading', 'checked', 'selected', 'separator', 'hideLeading', 'pressDisabled', 'draggable', 'active', 'autoplay'].includes(key) && typeof item !== 'boolean') continue;
1649
+ if (key === 'primaryFontWeight' && item !== 'medium') continue;
1650
+ if (key === 'buttonStyle' && item !== 'tertiary') continue;
1651
+ if (key === 'hoverActionKey' && (typeof item !== 'string' || !item.trim())) continue;
1652
+ if (key === 'accessibilityLabel' && typeof item !== 'string') continue;
1653
+ if ((field === 'style' || PROTOCOL_NUMBER_FIELDS.has(key)) && typeof item !== 'object' && typeof item === 'number' && (!Number.isFinite(item) || item < 0 && !['offsetX', 'offsetY'].includes(key))) continue;
1654
+ if (field === 'style' && PROTOCOL_NUMBER_FIELDS.has(key) && typeof item !== 'number') continue;
1655
+ if (key === 'leadingContentMaxWidthRatio' && (typeof item !== 'number' || item <= 0 || item > 1)) continue;
1656
+ const normalized = sanitizeDecoration(item, field === 'style' && key === 'image' ? 'imageStyle' : key);
1657
+ if (normalized !== undefined) next[key] = normalized;
1658
+ }
1659
+ if (field === 'titleImage') {
1660
+ // The nested image was already normalized with title-specific geometry.
1661
+ if (!next.image) return undefined;
1662
+ }
1663
+ if (field === 'media' && (!next.source || !Array.isArray(next.probeOrder))) return undefined;
1664
+ if (['leading', 'visual', 'secondaryLeading'].includes(field)) {
1665
+ if (next.kind === 'image' && !next.image) return {
1666
+ kind: 'token',
1667
+ ...pickFields(next, ['fallbackIcon', 'fallbackText', 'fallbackTextColor'])
1668
+ };
1669
+ if (next.kind === 'stackedImages' && (!Array.isArray(next.images) || next.images.length < 2)) return {
1670
+ kind: 'token'
1671
+ };
1672
+ if (next.kind === 'icon' && (typeof next.name !== 'string' || !next.name.trim())) return {
1673
+ kind: 'token'
1674
+ };
1675
+ if (!['token', 'account', 'wallet', 'network', 'image', 'icon', 'stackedImages'].includes(next.kind)) return {
1676
+ kind: 'token'
1677
+ };
1678
+ }
1679
+ if (field === 'overlays' && (!['topLeft', 'bottomRight'].includes(next.position) || !next.image && !next.name && !next.text)) return undefined;
1680
+ if (field === 'trailing' && next.kind === 'icon' && !('actionKey' in value) && (typeof next.name !== 'string' || !next.name.trim())) return undefined;
1681
+ if (field === 'trailing' && !['value', 'valuePair', 'button', 'checkbox', 'radio', 'switch', 'chevron', 'menu', 'drag', 'icon', 'spinner', 'progress'].includes(next.kind) && !('actionKey' in value)) return undefined;
1682
+ if (field === 'badges' && (typeof next.key !== 'string' || !next.text && !next.iconName && !next.icon)) return undefined;
1683
+ if (next.kind === 'sparkline') {
1684
+ const points = Array.isArray(value.points) ? value.points.filter(point => typeof point === 'number' && Number.isFinite(point)).slice(0, 256) : [];
1685
+ // Preserve the table's column identity even when its optional drawing fails.
1686
+ return points.length < 2 ? {
1687
+ key: next.key,
1688
+ kind: 'text',
1689
+ primary: []
1690
+ } : {
1691
+ ...next,
1692
+ points
1693
+ };
1694
+ }
1695
+ return next;
1696
+ }
1697
+ function sanitizeMarketMetrics(value) {
1698
+ if (!Array.isArray(value)) return value;
1699
+ return value.map(metric => {
1700
+ const next = pickFields(metric, MARKET_METRIC_FIELDS);
1701
+ for (const field of ['textSegments', 'secondaryTextSegments']) {
1702
+ if (next[field] !== undefined) next[field] = sanitizeDecoration(next[field], field);
1703
+ }
1704
+ return next;
1705
+ });
1706
+ }
1707
+ function sanitizeRowForProduction(row) {
1708
+ const object = protocolObject(row, 'row');
1709
+ const fields = ROW_FIELDS[row.type];
1710
+ if (!fields) return row;
1711
+ const next = pickFields(object, fields);
1712
+ for (const [field, value] of Object.entries(next)) {
1713
+ if ((/color$/i.test(field) || /background$/i.test(field)) && (typeof value !== 'string' || !/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))) {
1714
+ delete next[field];
1715
+ continue;
1716
+ }
1717
+ if (field === 'descriptionActionStart') {
1718
+ // Renderers clamp an offset past the text; anything else has no meaning.
1719
+ if (!isDescriptionActionStart(value)) delete next[field];
1720
+ continue;
1721
+ }
1722
+ if (field === 'parent' && isRecord(value)) next[field] = sanitizeRowForProduction(value);else if (field === 'children' && Array.isArray(value)) next[field] = value.map(child => sanitizeRowForProduction(child));else {
1723
+ const normalized = row.type === 'market' && field === 'metrics' ? sanitizeMarketMetrics(value) : sanitizeDecoration(value, field);
1724
+ if (normalized === undefined) delete next[field];else next[field] = normalized;
1725
+ }
1726
+ }
1727
+ if (isRecord(next.style)) next.style = pickFields(next.style, ['container', ...ROW_BOX_STYLE_KEYS_BY_TYPE[row.type], ...(TEXT_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? []), ...(EXTRA_STYLE_KEYS_BY_ROW_TYPE[row.type] ?? [])]);
1728
+ return sameJsonValue(row, next) ? row : next;
1729
+ }
1730
+
1731
+ /** Empty images and optional nulls share one meaning before strict assertions. */
1732
+ function normalizeEmptyImages(value, field = '') {
1733
+ if (value === null || value === undefined || typeof value !== 'object') return value;
1734
+ if (Array.isArray(value)) {
1735
+ const next = value.map(item => normalizeEmptyImages(item, field));
1736
+ return next.every((item, index) => item === value[index]) ? value : next.filter(item => item !== undefined);
1737
+ }
1738
+ const object = value;
1739
+ if (typeof object.uri === 'string' && !object.uri.trim() && 'width' in object && 'height' in object) return undefined;
1740
+ let changed = false;
1741
+ const next = {};
1742
+ for (const [key, item] of Object.entries(object)) {
1743
+ const optional = object.type && !['key', 'type', ...(REQUIRED_ROW_FIELDS[object.type] ?? [])].includes(key);
1744
+ if (item === undefined || item === null && optional && !(object.type === 'market' && key === 'metrics') || ['priceSegments', 'subtitleSegments'].includes(key) && Array.isArray(item) && item.length === 0) {
1745
+ changed = true;
1746
+ continue;
1747
+ }
1748
+ const normalized = field === 'headers' ? item : normalizeEmptyImages(item, key);
1749
+ if (normalized !== undefined) next[key] = normalized;
1750
+ if (normalized !== item) changed = true;
1751
+ }
1752
+ if (field === 'media' && object.source !== undefined && next.source === undefined || field === 'titleImage' && object.image !== undefined && next.image === undefined) return undefined;
1753
+ if (['leading', 'visual', 'secondaryLeading'].includes(field) && next.kind === 'image' && !next.image) return {
1754
+ kind: 'token'
1755
+ };
1756
+ if (field === 'overlays' && object.image !== undefined && !next.image) return undefined;
1757
+ return changed ? next : value;
1758
+ }
1759
+ function normalizeSnapshotForProduction(snapshot) {
1760
+ if (!Array.isArray(snapshot.rows)) return snapshot;
1761
+ let rows = snapshot.rows.map(sanitizeRowForProduction);
1762
+ rows = rows.map((row, index) => {
1763
+ if (!row.groupId) return row;
1764
+ const previous = rows[index - 1]?.groupId === row.groupId;
1765
+ const following = rows[index + 1]?.groupId === row.groupId;
1766
+ return {
1767
+ ...row,
1768
+ groupPosition: previous ? following ? 'middle' : 'last' : following ? 'first' : 'single'
1769
+ };
1770
+ });
1771
+ const next = {
1772
+ ...snapshot,
1773
+ rows,
1774
+ ...(snapshot.emptyState ? {
1775
+ emptyState: sanitizeRowForProduction(snapshot.emptyState)
1776
+ } : {}),
1777
+ ...(snapshot.fixedFooter ? {
1778
+ fixedFooter: sanitizeRowForProduction(snapshot.fixedFooter)
1779
+ } : {})
1780
+ };
1781
+ if (snapshot.theme) next.theme = sanitizeDecoration(snapshot.theme, 'theme');
1782
+ if (snapshot.listStyle) next.listStyle = sanitizeDecoration(snapshot.listStyle, 'style');
1783
+ if (snapshot.selection && Array.isArray(snapshot.selection.selectedKeys)) {
1784
+ const selectable = new Set(rows.filter(row => !row.disabled && !['sectionHeader', 'action', 'system', 'buttonGroup', 'market', 'walletGroup'].includes(row.type)).map(row => row.key));
1785
+ const selectedKeys = [...new Set(snapshot.selection.selectedKeys.filter(key => selectable.has(key)))];
1786
+ next.selection = {
1787
+ ...snapshot.selection,
1788
+ selectedKeys: snapshot.selection.mode === 'none' ? [] : snapshot.selection.mode === 'single' ? selectedKeys.slice(0, 1) : selectedKeys
1789
+ };
1790
+ }
1791
+ return sameJsonValue(snapshot, next) ? snapshot : next;
1792
+ }
1793
+ export function validateSnapshot(snapshot) {
1794
+ assertPlainSerializable(snapshot, 'snapshot', new Set(), false);
1795
+ protocolObject(snapshot, 'snapshot');
1796
+ const normalized = normalizeEmptyImages(snapshot);
1797
+ if (Array.isArray(normalized.rows)) {
1798
+ normalized.rows.forEach((row, index) => {
1799
+ if (row.type === 'market') assertMarketMetrics(row.metrics, `snapshot.rows[${index}].metrics`);
1800
+ });
1801
+ }
1802
+ const canonical = isDevelopment() ? normalized : normalizeSnapshotForProduction(normalized);
1803
+ assertPlainSerializable(canonical, 'snapshot', new Set());
1804
+ if (isDevelopment()) assertSnapshotContract(canonical);
1805
+ assertSnapshotProtocol(canonical);
1806
+ return normalizeSnapshotStyles(canonical);
1807
+ }
1808
+ const ownedNativeSnapshots = new WeakMap();
1809
+ function capturePlainData(value, seen = new Map()) {
1810
+ if (value === null || typeof value !== 'object') return value;
1811
+ const previous = seen.get(value);
1812
+ if (previous) return previous;
1813
+ const copy = Array.isArray(value) ? new Array(value.length) : Object.create(Object.getPrototypeOf(value));
1814
+ seen.set(value, copy);
1815
+ const captureKey = key => {
1816
+ Object.defineProperty(copy, key, {
1817
+ value: capturePlainData(value[key], seen),
1818
+ enumerable: true,
1819
+ writable: true,
1820
+ configurable: true
1821
+ });
1822
+ };
1823
+ if (Array.isArray(value)) {
1824
+ for (let index = 0; index < value.length; index += 1) {
1825
+ if (index in value) captureKey(String(index));
1826
+ }
1827
+ Object.keys(value).forEach(key => {
1828
+ const index = Number(key);
1829
+ if (Number.isInteger(index) && index >= 0 && index < value.length && String(index) === key) return;
1830
+ captureKey(key);
1831
+ });
1832
+ } else {
1833
+ Object.keys(value).forEach(captureKey);
1834
+ }
1835
+ return copy;
1836
+ }
1837
+ function deepFreeze(value, seen = new WeakSet()) {
1838
+ if (value === null || typeof value !== 'object' || seen.has(value)) return value;
1839
+ seen.add(value);
1840
+ Object.values(value).forEach(item => deepFreeze(item, seen));
1841
+ return Object.freeze(value);
1842
+ }
1843
+
1844
+ /** Capture caller data once before validation, including accessor values. */
1845
+ export function captureNativeListInput(value) {
1846
+ return capturePlainData(value);
1847
+ }
1848
+
1849
+ /** Private native-wrapper ownership; exported validators keep their public identity. */
1850
+ export function ownValidatedNativeSnapshot(snapshot) {
1851
+ const owned = deepFreeze(snapshot);
1852
+ ownedNativeSnapshots.set(owned, new Map(owned.rows.map((row, index) => [row.key, index])));
1853
+ return owned;
982
1854
  }
983
1855
 
984
1856
  /**
@@ -1000,8 +1872,12 @@ function normalizeSnapshotStyles(snapshot) {
1000
1872
  return {
1001
1873
  ...snapshot,
1002
1874
  rows,
1003
- emptyState,
1004
- fixedFooter
1875
+ ...(emptyState !== undefined ? {
1876
+ emptyState
1877
+ } : {}),
1878
+ ...(fixedFooter !== undefined ? {
1879
+ fixedFooter
1880
+ } : {})
1005
1881
  };
1006
1882
  }
1007
1883
  function assertPatchChanges(patch, index) {
@@ -1024,7 +1900,23 @@ function assertPatchChanges(patch, index) {
1024
1900
  }
1025
1901
  switch (patch.type) {
1026
1902
  case 'identity':
1903
+ if (patch.changes.contentHeight !== undefined && patch.changes.contentHeight !== 'auto') {
1904
+ fail(`${path}.contentHeight`, 'must be auto');
1905
+ }
1906
+ if (patch.changes.subtitleLines !== undefined && ![0, 1, 2].includes(patch.changes.subtitleLines)) {
1907
+ fail(`${path}.subtitleLines`, 'must be 0, 1, or 2');
1908
+ }
1909
+ if (patch.changes.longPressActionKey !== undefined) {
1910
+ assertKey(patch.changes.longPressActionKey, `${path}.longPressActionKey`);
1911
+ }
1027
1912
  assertText(patch.changes.title, `${path}.title`);
1913
+ if ((patch.changes.titleSuffixes?.length ?? 0) > 3) fail(`${path}.titleSuffixes`, 'supports at most 3 suffixes');
1914
+ patch.changes.titleSuffixes?.forEach((suffix, index) => {
1915
+ assertText(suffix.text, `${path}.titleSuffixes[${index}].text`);
1916
+ if (!['secondary', 'disabled'].includes(suffix.tone)) fail(`${path}.titleSuffixes[${index}].tone`, 'must be secondary or disabled');
1917
+ if (suffix.maxWidth !== undefined && (!Number.isFinite(suffix.maxWidth) || suffix.maxWidth < 0 || suffix.maxWidth > 4096)) fail(`${path}.titleSuffixes[${index}].maxWidth`, 'must be finite within 0...4096');
1918
+ });
1919
+ assertIdentityExtras(patch.changes, path);
1028
1920
  assertText(patch.changes.subtitle, `${path}.subtitle`);
1029
1921
  assertText(patch.changes.tertiary, `${path}.tertiary`);
1030
1922
  if (patch.changes.tertiaryTone !== undefined && !['secondary', 'info'].includes(patch.changes.tertiaryTone)) {
@@ -1058,11 +1950,14 @@ function assertPatchChanges(patch, index) {
1058
1950
  }
1059
1951
  break;
1060
1952
  case 'message':
1953
+ if (patch.changes.presentation !== undefined && patch.changes.presentation !== 'inlineWarning') {
1954
+ fail(`${path}.presentation`, 'must be inlineWarning');
1955
+ }
1061
1956
  assertText(patch.changes.title, `${path}.title`);
1062
1957
  assertText(patch.changes.body, `${path}.body`);
1063
1958
  assertText(patch.changes.time, `${path}.time`);
1064
- if (patch.changes.bodyLines !== undefined && ![1, 2, 3].includes(patch.changes.bodyLines)) {
1065
- fail(`${path}.bodyLines`, 'must be 1, 2, or 3');
1959
+ if (patch.changes.bodyLines !== undefined && ![0, 1, 2, 3].includes(patch.changes.bodyLines)) {
1960
+ fail(`${path}.bodyLines`, 'must be 0, 1, 2, or 3');
1066
1961
  }
1067
1962
  assertImage(patch.changes.thumbnail, `${path}.thumbnail`);
1068
1963
  break;
@@ -1073,12 +1968,23 @@ function assertPatchChanges(patch, index) {
1073
1968
  patch.changes.columns?.forEach((column, columnIndex) => {
1074
1969
  assertKey(column.key, `${path}.columns[${columnIndex}].key`);
1075
1970
  assertText(column.text, `${path}.columns[${columnIndex}].text`);
1971
+ assertIdentityExtras(column, `${path}.columns[${columnIndex}]`);
1972
+ for (const field of ['textSegments', 'secondaryTextSegments']) {
1973
+ column[field]?.forEach((segment, segmentIndex) => {
1974
+ assertText(segment.text, `${path}.columns[${columnIndex}].${field}[${segmentIndex}].text`);
1975
+ if (segment.style !== undefined && segment.style !== 'subscript') fail(`${path}.columns[${columnIndex}].${field}[${segmentIndex}].style`, 'must be subscript');
1976
+ });
1977
+ }
1076
1978
  assertText(column.secondaryText, `${path}.columns[${columnIndex}].secondaryText`);
1077
1979
  assertTextTone(column.secondaryTone, `${path}.columns[${columnIndex}].secondaryTone`);
1078
1980
  });
1079
1981
  if ((patch.changes.badges?.length ?? 0) > MAX_BADGES) {
1080
1982
  fail(`${path}.badges`, `supports at most ${MAX_BADGES} badges`);
1081
1983
  }
1984
+ if ((patch.changes.trailing?.length ?? 0) > MAX_TRAILING_ACCESSORIES) {
1985
+ fail(`${path}.trailing`, `supports at most ${MAX_TRAILING_ACCESSORIES} accessories`);
1986
+ }
1987
+ assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
1082
1988
  break;
1083
1989
  case 'market':
1084
1990
  assertMarketRow({
@@ -1137,6 +2043,11 @@ function assertPatchChanges(patch, index) {
1137
2043
  assertText(patch.changes.title, `${path}.title`);
1138
2044
  assertText(patch.changes.subtitle, `${path}.subtitle`);
1139
2045
  assertText(patch.changes.value, `${path}.value`);
2046
+ if (patch.changes.leadingBadge) {
2047
+ assertKey(patch.changes.leadingBadge.key, `${path}.leadingBadge.key`);
2048
+ assertText(patch.changes.leadingBadge.text, `${path}.leadingBadge.text`);
2049
+ }
2050
+ assertTextHelp(patch.changes.valueHelp, `${path}.valueHelp`);
1140
2051
  if (patch.changes.valueActionKey !== undefined) {
1141
2052
  assertKey(patch.changes.valueActionKey, `${path}.valueActionKey`);
1142
2053
  }
@@ -1150,6 +2061,11 @@ function assertPatchChanges(patch, index) {
1150
2061
  }
1151
2062
  assertTrailingAccessories(patch.changes.trailing, `${path}.trailing`);
1152
2063
  break;
2064
+ case 'buttonGroup':
2065
+ if (patch.changes.buttons !== undefined) assertButtonGroup({
2066
+ buttons: patch.changes.buttons
2067
+ }, path);
2068
+ break;
1153
2069
  case 'system':
1154
2070
  assertText(patch.changes.message, `${path}.message`);
1155
2071
  break;
@@ -1157,19 +2073,119 @@ function assertPatchChanges(patch, index) {
1157
2073
  fail(`patches[${index}].type`, 'is not supported');
1158
2074
  }
1159
2075
  }
2076
+ function normalizePatch(patch, index) {
2077
+ const path = `patches[${index}]`;
2078
+ protocolObject(patch, path);
2079
+ protocolKey(patch.key, `${path}.key`);
2080
+ if (isDevelopment()) assertKey(patch.key, `${path}.key`);
2081
+ assertRowType(patch.type, path);
2082
+ const raw = protocolObject(patch.changes, `${path}.changes`);
2083
+ assertPlainSerializable(raw, `${path}.changes`, new Set(), false);
2084
+ const fields = PATCH_FIELDS[patch.type];
2085
+ const changes = {};
2086
+ for (const [field, value] of Object.entries(raw)) {
2087
+ if (value === undefined) continue;
2088
+ if (!fields?.includes(field)) {
2089
+ if (isDevelopment()) fail(`${path}.changes.${field}`, 'unsupported patch field');
2090
+ continue;
2091
+ }
2092
+ if (value === null) {
2093
+ if (patch.type === 'market' && field === 'metrics') fail(`${path}.changes.metrics`, 'use a full snapshot to remove metrics');
2094
+ if (REQUIRED_ROW_FIELDS[patch.type].includes(field) || patch.type === 'system' && field === 'message') {
2095
+ // The concrete system variant is checked after merging with its baseline.
2096
+ if (patch.type !== 'system') fail(`${path}.changes.${field}`, 'required field cannot be cleared');
2097
+ }
2098
+ changes[field] = null;
2099
+ continue;
2100
+ }
2101
+ if (patch.type === 'market' && field === 'metrics') assertMarketMetrics(value, `${path}.changes.metrics`);
2102
+ if (['priceSegments', 'subtitleSegments'].includes(field) && Array.isArray(value) && value.length === 0) {
2103
+ changes[field] = null;
2104
+ continue;
2105
+ }
2106
+ const normalized = normalizeEmptyImages(value, field);
2107
+ if (normalized === undefined) {
2108
+ if (!REQUIRED_ROW_FIELDS[patch.type].includes(field)) changes[field] = null;
2109
+ continue;
2110
+ }
2111
+ const canonical = isDevelopment() ? normalized : patch.type === 'market' && field === 'metrics' ? sanitizeMarketMetrics(normalized) : sanitizeDecoration(normalized, field);
2112
+ if (canonical !== undefined) changes[field] = canonical;else if (field === 'titleImage') changes[field] = null;
2113
+ }
2114
+ if (patch.type === 'market' && Array.isArray(changes.priceSegments) && changes.priceSegments.length > 0 && (typeof changes.price !== 'string' || !changes.price.trim())) fail(`${path}.changes.price`, 'is required when priceSegments is updated');
2115
+ if (!isDevelopment()) {
2116
+ const sanitized = sanitizeRowForProduction({
2117
+ type: patch.type,
2118
+ ...changes
2119
+ });
2120
+ for (const [field, value] of Object.entries(changes)) {
2121
+ if (value === null) continue;
2122
+ if (sanitized[field] === undefined) delete changes[field];else changes[field] = sanitized[field];
2123
+ }
2124
+ }
2125
+ const values = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== null));
2126
+ if (patch.type === 'market' && 'metrics' in changes) assertMarketMetrics(changes.metrics, `${path}.changes.metrics`);
2127
+ assertPlainSerializable(values, `${path}.changes`, new Set());
2128
+ assertProtocolFields(values, `${path}.changes`);
2129
+ if (isDevelopment()) assertPatchChanges({
2130
+ ...patch,
2131
+ changes: values
2132
+ }, index);
2133
+ const normalizedPatch = {
2134
+ type: patch.type,
2135
+ key: patch.key,
2136
+ changes
2137
+ };
2138
+ return Object.keys(changes).length > 0 ? normalizePatchStyles([normalizedPatch])[0] : undefined;
2139
+ }
2140
+ function reportRejectedPatch(index) {
2141
+ console.warn(`NativeList rejected invalid patch unit at patches[${index}]`);
2142
+ }
1160
2143
  export function validatePatches(patches) {
1161
- assertPlainSerializable(patches, 'patches', new Set());
1162
- const keys = new Set();
1163
- patches.forEach((patch, index) => {
1164
- assertKey(patch.key, `patches[${index}].key`);
1165
- if (keys.has(patch.key)) fail(`patches[${index}].key`, `duplicate key "${patch.key}"`);
1166
- keys.add(patch.key);
1167
- if (Object.keys(patch.changes).length === 0) {
1168
- fail(`patches[${index}].changes`, 'must contain at least one field');
2144
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
2145
+ const units = new Map();
2146
+ const rejectedKeys = new Set();
2147
+ const reject = (key, index, error) => {
2148
+ if (isDevelopment()) throw error;
2149
+ rejectedKeys.add(key);
2150
+ reportRejectedPatch(index);
2151
+ };
2152
+ patches.forEach((input, index) => {
2153
+ const key = isRecord(input) && typeof input.key === 'string' ? input.key : '';
2154
+ try {
2155
+ protocolObject(input, `patches[${index}]`);
2156
+ protocolKey(input.key, `patches[${index}].key`);
2157
+ assertRowType(input.type, `patches[${index}]`);
2158
+ const changes = capturePlainData(protocolObject(input.changes, `patches[${index}].changes`));
2159
+ assertPlainSerializable(changes, `patches[${index}].changes`, new Set(), false);
2160
+ const previous = units.get(key);
2161
+ if (previous && previous.patch.type !== input.type) fail(`patches[${index}].type`, 'conflicting row types');
2162
+ const defined = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== undefined));
2163
+ units.set(key, {
2164
+ index,
2165
+ patch: {
2166
+ key,
2167
+ type: input.type,
2168
+ changes: {
2169
+ ...previous?.patch.changes,
2170
+ ...defined
2171
+ }
2172
+ }
2173
+ });
2174
+ } catch (error) {
2175
+ reject(key, index, error);
1169
2176
  }
1170
- assertPatchChanges(patch, index);
1171
2177
  });
1172
- return normalizePatchStyles(patches);
2178
+ const accepted = [];
2179
+ for (const [key, unit] of units) {
2180
+ if (rejectedKeys.has(key)) continue;
2181
+ try {
2182
+ const patch = normalizePatch(unit.patch, unit.index);
2183
+ if (patch) accepted.push(patch);
2184
+ } catch (error) {
2185
+ reject(key, unit.index, error);
2186
+ }
2187
+ }
2188
+ return accepted;
1173
2189
  }
1174
2190
 
1175
2191
  /** Patches reach the native side without passing through a snapshot. */
@@ -1191,31 +2207,230 @@ function normalizePatchStyles(patches) {
1191
2207
  });
1192
2208
  return changed ? next : patches;
1193
2209
  }
1194
- export function applyRowPatches(snapshot, patches) {
1195
- validatePatches(patches);
1196
- const patchByKey = new Map(patches.map(patch => [patch.key, patch]));
1197
- const knownKeys = new Set(snapshot.rows.map(row => row.key));
1198
- patches.forEach(patch => {
1199
- if (!knownKeys.has(patch.key)) fail('patches', `unknown row key "${patch.key}"`);
1200
- });
1201
- const rows = snapshot.rows.map(row => {
1202
- const patch = patchByKey.get(row.key);
1203
- if (!patch) return row;
1204
- if (patch.type !== row.type) {
1205
- fail('patches', `row "${row.key}" is ${row.type}, not ${patch.type}`);
2210
+ const EMPTY_ROW_PATCHES = Object.freeze([]);
2211
+ function sameJsonValue(left, right) {
2212
+ if (left === right) return true;
2213
+ if (left === null || right === null) return false;
2214
+ if (typeof left !== 'object' || typeof right !== 'object') return false;
2215
+ if (Array.isArray(left) || Array.isArray(right)) {
2216
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => sameJsonValue(value, right[index]));
2217
+ }
2218
+ const leftObject = left;
2219
+ const rightObject = right;
2220
+ const leftKeys = Object.keys(leftObject).filter(key => leftObject[key] !== undefined);
2221
+ const rightKeys = Object.keys(rightObject).filter(key => rightObject[key] !== undefined);
2222
+ return leftKeys.length === rightKeys.length && leftKeys.every(key => sameJsonValue(leftObject[key], rightObject[key]));
2223
+ }
2224
+ function sameOptionalPresence(left, right) {
2225
+ return left === undefined === (right === undefined);
2226
+ }
2227
+
2228
+ /** Plan value-only patches; callers own valid immutable snapshots and commit state. */
2229
+ export function planNativeListPatches(previous, next) {
2230
+ if (previous === next) return EMPTY_ROW_PATCHES;
2231
+ const {
2232
+ rows: previousRows,
2233
+ ...previousMetadata
2234
+ } = previous;
2235
+ const {
2236
+ rows: nextRows,
2237
+ ...nextMetadata
2238
+ } = next;
2239
+ if (previousRows.length !== nextRows.length || !sameJsonValue(previousMetadata, nextMetadata)) return undefined;
2240
+ if (previousRows === nextRows) return EMPTY_ROW_PATCHES;
2241
+ const patches = [];
2242
+ for (let index = 0; index < nextRows.length; index += 1) {
2243
+ const oldRow = previousRows[index];
2244
+ const row = nextRows[index];
2245
+ if (oldRow.key !== row.key || oldRow.type !== row.type) return undefined;
2246
+ if (oldRow === row) continue;
2247
+ if (oldRow.type === 'identity' && row.type === 'identity') {
2248
+ const {
2249
+ subtitle: oldSubtitle,
2250
+ subtitleSegments: oldSubtitleSegments,
2251
+ trailing: oldTrailing,
2252
+ ...oldMetadata
2253
+ } = oldRow;
2254
+ const {
2255
+ subtitle,
2256
+ subtitleSegments,
2257
+ trailing,
2258
+ ...metadata
2259
+ } = row;
2260
+ if (!sameOptionalPresence(oldSubtitle, subtitle) || !sameOptionalPresence(oldSubtitleSegments, subtitleSegments) || !sameOptionalPresence(oldTrailing, trailing) || !sameJsonValue(oldMetadata, metadata)) return undefined;
2261
+ if (!sameJsonValue(oldSubtitle, subtitle) || !sameJsonValue(oldSubtitleSegments, subtitleSegments) || !sameJsonValue(oldTrailing, trailing)) {
2262
+ patches.push({
2263
+ type: 'identity',
2264
+ key: row.key,
2265
+ changes: {
2266
+ subtitle,
2267
+ subtitleSegments,
2268
+ trailing
2269
+ }
2270
+ });
2271
+ }
2272
+ } else if (oldRow.type === 'dataRow' && row.type === 'dataRow') {
2273
+ const {
2274
+ columns: oldColumns,
2275
+ trailing: oldTrailing,
2276
+ ...oldMetadata
2277
+ } = oldRow;
2278
+ const {
2279
+ columns,
2280
+ trailing,
2281
+ ...metadata
2282
+ } = row;
2283
+ if (!sameOptionalPresence(oldTrailing, trailing) || !sameJsonValue(oldMetadata, metadata) || !sameJsonValue(oldColumns[0], columns[0])) return undefined;
2284
+ if (!sameJsonValue(oldColumns.slice(1), columns.slice(1)) || !sameJsonValue(oldTrailing, trailing)) {
2285
+ patches.push({
2286
+ type: 'dataRow',
2287
+ key: row.key,
2288
+ changes: {
2289
+ columns,
2290
+ trailing
2291
+ }
2292
+ });
2293
+ }
2294
+ } else if (!sameJsonValue(oldRow, row)) {
2295
+ return undefined;
2296
+ }
2297
+ }
2298
+ return patches.length === 0 ? EMPTY_ROW_PATCHES : patches;
2299
+ }
2300
+ function mergeAndValidateSingleRow(previous, patch, index) {
2301
+ if (previous.key !== patch.key) fail(`patches[${index}].key`, 'does not match row identity');
2302
+ if (previous.type !== patch.type) fail(`patches[${index}].type`, 'does not match row type');
2303
+ const changes = {
2304
+ ...patch.changes
2305
+ };
2306
+ if (previous.type === 'market') {
2307
+ if (typeof changes.price === 'string' && !('priceSegments' in changes) && previous.priceSegments !== undefined) changes.priceSegments = null;
2308
+ if ((previous.webTable !== undefined || 'webTable' in changes) && ['price', 'priceSegments', 'change'].some(field => field in changes) && changes.webTable === undefined) fail(`patches[${index}].changes.webTable`, 'table quote changes require visible table cells');
2309
+ }
2310
+ if (previous.type === 'identity' || previous.type === 'market') {
2311
+ if (typeof changes.subtitle === 'string' && !('subtitleSegments' in changes) && previous.subtitleSegments !== undefined) changes.subtitleSegments = null;
2312
+ if (Array.isArray(changes.subtitleSegments) && changes.subtitleSegments.length > 0 && !('subtitle' in changes) && previous.subtitle !== undefined) changes.subtitle = null;
2313
+ }
2314
+ // The offset points into one specific description string, so a patch that
2315
+ // replaces the description without restating it falls back to the default.
2316
+ if (previous.type === 'activity' && 'description' in changes && changes.description !== previous.description && !('descriptionActionStart' in changes) && previous.descriptionActionStart !== undefined) changes.descriptionActionStart = null;
2317
+ const merged = {
2318
+ ...previous
2319
+ };
2320
+ for (const [field, value] of Object.entries(changes)) {
2321
+ if (value === null) delete merged[field];else if (value !== undefined) merged[field] = value;
2322
+ }
2323
+ const next = normalizeRowStyles(merged);
2324
+ assertPlainSerializable(next, `rows[${index}]`, new Set());
2325
+ if (isDevelopment()) assertRow(next, index);
2326
+ assertRowProtocol(next, `rows[${index}]`);
2327
+ return {
2328
+ row: next,
2329
+ patch: {
2330
+ type: patch.type,
2331
+ key: patch.key,
2332
+ changes
2333
+ }
2334
+ };
2335
+ }
2336
+
2337
+ /** One canonical batch owns both accepted rows and the native wire payload. */
2338
+ export function applyValidatedRowPatches(snapshot, patches) {
2339
+ if (!Array.isArray(patches)) fail('patches', 'must be an array');
2340
+ const owned = ownedNativeSnapshots.has(snapshot);
2341
+ const rowIndexes = ownedNativeSnapshots.get(snapshot) ?? validatedRowIndexes.get(snapshot) ?? new Map(snapshot.rows.map((row, index) => [row.key, index]));
2342
+ validatedRowIndexes.set(snapshot, rowIndexes);
2343
+ const units = new Map();
2344
+ const rejected = new Set();
2345
+ const rejectedGroups = new Set();
2346
+ const reject = (key, index, error) => {
2347
+ if (isDevelopment()) throw error;
2348
+ rejected.add(key);
2349
+ const rowIndex = rowIndexes.get(key);
2350
+ const group = rowIndex === undefined ? undefined : snapshot.rows[rowIndex].groupId;
2351
+ if (group) rejectedGroups.add(group);
2352
+ reportRejectedPatch(index);
2353
+ };
2354
+ patches.forEach((input, index) => {
2355
+ const key = isRecord(input) && typeof input.key === 'string' ? input.key : '';
2356
+ try {
2357
+ protocolObject(input, `patches[${index}]`);
2358
+ protocolKey(input.key, `patches[${index}].key`);
2359
+ const rowIndex = rowIndexes.get(input.key);
2360
+ if (rowIndex === undefined) fail(`patches[${index}].key`, 'unknown row identity');
2361
+ if (snapshot.rows[rowIndex].type !== input.type) fail(`patches[${index}].type`, 'does not match row type');
2362
+ const changes = protocolObject(input.changes, `patches[${index}].changes`);
2363
+ const captured = capturePlainData(changes);
2364
+ assertPlainSerializable(captured, `patches[${index}].changes`, new Set(), false);
2365
+ const previous = units.get(input.key);
2366
+ // Undefined is omitted at every merge, so it cannot overwrite an earlier change.
2367
+ const defined = Object.fromEntries(Object.entries(captured).filter(([, value]) => value !== undefined));
2368
+ units.set(input.key, {
2369
+ index,
2370
+ type: input.type,
2371
+ changes: {
2372
+ ...previous?.changes,
2373
+ ...defined
2374
+ }
2375
+ });
2376
+ } catch (error) {
2377
+ reject(key, index, error);
1206
2378
  }
1207
- if (row.type === 'market' && row.webTable && patch.type === 'market' && (patch.changes.price !== undefined || patch.changes.priceSegments !== undefined || patch.changes.change !== undefined) && patch.changes.webTable === undefined) fail('patches', 'table quote changes must include the visible table cells');
1208
- return {
1209
- ...row,
1210
- ...patch.changes,
1211
- key: row.key,
1212
- type: row.type
1213
- };
1214
2379
  });
1215
- return validateSnapshot({
2380
+ const pending = new Map();
2381
+ for (const [key, unit] of units) {
2382
+ if (rejected.has(key)) continue;
2383
+ try {
2384
+ const patch = normalizePatch({
2385
+ key,
2386
+ type: unit.type,
2387
+ changes: unit.changes
2388
+ }, unit.index);
2389
+ if (!patch) continue;
2390
+ const merged = mergeAndValidateSingleRow(snapshot.rows[rowIndexes.get(key)], patch, rowIndexes.get(key));
2391
+ if (merged.row.disabled && snapshot.selection?.selectedKeys.includes(key)) fail(`patches[${unit.index}]`, 'cannot disable a selected row');
2392
+ pending.set(key, merged);
2393
+ } catch (error) {
2394
+ reject(key, unit.index, error);
2395
+ }
2396
+ }
2397
+ const accepted = [];
2398
+ let rows;
2399
+ for (const [key, value] of pending) {
2400
+ const index = rowIndexes.get(key);
2401
+ const group = snapshot.rows[index].groupId;
2402
+ if (rejected.has(key) || group && rejectedGroups.has(group)) continue;
2403
+ if (!rows) rows = snapshot.rows.slice();
2404
+ rows[index] = owned ? deepFreeze(value.row) : value.row;
2405
+ accepted.push(owned ? deepFreeze(value.patch) : value.patch);
2406
+ }
2407
+ if (!rows) return {
2408
+ patches: EMPTY_ROW_PATCHES,
2409
+ snapshot,
2410
+ json: '[]'
2411
+ };
2412
+ const next = owned ? Object.freeze({
2413
+ ...snapshot,
2414
+ rows: Object.freeze(rows)
2415
+ }) : {
1216
2416
  ...snapshot,
1217
2417
  rows
1218
- });
2418
+ };
2419
+ if (owned) ownedNativeSnapshots.set(next, rowIndexes);else validatedRowIndexes.set(next, rowIndexes);
2420
+ return {
2421
+ patches: accepted,
2422
+ snapshot: next,
2423
+ json: JSON.stringify(accepted)
2424
+ };
2425
+ }
2426
+ const validatedRowIndexes = new WeakMap();
2427
+ export function applyOwnedNativePatches(snapshot, patches) {
2428
+ const owned = ownedNativeSnapshots.has(snapshot) ? snapshot : ownValidatedNativeSnapshot(validateSnapshot(capturePlainData(snapshot)));
2429
+ return applyValidatedRowPatches(owned, patches);
2430
+ }
2431
+ export function applyRowPatches(snapshot, patches) {
2432
+ const baseline = ownedNativeSnapshots.has(snapshot) ? snapshot : validateSnapshot(snapshot);
2433
+ return applyValidatedRowPatches(baseline, patches).snapshot;
1219
2434
  }
1220
2435
  export function serializeSnapshot(snapshot) {
1221
2436
  return JSON.stringify(validateSnapshot(snapshot));