@onekeyfe/react-native-native-list 6.7.0-2 → 6.7.0-21

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