@jsb188/mday 1.1.11 → 1.1.12

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 (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -1,40 +1,40 @@
1
1
  import type {
2
2
  SheetAccessInfoGQL,
3
3
  SheetAuthoritativeCellGQL,
4
- SheetAuthoritativeRegionGQL,
5
4
  SheetBootstrapGQL,
6
5
  SheetBootstrapMode,
7
- SheetCellGQL,
6
+ SheetBootstrapStatus,
7
+ SheetComputedCellGQL,
8
8
  SheetDeletedCellCoordGQL,
9
9
  SheetGQL,
10
+ SheetGridPageInfoGQL,
10
11
  SheetGridViewportObj,
11
12
  SheetJournalSeq,
12
- SheetRangeGQL,
13
- SheetReferencedDataTableSchemaGQL,
14
- SheetRegionGQL,
13
+ SheetRealtimeCapabilityGQL,
14
+ SheetStructureOperationEnum,
15
15
  SheetTabChangeGQL,
16
16
  SheetTabGQL,
17
17
  SheetTabSummaryGQL,
18
- SheetViewGQL,
19
18
  } from '../types/sheet.d.ts';
20
- import {
21
- getSheetViewFullViewport,
22
- normalizeSheetDesign,
23
- normalizeSheetViewport,
24
- } from './sheet.ts';
19
+ import { SHEET_MAX_COLUMN_COUNT, SHEET_MAX_ROW_COUNT, SHEET_STRUCTURE_OPERATION_ENUMS } from '../constants/sheet.ts';
20
+ import { getSheetViewFullViewport, normalizeSheetDesign, normalizeSheetViewport } from './sheetDesign.ts';
21
+ import type { SheetAxisMoveInput } from './sheetAxisMove.ts';
25
22
  import {
26
23
  isHardNewSheetCellsJournalOrderedTargetGroups,
24
+ isSheetComputedJournalCell,
27
25
  SHEET_CELLS_JOURNAL_VERSION,
26
+ SHEET_COMPUTED_JOURNAL_VERSION,
27
+ SHEET_DESIGN_JOURNAL_VERSION,
28
+ SHEET_STRUCTURE_JOURNAL_VERSION,
28
29
  } from './sheetJournal.ts';
29
30
  import {
30
31
  compareSheetJournalSeq,
31
32
  parseSheetJournalSeq,
33
+ SHEET_JOURNAL_MAX_SEQ,
32
34
  SHEET_JOURNAL_ZERO_SEQ,
35
+ sheetJournalSeqIsPositive,
33
36
  } from './sheetSequence.ts';
34
- import {
35
- decodeSheetSnapshot,
36
- isSupportedSheetSnapshotEncodingVersion,
37
- } from './sheetSnapshot.ts';
37
+ import { decodeSheetSnapshot, isSupportedSheetSnapshotEncodingVersion } from './sheetSnapshot.ts';
38
38
 
39
39
  export type SheetBootstrapValidationCode =
40
40
  | 'INVALID_RESPONSE'
@@ -55,23 +55,21 @@ export type ValidatedSheetBootstrapAccess = {
55
55
  signInRequired: boolean;
56
56
  };
57
57
 
58
- export type SheetBootstrapBaseSnapshotIdentity = Readonly<{
58
+ /*
59
+ * One decoded, integrity-checked tab image at a journal seq: the base a
60
+ * SNAPSHOT install replays its tail over. The client's tab store installs it
61
+ * and applies the tail rows through the same reducer as live packets.
62
+ */
63
+ export type SheetBootstrapTabImage = Readonly<{
59
64
  organizationId: string;
60
65
  sheetId: string;
61
66
  sheetTabId: string;
62
67
  seq: SheetJournalSeq;
63
- encodingVersion: number;
64
- checksum: string;
65
- viewport: Readonly<SheetGridViewportObj>;
66
- }>;
68
+ cells: SheetAuthoritativeCellGQL[];
67
69
 
68
- export type SheetBootstrapTabState = Readonly<{
69
- organizationId: string;
70
- sheetId: string;
71
- sheetTabId: string;
72
- baseSnapshot: SheetBootstrapBaseSnapshotIdentity;
73
- appliedSeq: SheetJournalSeq;
74
- view: SheetViewGQL;
70
+ pageInfo: SheetGridPageInfoGQL | null;
71
+ /* The tab image at `seq`, design and designRevision included. */
72
+ sheetTab: SheetTabGQL;
75
73
  }>;
76
74
 
77
75
  export type SheetBootstrapDeniedResult = {
@@ -88,7 +86,6 @@ export type SheetBootstrapDeferredResult = {
88
86
  sheet: SheetGQL | null;
89
87
  tabs: SheetTabSummaryGQL[];
90
88
  selectedTab: SheetTabGQL | null;
91
- referencedDataTables: SheetReferencedDataTableSchemaGQL[];
92
89
  };
93
90
 
94
91
  export type SheetBootstrapReadyResult = {
@@ -102,14 +99,37 @@ export type SheetBootstrapReadyResult = {
102
99
  mode: SheetBootstrapMode;
103
100
  currentSeq: SheetJournalSeq;
104
101
  servedViewport: SheetGridViewportObj;
105
- referencedDataTables: SheetReferencedDataTableSchemaGQL[];
106
- state: SheetBootstrapTabState | null;
102
+
103
+ /* SNAPSHOT: the decoded snapshot image the rows replay over; DELTA: null. */
104
+ image: SheetBootstrapTabImage | null;
105
+ /*
106
+ * The validated journal rows in seq order: the DELTA rows after the
107
+ * requested `sinceSeq`, or the tail after the snapshot image.
108
+ */
109
+ rows: SheetBootstrapRowPatch[];
110
+ /* The seq the rows start after: `sinceSeq` for DELTA, the snapshot seq otherwise. */
111
+ rowsAfterSeq: SheetJournalSeq;
112
+ /*
113
+ * SNAPSHOT answers to a request with `sinceSeq`: the topology rows the
114
+ * image absorbed after it (S-4); null for every other answer.
115
+ */
116
+ topology: SheetBootstrapTopology | null;
107
117
  };
108
118
 
109
- export type SheetBootstrapApplyResult =
110
- | SheetBootstrapDeniedResult
111
- | SheetBootstrapDeferredResult
112
- | SheetBootstrapReadyResult;
119
+ /*
120
+ * The topology rows a SNAPSHOT image absorbed after the request's applied seq
121
+ * (S-4): every STRUCTURE row (a row/column insert, delete or move; the op
122
+ * only, never applied to the image) in (afterSeq, image seq] when `complete`.
123
+ * A client re-maps its pending work through them; an incomplete set is empty
124
+ * and the client fails that work closed.
125
+ */
126
+ export type SheetBootstrapTopology = {
127
+ afterSeq: SheetJournalSeq;
128
+ complete: boolean;
129
+ rows: SheetBootstrapRowPatch[];
130
+ };
131
+
132
+ export type SheetBootstrapApplyResult = SheetBootstrapDeniedResult | SheetBootstrapDeferredResult | SheetBootstrapReadyResult;
113
133
 
114
134
  export type SheetBootstrapSnapshotScope = {
115
135
  organizationId: string;
@@ -120,16 +140,55 @@ export type SheetBootstrapSnapshotScope = {
120
140
 
121
141
  type SheetBootstrapScope = SheetBootstrapSnapshotScope;
122
142
 
123
- type SheetBootstrapCellPatch = {
143
+ /* One replayable DESIGN row: the tab image it carries and its design revision. */
144
+ export type SheetBootstrapDesignPatch = {
145
+ /* The row's tab image (design, name, ...); rename/reorder rows carry no design. */
146
+ tab: Record<string, unknown>;
147
+ designRevision: SheetJournalSeq;
148
+ };
149
+
150
+ /*
151
+ * One replayable structure operation with its design revision fence and command identity.
152
+ */
153
+ export type SheetBootstrapStructurePatch = {
154
+ baseDesignRevision: SheetJournalSeq;
155
+
156
+ designRevision: SheetJournalSeq;
157
+ opId: string | null;
158
+ seq: SheetJournalSeq;
159
+ op:
160
+ | {
161
+ kind: 'INSERT_DELETE';
162
+ operation: SheetStructureOperationEnum;
163
+ index: number;
164
+ }
165
+ | { kind: 'AXIS_MOVE'; axisMoveOps: SheetAxisMoveInput[] };
166
+ };
167
+
168
+ /*
169
+ * One validated journal row, applied as cells, computed values, tombstones and design. Structure operations apply first.
170
+ */
171
+ export type SheetBootstrapRowPatch = {
172
+ kind: 'CELLS' | 'COMPUTED' | 'DESIGN' | 'STRUCTURE';
173
+ seq: SheetJournalSeq;
174
+ commandId: string | null;
124
175
  cells: SheetAuthoritativeCellGQL[];
125
176
  deletedCellCoords: SheetDeletedCellCoordGQL[];
177
+ /* Derived write-backs of one COMPUTED row; [] for every other kind. */
178
+ computedCells: SheetComputedCellGQL[];
179
+ /* Tab image of one DESIGN row; absent for every other kind. */
180
+ design?: SheetBootstrapDesignPatch;
181
+ /* Topology op of one STRUCTURE row; absent for every other kind. */
182
+ structureOp?: SheetBootstrapStructurePatch;
126
183
  };
127
184
 
128
- export const SHEET_BOOTSTRAP_CONTRACT_VERSION = 2;
185
+ export const SHEET_BOOTSTRAP_CONTRACT_VERSION = 4;
129
186
 
130
187
  const FILE_CONSTANTS = {
131
188
  checksumPattern: /^[a-f0-9]{64}$/,
132
189
  canonicalIntegerPattern: /^(0|[1-9]\d*)$/,
190
+ /* A canonical positive journal seq of at most 19 digits (bigint range). */
191
+ positiveSeqPattern: /^[1-9]\d{0,18}$/,
133
192
  };
134
193
 
135
194
  /**
@@ -152,10 +211,7 @@ export class SheetBootstrapValidationError extends Error {
152
211
  /*
153
212
  * Throw one typed bootstrap validation failure.
154
213
  */
155
- function failSheetBootstrap(
156
- code: SheetBootstrapValidationCode,
157
- message: string,
158
- ): never {
214
+ function failSheetBootstrap(code: SheetBootstrapValidationCode, message: string): never {
159
215
  throw new SheetBootstrapValidationError(code, message);
160
216
  }
161
217
 
@@ -181,10 +237,7 @@ function validateSheetBootstrapContract(bootstrap: SheetBootstrapGQL): {
181
237
  contractVersion: typeof SHEET_BOOTSTRAP_CONTRACT_VERSION;
182
238
  } {
183
239
  if (bootstrap.contractVersion !== SHEET_BOOTSTRAP_CONTRACT_VERSION) {
184
- return failSheetBootstrap(
185
- 'INVALID_CONTRACT',
186
- `Unsupported openSheet contract version: ${String(bootstrap.contractVersion)}.`,
187
- );
240
+ return failSheetBootstrap('INVALID_CONTRACT', `Unsupported openSheet contract version: ${String(bootstrap.contractVersion)}.`);
188
241
  }
189
242
  return {
190
243
  contractVersion: SHEET_BOOTSTRAP_CONTRACT_VERSION,
@@ -194,9 +247,7 @@ function validateSheetBootstrapContract(bootstrap: SheetBootstrapGQL): {
194
247
  /*
195
248
  * Return whether a response carries any authorization-scoped workbook data.
196
249
  */
197
- function sheetBootstrapHasScopedReadData(
198
- bootstrap: SheetBootstrapGQL,
199
- ): boolean {
250
+ function sheetBootstrapHasScopedReadData(bootstrap: SheetBootstrapGQL): boolean {
200
251
  return (
201
252
  bootstrap.sheet != null ||
202
253
  bootstrap.tabs != null ||
@@ -206,7 +257,6 @@ function sheetBootstrapHasScopedReadData(
206
257
  bootstrap.servedViewport != null ||
207
258
  bootstrap.snapshot != null ||
208
259
  bootstrap.changes != null ||
209
- bootstrap.referencedDataTables != null ||
210
260
  bootstrap.realtimeToken != null
211
261
  );
212
262
  }
@@ -214,20 +264,9 @@ function sheetBootstrapHasScopedReadData(
214
264
  /*
215
265
  * Return one bounded signed realtime capability without normalizing its bytes.
216
266
  */
217
- function requireSheetBootstrapRealtimeToken(
218
- value: unknown,
219
- label: string,
220
- ): string {
221
- if (
222
- typeof value !== 'string' ||
223
- !value ||
224
- value !== value.trim() ||
225
- value.length > 16_384
226
- ) {
227
- return failSheetBootstrap(
228
- 'INVALID_ACCESS',
229
- `${label} must be a bounded non-empty string.`,
230
- );
267
+ function requireSheetBootstrapRealtimeToken(value: unknown, label: string): string {
268
+ if (typeof value !== 'string' || !value || value !== value.trim() || value.length > 16_384) {
269
+ return failSheetBootstrap('INVALID_ACCESS', `${label} must be a bounded non-empty string.`);
231
270
  }
232
271
 
233
272
  return value;
@@ -236,11 +275,7 @@ function requireSheetBootstrapRealtimeToken(
236
275
  /*
237
276
  * Return a required non-empty GraphQL identifier as an exact string.
238
277
  */
239
- function requireSheetBootstrapId(
240
- value: unknown,
241
- label: string,
242
- code: SheetBootstrapValidationCode = 'SCOPE_MISMATCH',
243
- ): string {
278
+ function requireSheetBootstrapId(value: unknown, label: string, code: SheetBootstrapValidationCode = 'SCOPE_MISMATCH'): string {
244
279
  if (typeof value !== 'string' || !value) {
245
280
  return failSheetBootstrap(code, `${label} must be a non-empty string.`);
246
281
  }
@@ -254,20 +289,15 @@ function requireSheetBootstrapId(
254
289
  function requireSheetBootstrapSeq(
255
290
  value: unknown,
256
291
  label: string,
292
+ code: SheetBootstrapValidationCode = 'INVALID_SEQUENCE',
257
293
  ): SheetJournalSeq {
258
294
  if (typeof value !== 'string') {
259
- return failSheetBootstrap(
260
- 'INVALID_SEQUENCE',
261
- `${label} must be a canonical base-10 string.`,
262
- );
295
+ return failSheetBootstrap(code, `${label} must be a canonical base-10 string.`);
263
296
  }
264
297
 
265
298
  const parsed = parseSheetJournalSeq(value);
266
299
  if (parsed === null || parsed !== value) {
267
- return failSheetBootstrap(
268
- 'INVALID_SEQUENCE',
269
- `${label} is not a canonical journal sequence.`,
270
- );
300
+ return failSheetBootstrap(code, `${label} is not a canonical journal sequence.`);
271
301
  }
272
302
 
273
303
  return parsed;
@@ -278,10 +308,7 @@ function requireSheetBootstrapSeq(
278
308
  */
279
309
  function requireSheetBootstrapGridIndex(value: unknown, label: string): number {
280
310
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
281
- return failSheetBootstrap(
282
- 'INVALID_VIEWPORT',
283
- `${label} must be a positive safe integer.`,
284
- );
311
+ return failSheetBootstrap('INVALID_VIEWPORT', `${label} must be a positive safe integer.`);
285
312
  }
286
313
 
287
314
  return value;
@@ -292,10 +319,7 @@ function requireSheetBootstrapGridIndex(value: unknown, label: string): number {
292
319
  */
293
320
  function requireSheetBootstrapCount(value: unknown, label: string): number {
294
321
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
295
- return failSheetBootstrap(
296
- 'INVALID_SNAPSHOT',
297
- `${label} must be a non-negative safe integer.`,
298
- );
322
+ return failSheetBootstrap('INVALID_SNAPSHOT', `${label} must be a non-negative safe integer.`);
299
323
  }
300
324
 
301
325
  return value;
@@ -304,43 +328,21 @@ function requireSheetBootstrapCount(value: unknown, label: string): number {
304
328
  /*
305
329
  * Validate and copy one full-grid viewport.
306
330
  */
307
- function requireSheetBootstrapViewport(
308
- value: unknown,
309
- label: string,
310
- ): SheetGridViewportObj {
311
- const viewport = requireSheetBootstrapRecord(
312
- value,
313
- label,
314
- 'INVALID_VIEWPORT',
315
- );
331
+ function requireSheetBootstrapViewport(value: unknown, label: string): SheetGridViewportObj {
332
+ const viewport = requireSheetBootstrapRecord(value, label, 'INVALID_VIEWPORT');
316
333
 
317
334
  return {
318
- startRowIndex: requireSheetBootstrapGridIndex(
319
- viewport.startRowIndex,
320
- `${label}.startRowIndex`,
321
- ),
322
- startColumnIndex: requireSheetBootstrapGridIndex(
323
- viewport.startColumnIndex,
324
- `${label}.startColumnIndex`,
325
- ),
326
- rowCount: requireSheetBootstrapGridIndex(
327
- viewport.rowCount,
328
- `${label}.rowCount`,
329
- ),
330
- columnCount: requireSheetBootstrapGridIndex(
331
- viewport.columnCount,
332
- `${label}.columnCount`,
333
- ),
335
+ startRowIndex: requireSheetBootstrapGridIndex(viewport.startRowIndex, `${label}.startRowIndex`),
336
+ startColumnIndex: requireSheetBootstrapGridIndex(viewport.startColumnIndex, `${label}.startColumnIndex`),
337
+ rowCount: requireSheetBootstrapGridIndex(viewport.rowCount, `${label}.rowCount`),
338
+ columnCount: requireSheetBootstrapGridIndex(viewport.columnCount, `${label}.columnCount`),
334
339
  };
335
340
  }
336
341
 
337
342
  /*
338
343
  * Return whether two viewport values describe the exact same grid rectangle.
339
344
  */
340
- function sheetBootstrapViewportsAreEqual(
341
- left: SheetGridViewportObj,
342
- right: SheetGridViewportObj,
343
- ): boolean {
345
+ function sheetBootstrapViewportsAreEqual(left: SheetGridViewportObj, right: SheetGridViewportObj): boolean {
344
346
  return (
345
347
  left.startRowIndex === right.startRowIndex &&
346
348
  left.startColumnIndex === right.startColumnIndex &&
@@ -349,28 +351,10 @@ function sheetBootstrapViewportsAreEqual(
349
351
  );
350
352
  }
351
353
 
352
- /*
353
- * Require an exact viewport match at a negotiated integrity boundary.
354
- */
355
- function requireMatchingSheetBootstrapViewport(
356
- actual: SheetGridViewportObj,
357
- expected: SheetGridViewportObj,
358
- label: string,
359
- ): void {
360
- if (!sheetBootstrapViewportsAreEqual(actual, expected)) {
361
- failSheetBootstrap(
362
- 'INVALID_VIEWPORT',
363
- `${label} does not match the negotiated full-tab viewport.`,
364
- );
365
- }
366
- }
367
-
368
354
  /*
369
355
  * Return the canonical full viewport implied by one selected tab design.
370
356
  */
371
- function getExpectedSheetBootstrapViewport(
372
- selectedTab: SheetTabGQL,
373
- ): SheetGridViewportObj {
357
+ function getExpectedSheetBootstrapViewport(selectedTab: SheetTabGQL): SheetGridViewportObj {
374
358
  return getSheetViewFullViewport(
375
359
  normalizeSheetDesign({
376
360
  grid: selectedTab.design?.grid as any,
@@ -381,55 +365,23 @@ function getExpectedSheetBootstrapViewport(
381
365
  /*
382
366
  * Validate the embedded effective access facts before reading scoped data.
383
367
  */
384
- function validateSheetBootstrapAccess(
385
- value: unknown,
386
- expectedSheetId: string,
387
- ): ValidatedSheetBootstrapAccess {
388
- const access = requireSheetBootstrapRecord(
389
- value,
390
- 'openSheet.access',
391
- 'INVALID_ACCESS',
392
- ) as SheetAccessInfoGQL;
393
- const sheetId = requireSheetBootstrapId(
394
- access.sheetId,
395
- 'openSheet.access.sheetId',
396
- 'INVALID_ACCESS',
397
- );
368
+ function validateSheetBootstrapAccess(value: unknown, expectedSheetId: string): ValidatedSheetBootstrapAccess {
369
+ const access = requireSheetBootstrapRecord(value, 'openSheet.access', 'INVALID_ACCESS') as SheetAccessInfoGQL;
370
+ const sheetId = requireSheetBootstrapId(access.sheetId, 'openSheet.access.sheetId', 'INVALID_ACCESS');
398
371
  if (sheetId !== expectedSheetId) {
399
- failSheetBootstrap(
400
- 'INVALID_ACCESS',
401
- 'openSheet access belongs to a different sheet.',
402
- );
372
+ failSheetBootstrap('INVALID_ACCESS', 'openSheet access belongs to a different sheet.');
403
373
  }
404
374
 
405
- if (
406
- typeof access.canView !== 'boolean' ||
407
- typeof access.canEdit !== 'boolean' ||
408
- typeof access.signInRequired !== 'boolean'
409
- ) {
410
- failSheetBootstrap(
411
- 'INVALID_ACCESS',
412
- 'openSheet access flags must be explicit booleans.',
413
- );
375
+ if (typeof access.canView !== 'boolean' || typeof access.canEdit !== 'boolean' || typeof access.signInRequired !== 'boolean') {
376
+ failSheetBootstrap('INVALID_ACCESS', 'openSheet access flags must be explicit booleans.');
414
377
  }
415
378
 
416
379
  const organizationId =
417
380
  access.organizationId === null || access.organizationId === undefined
418
381
  ? null
419
- : requireSheetBootstrapId(
420
- access.organizationId,
421
- 'openSheet.access.organizationId',
422
- 'INVALID_ACCESS',
423
- );
424
- if (
425
- (access.canView && !organizationId) ||
426
- (access.canEdit && !access.canView) ||
427
- (access.signInRequired && access.canView)
428
- ) {
429
- failSheetBootstrap(
430
- 'INVALID_ACCESS',
431
- 'openSheet access flags are internally inconsistent.',
432
- );
382
+ : requireSheetBootstrapId(access.organizationId, 'openSheet.access.organizationId', 'INVALID_ACCESS');
383
+ if ((access.canView && !organizationId) || (access.canEdit && !access.canView) || (access.signInRequired && access.canView)) {
384
+ failSheetBootstrap('INVALID_ACCESS', 'openSheet access flags are internally inconsistent.');
433
385
  }
434
386
 
435
387
  return {
@@ -441,30 +393,55 @@ function validateSheetBootstrapAccess(
441
393
  };
442
394
  }
443
395
 
396
+ export type ValidatedSheetRealtimeCapability = {
397
+ access: ValidatedSheetBootstrapAccess;
398
+ realtimeToken: string | null;
399
+
400
+ status: SheetBootstrapStatus;
401
+ };
402
+
403
+ /*
404
+ * Validate one capability renewal against the Sheet it renews. READY carries a
405
+ * bounded Sheet token; every other status carries no token at all.
406
+ */
407
+ export function validateSheetRealtimeCapability(value: unknown, expectedSheetId: string): ValidatedSheetRealtimeCapability {
408
+ const capability = requireSheetBootstrapRecord(value, 'renewSheetRealtimeCapability') as SheetRealtimeCapabilityGQL;
409
+ if (!['DENIED', 'READY', 'RETRY', 'UNAVAILABLE'].includes(capability.status)) {
410
+ failSheetBootstrap('INVALID_STATUS', 'renewSheetRealtimeCapability returned an unknown status.');
411
+ }
412
+ const access = validateSheetBootstrapAccess(capability.access, expectedSheetId);
413
+ if (capability.status !== 'READY') {
414
+ return {
415
+ access,
416
+ realtimeToken: null,
417
+
418
+ status: capability.status,
419
+ };
420
+ }
421
+ if (!access.canView) {
422
+ failSheetBootstrap('INVALID_ACCESS', 'A READY capability renewal needs view access.');
423
+ }
424
+
425
+ return {
426
+ access,
427
+ realtimeToken: requireSheetBootstrapRealtimeToken(capability.realtimeToken, 'renewSheetRealtimeCapability.realtimeToken'),
428
+
429
+ status: 'READY',
430
+ };
431
+ }
432
+
444
433
  /*
445
434
  * Validate one workbook's identity against the authorized bootstrap scope.
446
435
  */
447
- function validateSheetBootstrapWorkbook(
448
- value: unknown,
449
- access: ValidatedSheetBootstrapAccess,
450
- ): SheetGQL {
451
- const sheet = requireSheetBootstrapRecord(
452
- value,
453
- 'openSheet.sheet',
454
- ) as SheetGQL;
436
+ function validateSheetBootstrapWorkbook(value: unknown, access: ValidatedSheetBootstrapAccess): SheetGQL {
437
+ const sheet = requireSheetBootstrapRecord(value, 'openSheet.sheet') as SheetGQL;
455
438
  if (
456
- requireSheetBootstrapId(sheet.id, 'openSheet.sheet.id') !==
457
- access.sheetId ||
458
- requireSheetBootstrapId(
459
- sheet.organizationId,
460
- 'openSheet.sheet.organizationId',
461
- ) !== access.organizationId
439
+ requireSheetBootstrapId(sheet.id, 'openSheet.sheet.id') !== access.sheetId ||
440
+ requireSheetBootstrapId(sheet.organizationId, 'openSheet.sheet.organizationId') !== access.organizationId
462
441
  ) {
463
- failSheetBootstrap(
464
- 'SCOPE_MISMATCH',
465
- 'openSheet workbook does not match its authorized scope.',
466
- );
442
+ failSheetBootstrap('SCOPE_MISMATCH', 'openSheet workbook does not match its authorized scope.');
467
443
  }
444
+ requireSheetBootstrapSeq(sheet.manifestRevision, 'openSheet.sheet.manifestRevision');
468
445
 
469
446
  return sheet;
470
447
  }
@@ -472,52 +449,28 @@ function validateSheetBootstrapWorkbook(
472
449
  /*
473
450
  * Validate tab summaries, their exact cursors, and same-workbook references.
474
451
  */
475
- function validateSheetBootstrapTabSummaries(
476
- value: unknown,
477
- ): SheetTabSummaryGQL[] {
452
+ function validateSheetBootstrapTabSummaries(value: unknown): SheetTabSummaryGQL[] {
478
453
  if (!Array.isArray(value)) {
479
- return failSheetBootstrap(
480
- 'INVALID_RESPONSE',
481
- 'openSheet.tabs must be an array.',
482
- );
454
+ return failSheetBootstrap('INVALID_RESPONSE', 'openSheet.tabs must be an array.');
483
455
  }
484
456
 
485
457
  const tabIds = new Set<string>();
486
458
  const tabs = value.map((item, index) => {
487
- const tab = requireSheetBootstrapRecord(
488
- item,
489
- `openSheet.tabs[${index}]`,
490
- ) as SheetTabSummaryGQL;
491
- const tabId = requireSheetBootstrapId(
492
- tab.id,
493
- `openSheet.tabs[${index}].id`,
494
- );
459
+ const tab = requireSheetBootstrapRecord(item, `openSheet.tabs[${index}]`) as SheetTabSummaryGQL;
460
+ const tabId = requireSheetBootstrapId(tab.id, `openSheet.tabs[${index}].id`);
495
461
  if (tabIds.has(tabId)) {
496
- failSheetBootstrap(
497
- 'SCOPE_MISMATCH',
498
- 'openSheet contains duplicate tab summaries.',
499
- );
462
+ failSheetBootstrap('SCOPE_MISMATCH', 'openSheet contains duplicate tab summaries.');
500
463
  }
501
464
  tabIds.add(tabId);
502
- if (
503
- typeof tab.name !== 'string' ||
504
- !tab.name.trim() ||
505
- tab.name !== tab.name.trim()
506
- ) {
507
- failSheetBootstrap(
508
- 'INVALID_RESPONSE',
509
- `openSheet.tabs[${index}].name must be a canonical non-empty string.`,
510
- );
465
+ if (typeof tab.name !== 'string' || !tab.name.trim() || tab.name !== tab.name.trim()) {
466
+ failSheetBootstrap('INVALID_RESPONSE', `openSheet.tabs[${index}].name must be a canonical non-empty string.`);
511
467
  }
512
- requireSheetBootstrapSeq(
513
- tab.currentSeq,
514
- `openSheet.tabs[${index}].currentSeq`,
515
- );
468
+ if (typeof tab.hidden !== 'boolean') {
469
+ failSheetBootstrap('INVALID_RESPONSE', `openSheet.tabs[${index}].hidden must be a boolean.`);
470
+ }
471
+ requireSheetBootstrapSeq(tab.currentSeq, `openSheet.tabs[${index}].currentSeq`);
516
472
  if (!Array.isArray(tab.referencedTabIds)) {
517
- failSheetBootstrap(
518
- 'INVALID_RESPONSE',
519
- `openSheet.tabs[${index}].referencedTabIds must be an array.`,
520
- );
473
+ failSheetBootstrap('INVALID_RESPONSE', `openSheet.tabs[${index}].referencedTabIds must be an array.`);
521
474
  }
522
475
 
523
476
  return tab;
@@ -526,15 +479,9 @@ function validateSheetBootstrapTabSummaries(
526
479
  tabs.forEach((tab, tabIndex) => {
527
480
  const referenceIds = new Set<string>();
528
481
  (tab.referencedTabIds || []).forEach((referenceId, referenceIndex) => {
529
- const id = requireSheetBootstrapId(
530
- referenceId,
531
- `openSheet.tabs[${tabIndex}].referencedTabIds[${referenceIndex}]`,
532
- );
482
+ const id = requireSheetBootstrapId(referenceId, `openSheet.tabs[${tabIndex}].referencedTabIds[${referenceIndex}]`);
533
483
  if (!tabIds.has(id) || referenceIds.has(id)) {
534
- failSheetBootstrap(
535
- 'SCOPE_MISMATCH',
536
- 'openSheet tab references must be unique visible workbook tabs.',
537
- );
484
+ failSheetBootstrap('SCOPE_MISMATCH', 'openSheet tab references must be unique visible workbook tabs.');
538
485
  }
539
486
  referenceIds.add(id);
540
487
  });
@@ -551,96 +498,30 @@ function validateSelectedSheetBootstrapTab(
551
498
  access: ValidatedSheetBootstrapAccess,
552
499
  tabs: SheetTabSummaryGQL[],
553
500
  ): SheetTabGQL {
554
- const selectedTab = requireSheetBootstrapRecord(
555
- value,
556
- 'openSheet.selectedTab',
557
- ) as SheetTabGQL;
558
- const selectedTabId = requireSheetBootstrapId(
559
- selectedTab.id,
560
- 'openSheet.selectedTab.id',
561
- );
501
+ const selectedTab = requireSheetBootstrapRecord(value, 'openSheet.selectedTab') as SheetTabGQL;
502
+ const selectedTabId = requireSheetBootstrapId(selectedTab.id, 'openSheet.selectedTab.id');
562
503
  if (
563
- requireSheetBootstrapId(
564
- selectedTab.organizationId,
565
- 'openSheet.selectedTab.organizationId',
566
- ) !== access.organizationId ||
567
- requireSheetBootstrapId(
568
- selectedTab.sheetId,
569
- 'openSheet.selectedTab.sheetId',
570
- ) !== access.sheetId ||
504
+ requireSheetBootstrapId(selectedTab.organizationId, 'openSheet.selectedTab.organizationId') !== access.organizationId ||
505
+ requireSheetBootstrapId(selectedTab.sheetId, 'openSheet.selectedTab.sheetId') !== access.sheetId ||
571
506
  !tabs.some((tab) => tab.id === selectedTabId)
572
507
  ) {
573
- failSheetBootstrap(
574
- 'SCOPE_MISMATCH',
575
- 'openSheet selected tab is outside the authorized workbook.',
576
- );
508
+ failSheetBootstrap('SCOPE_MISMATCH', 'openSheet selected tab is outside the authorized workbook.');
577
509
  }
578
- requireSheetBootstrapSeq(
579
- selectedTab.designRevision,
580
- 'openSheet.selectedTab.designRevision',
581
- );
510
+ requireSheetBootstrapSeq(selectedTab.designRevision, 'openSheet.selectedTab.designRevision');
582
511
 
583
512
  return selectedTab;
584
513
  }
585
514
 
586
- /*
587
- * Validate the small referenced-table schema set and reject duplicate ids.
588
- */
589
- function validateSheetBootstrapReferencedTables(
590
- value: unknown,
591
- ): SheetReferencedDataTableSchemaGQL[] {
592
- if (!Array.isArray(value)) {
593
- return failSheetBootstrap(
594
- 'INVALID_RESPONSE',
595
- 'openSheet.referencedDataTables must be an array.',
596
- );
597
- }
598
-
599
- const ids = new Set<string>();
600
- return value.map((item, index) => {
601
- const table = requireSheetBootstrapRecord(
602
- item,
603
- `openSheet.referencedDataTables[${index}]`,
604
- ) as SheetReferencedDataTableSchemaGQL;
605
- const id = requireSheetBootstrapId(
606
- table.id,
607
- `openSheet.referencedDataTables[${index}].id`,
608
- );
609
- if (ids.has(id)) {
610
- failSheetBootstrap(
611
- 'SCOPE_MISMATCH',
612
- 'openSheet contains duplicate referenced table schemas.',
613
- );
614
- }
615
- requireSheetBootstrapRealtimeToken(
616
- table.realtimeToken,
617
- `openSheet.referencedDataTables[${index}].realtimeToken`,
618
- );
619
- ids.add(id);
620
- return table;
621
- });
622
- }
623
-
624
515
  /*
625
516
  * Require one tab-owned record to carry the exact authorized ancestry.
626
517
  */
627
- function validateSheetBootstrapRecordScope(
628
- value: Record<string, any>,
629
- scope: SheetBootstrapScope,
630
- label: string,
631
- ): void {
518
+ function validateSheetBootstrapRecordScope(value: Record<string, any>, scope: SheetBootstrapScope, label: string): void {
632
519
  if (
633
- requireSheetBootstrapId(value.organizationId, `${label}.organizationId`) !==
634
- scope.organizationId ||
635
- requireSheetBootstrapId(value.sheetId, `${label}.sheetId`) !==
636
- scope.sheetId ||
637
- requireSheetBootstrapId(value.sheetTabId, `${label}.sheetTabId`) !==
638
- scope.sheetTabId
520
+ requireSheetBootstrapId(value.organizationId, `${label}.organizationId`) !== scope.organizationId ||
521
+ requireSheetBootstrapId(value.sheetId, `${label}.sheetId`) !== scope.sheetId ||
522
+ requireSheetBootstrapId(value.sheetTabId, `${label}.sheetTabId`) !== scope.sheetTabId
639
523
  ) {
640
- failSheetBootstrap(
641
- 'SCOPE_MISMATCH',
642
- `${label} belongs to a different sheet scope.`,
643
- );
524
+ failSheetBootstrap('SCOPE_MISMATCH', `${label} belongs to a different sheet scope.`);
644
525
  }
645
526
  }
646
527
 
@@ -652,28 +533,17 @@ function validateSheetBootstrapCoordinate(
652
533
  scope: SheetBootstrapScope,
653
534
  label: string,
654
535
  ): { rowIndex: number; columnIndex: number } {
655
- const rowIndex = requireSheetBootstrapGridIndex(
656
- value.rowIndex,
657
- `${label}.rowIndex`,
658
- );
659
- const columnIndex = requireSheetBootstrapGridIndex(
660
- value.columnIndex,
661
- `${label}.columnIndex`,
662
- );
663
- const lastRowIndex =
664
- scope.viewport.startRowIndex + scope.viewport.rowCount - 1;
665
- const lastColumnIndex =
666
- scope.viewport.startColumnIndex + scope.viewport.columnCount - 1;
536
+ const rowIndex = requireSheetBootstrapGridIndex(value.rowIndex, `${label}.rowIndex`);
537
+ const columnIndex = requireSheetBootstrapGridIndex(value.columnIndex, `${label}.columnIndex`);
538
+ const lastRowIndex = scope.viewport.startRowIndex + scope.viewport.rowCount - 1;
539
+ const lastColumnIndex = scope.viewport.startColumnIndex + scope.viewport.columnCount - 1;
667
540
  if (
668
541
  rowIndex < scope.viewport.startRowIndex ||
669
542
  rowIndex > lastRowIndex ||
670
543
  columnIndex < scope.viewport.startColumnIndex ||
671
544
  columnIndex > lastColumnIndex
672
545
  ) {
673
- failSheetBootstrap(
674
- 'INVALID_VIEWPORT',
675
- `${label} is outside the served viewport.`,
676
- );
546
+ failSheetBootstrap('INVALID_VIEWPORT', `${label} is outside the served viewport.`);
677
547
  }
678
548
 
679
549
  return { rowIndex, columnIndex };
@@ -682,136 +552,101 @@ function validateSheetBootstrapCoordinate(
682
552
  /*
683
553
  * Validate one replay cell and return its canonical coordinate key.
684
554
  */
685
- function validateSheetBootstrapCell(
686
- value: unknown,
687
- scope: SheetBootstrapScope,
688
- label: string,
689
- ): string {
555
+ function validateSheetBootstrapCell(value: unknown, scope: SheetBootstrapScope, label: string): string {
690
556
  const cell = requireSheetBootstrapRecord(value, label, 'INVALID_CHANGE');
691
557
  validateSheetBootstrapRecordScope(cell, scope, label);
692
558
  requireSheetBootstrapId(cell.id, `${label}.id`, 'INVALID_CHANGE');
693
- requireSheetBootstrapSeq(cell.revision, `${label}.revision`);
559
+ const revision = requireSheetBootstrapSeq(cell.revision, `${label}.revision`);
560
+ if (!sheetJournalSeqIsPositive(revision)) {
561
+ failSheetBootstrap('INVALID_SEQUENCE', `${label}.revision must be positive.`);
562
+ }
694
563
  const coordinate = validateSheetBootstrapCoordinate(cell, scope, label);
695
564
 
696
565
  return `${coordinate.rowIndex}:${coordinate.columnIndex}`;
697
566
  }
698
567
 
699
568
  /*
700
- * Validate one deletion tombstone and return its canonical coordinate key.
569
+ * Return whether one decoded snapshot cell passes every check
570
+ * validateSheetBootstrapCell makes, without building labels or BigInts. A
571
+ * false result only means the caller must run validateSheetBootstrapCell to
572
+ * raise the exact failure.
701
573
  */
702
- function validateSheetBootstrapDeletedCoordinate(
574
+ function isValidSheetBootstrapSnapshotCell(
703
575
  value: unknown,
704
576
  scope: SheetBootstrapScope,
705
- label: string,
706
- ): string {
707
- const coordinate = requireSheetBootstrapRecord(
708
- value,
709
- label,
710
- 'INVALID_CHANGE',
711
- );
712
- if (
713
- requireSheetBootstrapId(
714
- coordinate.sheetTabId,
715
- `${label}.sheetTabId`,
716
- 'INVALID_CHANGE',
717
- ) !== scope.sheetTabId
718
- ) {
719
- failSheetBootstrap(
720
- 'SCOPE_MISMATCH',
721
- `${label} belongs to a different Sheet tab.`,
722
- );
723
- }
724
- const indexes = validateSheetBootstrapCoordinate(coordinate, scope, label);
725
- if (
726
- coordinate.id !== null &&
727
- coordinate.id !== undefined &&
728
- (typeof coordinate.id !== 'string' || !coordinate.id)
729
- ) {
730
- failSheetBootstrap(
731
- 'INVALID_CHANGE',
732
- `${label}.id must be a non-empty string when present.`,
733
- );
577
+ lastRowIndex: number,
578
+ lastColumnIndex: number,
579
+ ): value is Record<string, any> {
580
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
581
+ return false;
734
582
  }
735
583
 
736
- return `${indexes.rowIndex}:${indexes.columnIndex}`;
584
+ const cell = value as Record<string, any>;
585
+ const { id, revision, rowIndex, columnIndex } = cell;
586
+ return (
587
+ typeof cell.organizationId === 'string' &&
588
+ cell.organizationId !== '' &&
589
+ cell.organizationId === scope.organizationId &&
590
+ typeof cell.sheetId === 'string' &&
591
+ cell.sheetId !== '' &&
592
+ cell.sheetId === scope.sheetId &&
593
+ typeof cell.sheetTabId === 'string' &&
594
+ cell.sheetTabId !== '' &&
595
+ cell.sheetTabId === scope.sheetTabId &&
596
+ typeof id === 'string' &&
597
+ id !== '' &&
598
+ typeof revision === 'string' &&
599
+ FILE_CONSTANTS.positiveSeqPattern.test(revision) &&
600
+ (revision.length < 19 || revision <= SHEET_JOURNAL_MAX_SEQ) &&
601
+ typeof rowIndex === 'number' &&
602
+ Number.isSafeInteger(rowIndex) &&
603
+ rowIndex > 0 &&
604
+ typeof columnIndex === 'number' &&
605
+ Number.isSafeInteger(columnIndex) &&
606
+ columnIndex > 0 &&
607
+ !(
608
+ rowIndex < scope.viewport.startRowIndex ||
609
+ rowIndex > lastRowIndex ||
610
+ columnIndex < scope.viewport.startColumnIndex ||
611
+ columnIndex > lastColumnIndex
612
+ )
613
+ );
737
614
  }
738
615
 
739
616
  /*
740
- * Validate one decoded formatting range and its full-tab ancestry and bounds.
617
+ * Validate one deletion tombstone and return its canonical coordinate key.
741
618
  */
742
- function validateSheetBootstrapRange(
743
- value: SheetRangeGQL,
744
- scope: SheetBootstrapScope,
745
- index: number,
746
- ): void {
747
- const label = `snapshot.ranges[${index}]`;
748
- const range = requireSheetBootstrapRecord(value, label, 'INVALID_SNAPSHOT');
749
- validateSheetBootstrapRecordScope(range, scope, label);
750
- requireSheetBootstrapId(range.id, `${label}.id`, 'INVALID_SNAPSHOT');
751
- const start = validateSheetBootstrapCoordinate(
752
- {
753
- rowIndex: range.startRowIndex,
754
- columnIndex: range.startColumnIndex,
755
- },
756
- scope,
757
- `${label}.start`,
758
- );
759
- const end = validateSheetBootstrapCoordinate(
760
- {
761
- rowIndex: range.endRowIndex,
762
- columnIndex: range.endColumnIndex,
763
- },
764
- scope,
765
- `${label}.end`,
766
- );
767
- if (end.rowIndex < start.rowIndex || end.columnIndex < start.columnIndex) {
768
- failSheetBootstrap('INVALID_SNAPSHOT', `${label} has inverted bounds.`);
619
+ function validateSheetBootstrapDeletedCoordinate(value: unknown, scope: SheetBootstrapScope, label: string): string {
620
+ const coordinate = requireSheetBootstrapRecord(value, label, 'INVALID_CHANGE');
621
+ if (requireSheetBootstrapId(coordinate.sheetTabId, `${label}.sheetTabId`, 'INVALID_CHANGE') !== scope.sheetTabId) {
622
+ failSheetBootstrap('SCOPE_MISMATCH', `${label} belongs to a different Sheet tab.`);
623
+ }
624
+ const indexes = validateSheetBootstrapCoordinate(coordinate, scope, label);
625
+ if (coordinate.id === null && coordinate.revision === null) {
626
+ return `${indexes.rowIndex}:${indexes.columnIndex}`;
627
+ }
628
+ if (typeof coordinate.id !== 'string' || !coordinate.id || coordinate.id.trim() !== coordinate.id) {
629
+ failSheetBootstrap('INVALID_CHANGE', `${label}.id must be a non-empty string or explicit null.`);
630
+ }
631
+ const revision = requireSheetBootstrapSeq(coordinate.revision, `${label}.revision`);
632
+ if (!sheetJournalSeqIsPositive(revision)) {
633
+ failSheetBootstrap('INVALID_SEQUENCE', `${label}.revision must be positive.`);
769
634
  }
770
- }
771
635
 
772
- /*
773
- * Validate one decoded region's ancestry and anchor coordinate.
774
- */
775
- function validateSheetBootstrapRegion(
776
- value: SheetRegionGQL,
777
- scope: SheetBootstrapScope,
778
- index: number,
779
- ): void {
780
- const label = `snapshot.regions[${index}]`;
781
- const region = requireSheetBootstrapRecord(value, label, 'INVALID_SNAPSHOT');
782
- validateSheetBootstrapRecordScope(region, scope, label);
783
- requireSheetBootstrapId(region.id, `${label}.id`, 'INVALID_SNAPSHOT');
784
- validateSheetBootstrapCoordinate(
785
- {
786
- rowIndex: region.startRowIndex,
787
- columnIndex: region.startColumnIndex,
788
- },
789
- scope,
790
- `${label}.start`,
791
- );
636
+ return `${indexes.rowIndex}:${indexes.columnIndex}`;
792
637
  }
793
638
 
794
639
  /*
795
640
  * Compute the lowercase SHA-256 checksum for an exact UTF-8 snapshot payload.
796
641
  */
797
- export async function getSheetBootstrapPayloadChecksum(
798
- payload: string,
799
- ): Promise<string> {
642
+ export async function getSheetBootstrapPayloadChecksum(payload: string): Promise<string> {
800
643
  if (!globalThis.crypto?.subtle) {
801
- return failSheetBootstrap(
802
- 'INVALID_SNAPSHOT',
803
- 'SHA-256 is unavailable in this runtime.',
804
- );
644
+ return failSheetBootstrap('INVALID_SNAPSHOT', 'SHA-256 is unavailable in this runtime.');
805
645
  }
806
646
 
807
- const digest = await globalThis.crypto.subtle.digest(
808
- 'SHA-256',
809
- new TextEncoder().encode(payload),
810
- );
647
+ const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(payload));
811
648
 
812
- return Array.from(new Uint8Array(digest), (byte) =>
813
- byte.toString(16).padStart(2, '0'),
814
- ).join('');
649
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
815
650
  }
816
651
 
817
652
  /*
@@ -827,76 +662,43 @@ export async function decodeVerifiedSheetBootstrapSnapshot(params: {
827
662
  checksum: string;
828
663
  data: ReturnType<typeof decodeSheetSnapshot>;
829
664
  }> {
830
- const snapshot = requireSheetBootstrapRecord(
831
- params.snapshot,
832
- 'openSheet.snapshot',
833
- 'INVALID_SNAPSHOT',
834
- );
665
+ const snapshot = requireSheetBootstrapRecord(params.snapshot, 'openSheet.snapshot', 'INVALID_SNAPSHOT');
835
666
  const seq = requireSheetBootstrapSeq(snapshot.seq, 'openSheet.snapshot.seq');
836
667
  if (compareSheetJournalSeq(seq, params.currentSeq) > 0) {
837
- failSheetBootstrap(
838
- 'INVALID_SEQUENCE',
839
- 'openSheet snapshot sequence is ahead of the selected tab.',
840
- );
668
+ failSheetBootstrap('INVALID_SEQUENCE', 'openSheet snapshot sequence is ahead of the selected tab.');
841
669
  }
842
670
  if (!isSupportedSheetSnapshotEncodingVersion(snapshot.encodingVersion)) {
843
- failSheetBootstrap(
844
- 'INVALID_SNAPSHOT',
845
- 'openSheet snapshot encoding version is unsupported.',
846
- );
671
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot encoding version is unsupported.');
847
672
  }
848
- const viewport = requireSheetBootstrapViewport(
849
- snapshot.viewport,
850
- 'openSheet.snapshot.viewport',
851
- );
852
- requireMatchingSheetBootstrapViewport(
853
- viewport,
854
- params.scope.viewport,
855
- 'openSheet snapshot viewport',
856
- );
673
+ // Contract 3 selects only {seq, encodingVersion, checksum, payload}: the
674
+ // viewport, byte and cell counts are verified when a server still sends
675
+ // them; otherwise the image is checked against its own full grid.
676
+ const servedViewport =
677
+ snapshot.viewport === null || snapshot.viewport === undefined
678
+ ? null
679
+ : requireSheetBootstrapViewport(snapshot.viewport, 'openSheet.snapshot.viewport');
680
+ const viewport = servedViewport ?? params.scope.viewport;
857
681
  if (typeof snapshot.payload !== 'string' || !snapshot.payload) {
858
- failSheetBootstrap(
859
- 'INVALID_SNAPSHOT',
860
- 'openSheet snapshot payload must be a non-empty string.',
861
- );
862
- }
863
- if (
864
- typeof snapshot.checksum !== 'string' ||
865
- !FILE_CONSTANTS.checksumPattern.test(snapshot.checksum)
866
- ) {
867
- failSheetBootstrap(
868
- 'INVALID_SNAPSHOT',
869
- 'openSheet snapshot checksum must be lowercase SHA-256.',
870
- );
682
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot payload must be a non-empty string.');
871
683
  }
872
- if (
873
- typeof snapshot.payloadBytes !== 'string' ||
874
- !FILE_CONSTANTS.canonicalIntegerPattern.test(snapshot.payloadBytes)
875
- ) {
876
- failSheetBootstrap(
877
- 'INVALID_SNAPSHOT',
878
- 'openSheet snapshot payloadBytes must be a canonical integer string.',
879
- );
684
+ if (typeof snapshot.checksum !== 'string' || !FILE_CONSTANTS.checksumPattern.test(snapshot.checksum)) {
685
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot checksum must be lowercase SHA-256.');
880
686
  }
881
- const cellCount = requireSheetBootstrapCount(
882
- snapshot.cellCount,
883
- 'openSheet.snapshot.cellCount',
884
- );
885
- const payloadBytes = new TextEncoder().encode(snapshot.payload).byteLength;
886
- if (BigInt(snapshot.payloadBytes) !== BigInt(payloadBytes)) {
887
- failSheetBootstrap(
888
- 'INVALID_SNAPSHOT',
889
- 'openSheet snapshot UTF-8 byte length does not match metadata.',
890
- );
687
+ if (snapshot.payloadBytes !== null && snapshot.payloadBytes !== undefined) {
688
+ if (typeof snapshot.payloadBytes !== 'string' || !FILE_CONSTANTS.canonicalIntegerPattern.test(snapshot.payloadBytes)) {
689
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot payloadBytes must be a canonical integer string.');
690
+ }
691
+ const payloadBytes = new TextEncoder().encode(snapshot.payload).byteLength;
692
+ if (BigInt(snapshot.payloadBytes) !== BigInt(payloadBytes)) {
693
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot UTF-8 byte length does not match metadata.');
694
+ }
891
695
  }
892
- if (
893
- (await getSheetBootstrapPayloadChecksum(snapshot.payload)) !==
894
- snapshot.checksum
895
- ) {
896
- failSheetBootstrap(
897
- 'INVALID_SNAPSHOT',
898
- 'openSheet snapshot SHA-256 checksum verification failed.',
899
- );
696
+ const cellCount =
697
+ snapshot.cellCount === null || snapshot.cellCount === undefined
698
+ ? null
699
+ : requireSheetBootstrapCount(snapshot.cellCount, 'openSheet.snapshot.cellCount');
700
+ if ((await getSheetBootstrapPayloadChecksum(snapshot.payload)) !== snapshot.checksum) {
701
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot SHA-256 checksum verification failed.');
900
702
  }
901
703
 
902
704
  let data: ReturnType<typeof decodeSheetSnapshot>;
@@ -912,44 +714,34 @@ export async function decodeVerifiedSheetBootstrapSnapshot(params: {
912
714
  viewport,
913
715
  );
914
716
  } catch {
915
- return failSheetBootstrap(
916
- 'INVALID_SNAPSHOT',
917
- 'openSheet snapshot payload could not be decoded.',
918
- );
717
+ return failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot payload could not be decoded.');
919
718
  }
920
- if (data.cells.length !== cellCount) {
921
- failSheetBootstrap(
922
- 'INVALID_SNAPSHOT',
923
- 'openSheet snapshot decoded cell count does not match metadata.',
924
- );
719
+ if (cellCount !== null && data.cells.length !== cellCount) {
720
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot decoded cell count does not match metadata.');
925
721
  }
722
+ // Without a served viewport the image's own grid at its seq bounds it: the
723
+ // selected tab at currentSeq may have lost lines the tail deletes.
724
+ const scope: SheetBootstrapScope = {
725
+ ...params.scope,
726
+ viewport:
727
+ servedViewport ?? (data.sheetTab?.design?.grid ? getExpectedSheetBootstrapViewport(data.sheetTab as SheetTabGQL) : viewport),
728
+ };
926
729
 
927
730
  const cellCoordinates = new Set<string>();
731
+ const lastRowIndex = scope.viewport.startRowIndex + scope.viewport.rowCount - 1;
732
+ const lastColumnIndex = scope.viewport.startColumnIndex + scope.viewport.columnCount - 1;
928
733
  data.cells.forEach((cell, index) => {
929
- const key = validateSheetBootstrapCell(
930
- cell,
931
- params.scope,
932
- `snapshot.cells[${index}]`,
933
- );
734
+ // Fast accept; any failing cell reruns the full validator for its exact error
735
+ const key = isValidSheetBootstrapSnapshotCell(cell, scope, lastRowIndex, lastColumnIndex)
736
+ ? `${cell.rowIndex}:${cell.columnIndex}`
737
+ : validateSheetBootstrapCell(cell, scope, `snapshot.cells[${index}]`);
934
738
  if (cellCoordinates.has(key)) {
935
- failSheetBootstrap(
936
- 'INVALID_SNAPSHOT',
937
- 'openSheet snapshot contains duplicate cell coordinates.',
938
- );
739
+ failSheetBootstrap('INVALID_SNAPSHOT', 'openSheet snapshot contains duplicate cell coordinates.');
939
740
  }
940
741
  cellCoordinates.add(key);
941
742
  });
942
- data.ranges.forEach((range, index) => {
943
- validateSheetBootstrapRange(range, params.scope, index);
944
- });
945
- data.regions.forEach((region, index) => {
946
- validateSheetBootstrapRegion(region, params.scope, index);
947
- });
948
- requireSheetBootstrapRecord(
949
- data.pageInfo,
950
- 'snapshot.pageInfo',
951
- 'INVALID_SNAPSHOT',
952
- );
743
+
744
+ requireSheetBootstrapRecord(data.pageInfo, 'snapshot.pageInfo', 'INVALID_SNAPSHOT');
953
745
 
954
746
  return {
955
747
  seq,
@@ -960,78 +752,47 @@ export async function decodeVerifiedSheetBootstrapSnapshot(params: {
960
752
  }
961
753
 
962
754
  /*
963
- * Parse and validate one replayable hard-NEW v3 CELLS journal payload.
755
+ * Parse one journal row's JSON payload into a record, failing closed on a
756
+ * missing, non-string, malformed, or non-object payload.
964
757
  */
965
- function parseSheetBootstrapCellPatch(
966
- change: SheetTabChangeGQL,
967
- scope: SheetBootstrapScope,
968
- index: number,
969
- ): SheetBootstrapCellPatch {
758
+ function parseSheetBootstrapChangePayload(change: SheetTabChangeGQL, index: number): Record<string, any> {
970
759
  if (typeof change.payload !== 'string' || !change.payload) {
971
- return failSheetBootstrap(
972
- 'INVALID_CHANGE',
973
- `openSheet.changes[${index}].payload must be a JSON string.`,
974
- );
760
+ return failSheetBootstrap('INVALID_CHANGE', `openSheet.changes[${index}].payload must be a JSON string.`);
975
761
  }
976
762
 
977
- let payload: Record<string, any>;
978
763
  try {
979
- payload = requireSheetBootstrapRecord(
980
- JSON.parse(change.payload),
981
- `openSheet.changes[${index}].payload`,
982
- 'INVALID_CHANGE',
983
- );
764
+ return requireSheetBootstrapRecord(JSON.parse(change.payload), `openSheet.changes[${index}].payload`, 'INVALID_CHANGE');
984
765
  } catch (error) {
985
766
  if (error instanceof SheetBootstrapValidationError) {
986
767
  throw error;
987
768
  }
988
- return failSheetBootstrap(
989
- 'INVALID_CHANGE',
990
- `openSheet.changes[${index}].payload is invalid JSON.`,
991
- );
769
+ return failSheetBootstrap('INVALID_CHANGE', `openSheet.changes[${index}].payload is invalid JSON.`);
992
770
  }
771
+ }
993
772
 
994
- if (
995
- payload.v !== SHEET_CELLS_JOURNAL_VERSION ||
996
- !Array.isArray(payload.cells) ||
997
- !Array.isArray(payload.deletedCellCoords) ||
998
- !isHardNewSheetCellsJournalOrderedTargetGroups(
999
- payload.orderedTargetGroups,
1000
- ) ||
1001
- payload.truncated ||
1002
- payload.requiresSnapshot
1003
- ) {
1004
- failSheetBootstrap(
1005
- 'INVALID_CHANGE',
1006
- `openSheet.changes[${index}] is not a replayable CELLS payload.`,
1007
- );
1008
- }
773
+ /*
774
+ * Return the command id a journal row carries, or null for an anonymous row.
775
+ */
776
+ function getSheetBootstrapRowCommandId(change: SheetTabChangeGQL) {
777
+ return typeof change.commandId === 'string' && change.commandId ? change.commandId : null;
778
+ }
1009
779
 
780
+ /*
781
+ * Validate one row's cells and tombstones against the scope and return them
782
+ * typed; duplicate cell coordinates inside one row fail closed.
783
+ */
784
+ function validateSheetBootstrapRowCells(payload: Record<string, any>, scope: SheetBootstrapScope, index: number) {
1010
785
  const patchCoordinates = new Set<string>();
1011
786
  payload.cells.forEach((cell: unknown, cellIndex: number) => {
1012
- const key = validateSheetBootstrapCell(
1013
- cell,
1014
- scope,
1015
- `openSheet.changes[${index}].cells[${cellIndex}]`,
1016
- );
787
+ const key = validateSheetBootstrapCell(cell, scope, `openSheet.changes[${index}].cells[${cellIndex}]`);
1017
788
  if (patchCoordinates.has(key)) {
1018
- failSheetBootstrap(
1019
- 'INVALID_CHANGE',
1020
- `openSheet.changes[${index}] contains duplicate cell coordinates.`,
1021
- );
789
+ failSheetBootstrap('INVALID_CHANGE', `openSheet.changes[${index}] contains duplicate cell coordinates.`);
1022
790
  }
1023
791
  patchCoordinates.add(key);
1024
792
  });
1025
- payload.deletedCellCoords.forEach(
1026
- (coordinate: unknown, coordinateIndex: number) => {
1027
- validateSheetBootstrapDeletedCoordinate(
1028
- coordinate,
1029
- scope,
1030
- `openSheet.changes[${index}].deletedCellCoords[${coordinateIndex}]`,
1031
- );
1032
- },
1033
- );
1034
-
793
+ payload.deletedCellCoords.forEach((coordinate: unknown, coordinateIndex: number) => {
794
+ validateSheetBootstrapDeletedCoordinate(coordinate, scope, `openSheet.changes[${index}].deletedCellCoords[${coordinateIndex}]`);
795
+ });
1035
796
  return {
1036
797
  cells: payload.cells as SheetAuthoritativeCellGQL[],
1037
798
  deletedCellCoords: payload.deletedCellCoords as SheetDeletedCellCoordGQL[],
@@ -1039,530 +800,439 @@ function parseSheetBootstrapCellPatch(
1039
800
  }
1040
801
 
1041
802
  /*
1042
- * Validate a complete, contiguous, selected-tab-only CELLS journal tail.
803
+ * Validate one replayable v3 CELLS journal row and return its typed patch.
1043
804
  */
1044
- export function validateSheetBootstrapChanges(params: {
1045
- value: unknown;
1046
- afterSeq: SheetJournalSeq;
1047
- currentSeq: SheetJournalSeq;
1048
- scope: SheetBootstrapSnapshotScope;
1049
- }): SheetBootstrapCellPatch[] {
1050
- if (!Array.isArray(params.value)) {
1051
- return failSheetBootstrap(
1052
- 'INVALID_CHANGE',
1053
- 'openSheet.changes must be an array.',
1054
- );
805
+ function parseSheetBootstrapCellPatch(
806
+ change: SheetTabChangeGQL,
807
+ scope: SheetBootstrapScope,
808
+ index: number,
809
+ seq: SheetJournalSeq,
810
+ ): SheetBootstrapRowPatch {
811
+ const payload = parseSheetBootstrapChangePayload(change, index);
812
+ if (
813
+ payload.v !== SHEET_CELLS_JOURNAL_VERSION ||
814
+ !Array.isArray(payload.cells) ||
815
+ !Array.isArray(payload.deletedCellCoords) ||
816
+ !isHardNewSheetCellsJournalOrderedTargetGroups(payload.orderedTargetGroups) ||
817
+ payload.truncated ||
818
+ payload.requiresSnapshot
819
+ ) {
820
+ failSheetBootstrap('INVALID_CHANGE', `openSheet.changes[${index}] is not a replayable CELLS payload.`);
1055
821
  }
1056
- if (compareSheetJournalSeq(params.afterSeq, params.currentSeq) > 0) {
1057
- failSheetBootstrap(
1058
- 'INVALID_SEQUENCE',
1059
- 'openSheet replay base is ahead of currentSeq.',
1060
- );
822
+
823
+ return {
824
+ ...validateSheetBootstrapRowCells(payload, scope, index),
825
+ commandId: getSheetBootstrapRowCommandId(change),
826
+ computedCells: [],
827
+ kind: 'CELLS',
828
+ seq,
829
+ };
830
+ }
831
+
832
+ /*
833
+ * Validate one replayable v1 COMPUTED journal row and return its typed patch:
834
+ * every item must be an exact derived-fields-only item of the selected tab,
835
+ * inside the scope's grid, with no duplicate coordinates.
836
+ */
837
+ function parseSheetBootstrapComputedPatch(
838
+ change: SheetTabChangeGQL,
839
+ scope: SheetBootstrapScope,
840
+ index: number,
841
+ seq: SheetJournalSeq,
842
+ ): SheetBootstrapRowPatch {
843
+ const payload = parseSheetBootstrapChangePayload(change, index);
844
+ if (payload.v !== SHEET_COMPUTED_JOURNAL_VERSION || !Array.isArray(payload.cells) || payload.truncated || payload.requiresSnapshot) {
845
+ failSheetBootstrap('INVALID_CHANGE', `openSheet.changes[${index}] is not a replayable COMPUTED payload.`);
1061
846
  }
1062
847
 
1063
- let expectedSeq = BigInt(params.afterSeq) + 1n;
1064
- const patches = params.value.map((item, index) => {
1065
- const change = requireSheetBootstrapRecord(
1066
- item,
1067
- `openSheet.changes[${index}]`,
1068
- 'INVALID_CHANGE',
1069
- ) as SheetTabChangeGQL;
1070
- if (
1071
- requireSheetBootstrapId(
1072
- change.sheetTabId,
1073
- `openSheet.changes[${index}].sheetTabId`,
1074
- 'INVALID_CHANGE',
1075
- ) !== params.scope.sheetTabId ||
1076
- change.kind !== 'CELLS'
1077
- ) {
1078
- failSheetBootstrap(
1079
- 'SCOPE_MISMATCH',
1080
- `openSheet.changes[${index}] is not a selected-tab CELLS row.`,
1081
- );
848
+ const patchCoordinates = new Set<string>();
849
+ payload.cells.forEach((cell: unknown, cellIndex: number) => {
850
+ const label = `openSheet.changes[${index}].cells[${cellIndex}]`;
851
+ if (!isSheetComputedJournalCell(cell, scope.sheetTabId)) {
852
+ failSheetBootstrap('INVALID_CHANGE', `${label} is not an exact derived-fields-only cell of the selected tab.`);
1082
853
  }
1083
- const seq = requireSheetBootstrapSeq(
1084
- change.seq,
1085
- `openSheet.changes[${index}].seq`,
1086
- );
1087
- if (BigInt(seq) !== expectedSeq) {
1088
- failSheetBootstrap(
1089
- 'INVALID_SEQUENCE',
1090
- `openSheet changes are not contiguous after ${params.afterSeq}.`,
1091
- );
854
+ const coordinate = validateSheetBootstrapCoordinate(cell, scope, label);
855
+ const key = `${coordinate.rowIndex}:${coordinate.columnIndex}`;
856
+ if (patchCoordinates.has(key)) {
857
+ failSheetBootstrap('INVALID_CHANGE', `openSheet.changes[${index}] contains duplicate cell coordinates.`);
1092
858
  }
1093
- expectedSeq += 1n;
1094
-
1095
- return parseSheetBootstrapCellPatch(change, params.scope, index);
859
+ patchCoordinates.add(key);
1096
860
  });
1097
861
 
1098
- if (expectedSeq - 1n !== BigInt(params.currentSeq)) {
1099
- failSheetBootstrap(
1100
- 'INVALID_SEQUENCE',
1101
- 'openSheet changes do not end at currentSeq.',
1102
- );
1103
- }
1104
-
1105
- return patches;
862
+ return {
863
+ cells: [],
864
+ commandId: getSheetBootstrapRowCommandId(change),
865
+ computedCells: payload.cells as SheetComputedCellGQL[],
866
+ deletedCellCoords: [],
867
+ kind: 'COMPUTED',
868
+ seq,
869
+ };
1106
870
  }
1107
871
 
1108
872
  /*
1109
- * Return whether one incoming same-id cell is newer than the stored version.
873
+ * Return whether one unknown value is a positive safe integer grid index.
1110
874
  */
1111
- function sheetBootstrapCellShouldReplace(
1112
- existingCell: SheetCellGQL | undefined,
1113
- incomingCell: SheetCellGQL,
1114
- ): boolean {
1115
- if (!existingCell || String(existingCell.id) !== String(incomingCell.id)) {
1116
- return true;
1117
- }
1118
-
1119
- const existingRevision = parseSheetJournalSeq(existingCell.revision);
1120
- const incomingRevision = parseSheetJournalSeq(incomingCell.revision);
1121
- return (
1122
- !existingRevision ||
1123
- !incomingRevision ||
1124
- compareSheetJournalSeq(incomingRevision, existingRevision) > 0
1125
- );
875
+ function isSheetBootstrapGridIndex(value: unknown): value is number {
876
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
1126
877
  }
1127
878
 
1128
879
  /*
1129
- * Compare identifiers by Unicode code units without locale/ICU variability.
880
+ * Validate one replayable v2 DESIGN journal row and return its typed patch.
881
+ * The row applies from its full tab image; a rename or reorder row carries no
882
+ * design and only moves the revision. Ordering metadata is server-side state
883
+ * the replay does not consume, so it is not validated here.
1130
884
  */
1131
- function compareSheetBootstrapIds(left: unknown, right: unknown): number {
1132
- const leftId = String(left);
1133
- const rightId = String(right);
885
+ function parseSheetBootstrapDesignPatch(change: SheetTabChangeGQL, index: number, seq: SheetJournalSeq): SheetBootstrapRowPatch {
886
+ const label = `openSheet.changes[${index}]`;
887
+ const payload = parseSheetBootstrapChangePayload(change, index);
888
+ if (
889
+ payload.v !== SHEET_DESIGN_JOURNAL_VERSION ||
890
+ payload.truncated ||
891
+ payload.requiresSnapshot ||
892
+ !payload.tab ||
893
+ typeof payload.tab !== 'object' ||
894
+ Array.isArray(payload.tab)
895
+ ) {
896
+ failSheetBootstrap('INVALID_CHANGE', `${label} is not a replayable DESIGN payload.`);
897
+ }
898
+ const designRevision = requireSheetBootstrapSeq(payload.designRevision, `${label}.designRevision`, 'INVALID_CHANGE');
899
+ const tab = payload.tab as Record<string, unknown>;
900
+ if (String(tab.designRevision) !== designRevision) {
901
+ failSheetBootstrap('INVALID_CHANGE', `${label}.tab does not carry the row's design revision.`);
902
+ }
903
+ if (tab.design !== undefined && tab.design !== null && (typeof tab.design !== 'object' || Array.isArray(tab.design))) {
904
+ failSheetBootstrap('INVALID_CHANGE', `${label}.tab.design must be an object when present.`);
905
+ }
1134
906
 
1135
- return leftId < rightId ? -1 : leftId > rightId ? 1 : 0;
907
+ return {
908
+ cells: [],
909
+ commandId: getSheetBootstrapRowCommandId(change),
910
+ computedCells: [],
911
+ deletedCellCoords: [],
912
+ design: { designRevision, tab: { ...tab, designRevision } },
913
+ kind: 'DESIGN',
914
+ seq,
915
+ };
1136
916
  }
1137
917
 
1138
918
  /*
1139
- * Atomically replay validated journal patches into a fresh coordinate map.
919
+ * Validate the geometry of one axis move; its fit against the replayed grid
920
+ * is checked when it is applied.
1140
921
  */
1141
- function applySheetBootstrapCellPatches(
1142
- baseCells: SheetAuthoritativeCellGQL[],
1143
- patches: SheetBootstrapCellPatch[],
1144
- ): SheetAuthoritativeCellGQL[] {
1145
- const cellsByCoordinate = new Map(
1146
- baseCells.map((cell) => [`${cell.rowIndex}:${cell.columnIndex}`, cell]),
1147
- );
1148
-
1149
- patches.forEach((patch) => {
1150
- patch.cells.forEach((cell) => {
1151
- const key = `${cell.rowIndex}:${cell.columnIndex}`;
1152
- if (sheetBootstrapCellShouldReplace(cellsByCoordinate.get(key), cell)) {
1153
- cellsByCoordinate.set(key, cell);
1154
- }
1155
- });
1156
- patch.deletedCellCoords.forEach((coordinate) => {
1157
- const key = `${coordinate.rowIndex}:${coordinate.columnIndex}`;
1158
- const existingCell = cellsByCoordinate.get(key);
1159
- if (
1160
- existingCell &&
1161
- (!coordinate.id || String(existingCell.id) === String(coordinate.id))
1162
- ) {
1163
- cellsByCoordinate.delete(key);
1164
- }
1165
- });
1166
- });
922
+ function validateSheetBootstrapAxisMove(value: unknown, label: string): SheetAxisMoveInput {
923
+ const axisMove = requireSheetBootstrapRecord(value, label, 'INVALID_CHANGE');
924
+ if (
925
+ (axisMove.axis !== 'ROW' && axisMove.axis !== 'COLUMN') ||
926
+ !isSheetBootstrapGridIndex(axisMove.sourceStartIndex) ||
927
+ !isSheetBootstrapGridIndex(axisMove.sourceEndIndex) ||
928
+ !isSheetBootstrapGridIndex(axisMove.targetStartIndex)
929
+ ) {
930
+ failSheetBootstrap('INVALID_CHANGE', `${label} is not a row or column move.`);
931
+ }
1167
932
 
1168
- return [...cellsByCoordinate.values()].sort(
1169
- (left, right) =>
1170
- Number(left.rowIndex) - Number(right.rowIndex) ||
1171
- Number(left.columnIndex) - Number(right.columnIndex) ||
1172
- compareSheetBootstrapIds(left.id, right.id),
1173
- );
933
+ return {
934
+ axis: axisMove.axis,
935
+ sourceEndIndex: axisMove.sourceEndIndex,
936
+ sourceStartIndex: axisMove.sourceStartIndex,
937
+ targetStartIndex: axisMove.targetStartIndex,
938
+ };
1174
939
  }
1175
940
 
1176
941
  /*
1177
- * Validate a reusable decoded state before using it as a DELTA replay base.
942
+ * Validate one replayable v2 STRUCTURE journal row and return its typed patch.
943
+ * A row that restored state its op cannot express (`requiresSnapshot: true`,
944
+ * a structure undo re-inserting a deleted axis) fails closed so the caller
945
+ * falls back to a snapshot; the server excludes such rows from replayable
946
+ * tails already. `opOnly` reads a topology row (S-4) for its op alone, which
947
+ * stands whether or not the row itself replays.
1178
948
  */
1179
- function validateCurrentSheetBootstrapState(
1180
- state: SheetBootstrapTabState,
1181
- scope: SheetBootstrapScope,
1182
- ): void {
949
+ function parseSheetBootstrapStructurePatch(
950
+ change: SheetTabChangeGQL,
951
+ index: number,
952
+ seq: SheetJournalSeq,
953
+ opOnly = false,
954
+ ): SheetBootstrapRowPatch {
955
+ const label = `openSheet.changes[${index}]`;
956
+ const payload = parseSheetBootstrapChangePayload(change, index);
1183
957
  if (
1184
- state.organizationId !== scope.organizationId ||
1185
- state.sheetId !== scope.sheetId ||
1186
- state.sheetTabId !== scope.sheetTabId ||
1187
- state.baseSnapshot.organizationId !== scope.organizationId ||
1188
- state.baseSnapshot.sheetId !== scope.sheetId ||
1189
- state.baseSnapshot.sheetTabId !== scope.sheetTabId
958
+ payload.v !== SHEET_STRUCTURE_JOURNAL_VERSION ||
959
+ (payload.truncated && !opOnly) ||
960
+ !payload.structureOp ||
961
+ typeof payload.structureOp !== 'object' ||
962
+ Array.isArray(payload.structureOp)
1190
963
  ) {
1191
- failSheetBootstrap(
1192
- 'SCOPE_MISMATCH',
1193
- 'Cached bootstrap state belongs to a different sheet scope.',
1194
- );
964
+ failSheetBootstrap('INVALID_CHANGE', `${label} is not a replayable STRUCTURE payload.`);
1195
965
  }
1196
- const appliedSeq = requireSheetBootstrapSeq(
1197
- state.appliedSeq,
1198
- 'cached bootstrap appliedSeq',
1199
- );
1200
- const baseSeq = requireSheetBootstrapSeq(
1201
- state.baseSnapshot.seq,
1202
- 'cached bootstrap baseSnapshot.seq',
1203
- );
1204
- if (
1205
- compareSheetJournalSeq(baseSeq, appliedSeq) > 0 ||
1206
- !isSupportedSheetSnapshotEncodingVersion(
1207
- state.baseSnapshot.encodingVersion,
1208
- ) ||
1209
- !FILE_CONSTANTS.checksumPattern.test(state.baseSnapshot.checksum)
1210
- ) {
1211
- failSheetBootstrap(
1212
- 'INVALID_SNAPSHOT',
1213
- 'Cached bootstrap base snapshot identity is invalid.',
1214
- );
966
+ if (payload.requiresSnapshot && !opOnly) {
967
+ failSheetBootstrap('INVALID_CHANGE', `${label} restored state its structure op cannot express and demands a snapshot.`);
1215
968
  }
1216
- requireMatchingSheetBootstrapViewport(
1217
- state.baseSnapshot.viewport as SheetGridViewportObj,
1218
- scope.viewport,
1219
- 'Cached bootstrap viewport',
1220
- );
969
+ const baseDesignRevision = requireSheetBootstrapSeq(payload.baseDesignRevision, `${label}.baseDesignRevision`, 'INVALID_CHANGE');
970
+ const designRevision = requireSheetBootstrapSeq(payload.designRevision, `${label}.designRevision`, 'INVALID_CHANGE');
971
+
972
+ const structureOp = payload.structureOp as Record<string, unknown>;
1221
973
  if (
1222
- state.view.sheetId !== scope.sheetId ||
1223
- state.view.sheetTabId !== scope.sheetTabId ||
1224
- requireSheetBootstrapSeq(
1225
- state.view.cellsRevision,
1226
- 'cached bootstrap view.cellsRevision',
1227
- ) !== appliedSeq ||
1228
- !Array.isArray(state.view.cells) ||
1229
- !Array.isArray(state.view.ranges) ||
1230
- !Array.isArray(state.view.regions) ||
1231
- !state.view.pageInfo
974
+ requireSheetBootstrapSeq(structureOp.structureSeq, `${label}.structureOp.structureSeq`, 'INVALID_CHANGE') !== seq ||
975
+ (structureOp.opId !== null && (typeof structureOp.opId !== 'string' || !structureOp.opId))
1232
976
  ) {
1233
- failSheetBootstrap(
1234
- 'INVALID_RESPONSE',
1235
- 'Cached bootstrap view is incomplete or inconsistent.',
1236
- );
977
+ failSheetBootstrap('INVALID_CHANGE', `${label}.structureOp does not describe this row.`);
978
+ }
979
+ const patch = {
980
+ baseDesignRevision,
981
+
982
+ designRevision,
983
+ opId: structureOp.opId === null ? null : String(structureOp.opId),
984
+ seq,
985
+ };
986
+ const row = {
987
+ cells: [],
988
+ commandId: getSheetBootstrapRowCommandId(change) ?? patch.opId,
989
+ computedCells: [],
990
+ deletedCellCoords: [],
991
+ kind: 'STRUCTURE' as const,
992
+ seq,
993
+ };
994
+ if (structureOp.kind === 'INSERT_DELETE') {
995
+ const operation = structureOp.operation as SheetStructureOperationEnum;
996
+ if (!SHEET_STRUCTURE_OPERATION_ENUMS.includes(operation) || !isSheetBootstrapGridIndex(structureOp.index)) {
997
+ failSheetBootstrap('INVALID_CHANGE', `${label}.structureOp is not a row or column insert/delete.`);
998
+ }
999
+ return {
1000
+ ...row,
1001
+ structureOp: {
1002
+ ...patch,
1003
+ op: { kind: 'INSERT_DELETE', operation, index: structureOp.index },
1004
+ },
1005
+ };
1237
1006
  }
1238
- const viewDesignRevision = requireSheetBootstrapSeq(
1239
- state.view.designRevision,
1240
- 'cached bootstrap view.designRevision',
1241
- );
1242
1007
  if (
1243
- requireSheetBootstrapId(state.view.id, 'cached bootstrap view.id') !==
1244
- scope.sheetTabId
1008
+ structureOp.kind !== 'AXIS_MOVE' ||
1009
+ structureOp.operation !== 'MOVE_AXIS' ||
1010
+ !Array.isArray(payload.axisMoveOps) ||
1011
+ !payload.axisMoveOps.length
1245
1012
  ) {
1246
- failSheetBootstrap(
1247
- 'SCOPE_MISMATCH',
1248
- 'Cached bootstrap view id does not match its tab scope.',
1249
- );
1013
+ failSheetBootstrap('INVALID_CHANGE', `${label}.structureOp is not a known structure op.`);
1250
1014
  }
1251
- const sheetTab = requireSheetBootstrapRecord(
1252
- state.view.sheetTab,
1253
- 'cached bootstrap view.sheetTab',
1254
- );
1255
- const sheetTabDesignRevision = requireSheetBootstrapSeq(
1256
- sheetTab.designRevision,
1257
- 'cached bootstrap view.sheetTab.designRevision',
1258
- );
1259
- if (sheetTabDesignRevision !== viewDesignRevision) {
1260
- failSheetBootstrap(
1261
- 'INVALID_SEQUENCE',
1262
- 'Cached bootstrap design revisions do not agree.',
1263
- );
1015
+
1016
+ return {
1017
+ ...row,
1018
+ structureOp: {
1019
+ ...patch,
1020
+ op: {
1021
+ kind: 'AXIS_MOVE',
1022
+ axisMoveOps: payload.axisMoveOps.map((op: unknown, opIndex: number) =>
1023
+ validateSheetBootstrapAxisMove(op, `${label}.axisMoveOps[${opIndex}]`),
1024
+ ),
1025
+ },
1026
+ },
1027
+ };
1028
+ }
1029
+
1030
+ /*
1031
+ * Validate a complete, contiguous, selected-tab-only journal tail of
1032
+ * replayable CELLS / COMPUTED / DESIGN / STRUCTURE / REGION (v2) rows and
1033
+ * return one typed patch per row in seq order. Design revisions and topology
1034
+ * are applied by the client's tab reducer, which knows the state the tail
1035
+ * replays over.
1036
+ */
1037
+ export function validateSheetBootstrapChanges(params: {
1038
+ value: unknown;
1039
+ afterSeq: SheetJournalSeq;
1040
+ currentSeq: SheetJournalSeq;
1041
+ scope: SheetBootstrapSnapshotScope;
1042
+ }): SheetBootstrapRowPatch[] {
1043
+ if (!Array.isArray(params.value)) {
1044
+ return failSheetBootstrap('INVALID_CHANGE', 'openSheet.changes must be an array.');
1264
1045
  }
1265
- if (
1266
- requireSheetBootstrapId(
1267
- sheetTab.id,
1268
- 'cached bootstrap view.sheetTab.id',
1269
- ) !== scope.sheetTabId ||
1270
- requireSheetBootstrapId(
1271
- sheetTab.organizationId,
1272
- 'cached bootstrap view.sheetTab.organizationId',
1273
- ) !== scope.organizationId ||
1274
- requireSheetBootstrapId(
1275
- sheetTab.sheetId,
1276
- 'cached bootstrap view.sheetTab.sheetId',
1277
- ) !== scope.sheetId
1278
- ) {
1279
- failSheetBootstrap(
1280
- 'SCOPE_MISMATCH',
1281
- 'Cached bootstrap tab belongs to a different sheet scope.',
1282
- );
1046
+ if (compareSheetJournalSeq(params.afterSeq, params.currentSeq) > 0) {
1047
+ failSheetBootstrap('INVALID_SEQUENCE', 'openSheet replay base is ahead of currentSeq.');
1283
1048
  }
1284
1049
 
1285
- const cellCoordinates = new Set<string>();
1286
- (state.view.cells || []).forEach((cell, index) => {
1287
- const key = validateSheetBootstrapCell(
1288
- cell,
1289
- scope,
1290
- `cached bootstrap cells[${index}]`,
1291
- );
1292
- if (cellCoordinates.has(key)) {
1050
+ let expectedSeq = BigInt(params.afterSeq) + 1n;
1051
+ const patches = params.value.map((item, index) => {
1052
+ const change = requireSheetBootstrapRecord(item, `openSheet.changes[${index}]`, 'INVALID_CHANGE') as SheetTabChangeGQL;
1053
+ if (
1054
+ requireSheetBootstrapId(change.sheetTabId, `openSheet.changes[${index}].sheetTabId`, 'INVALID_CHANGE') !==
1055
+ params.scope.sheetTabId ||
1056
+ (change.kind !== 'CELLS' && change.kind !== 'COMPUTED' && change.kind !== 'DESIGN' && change.kind !== 'STRUCTURE')
1057
+ ) {
1293
1058
  failSheetBootstrap(
1294
- 'INVALID_RESPONSE',
1295
- 'Cached bootstrap view contains duplicate cell coordinates.',
1059
+ 'SCOPE_MISMATCH',
1060
+ `openSheet.changes[${index}] is not a selected-tab CELLS, COMPUTED, DESIGN, or STRUCTURE row.`,
1296
1061
  );
1297
1062
  }
1298
- cellCoordinates.add(key);
1299
- });
1300
- (state.view.ranges || []).forEach((range, index) => {
1301
- validateSheetBootstrapRange(range, scope, index);
1302
- });
1303
- (state.view.regions || []).forEach((region, index) => {
1304
- validateSheetBootstrapRegion(region, scope, index);
1063
+ const seq = requireSheetBootstrapSeq(change.seq, `openSheet.changes[${index}].seq`);
1064
+ if (BigInt(seq) !== expectedSeq) {
1065
+ failSheetBootstrap('INVALID_SEQUENCE', `openSheet changes are not contiguous after ${params.afterSeq}.`);
1066
+ }
1067
+ expectedSeq += 1n;
1068
+
1069
+ switch (change.kind) {
1070
+ case 'COMPUTED':
1071
+ return parseSheetBootstrapComputedPatch(change, params.scope, index, seq);
1072
+ case 'DESIGN':
1073
+ return parseSheetBootstrapDesignPatch(change, index, seq);
1074
+ case 'STRUCTURE':
1075
+ return parseSheetBootstrapStructurePatch(change, index, seq);
1076
+
1077
+ default:
1078
+ return parseSheetBootstrapCellPatch(change, params.scope, index, seq);
1079
+ }
1305
1080
  });
1306
- requireSheetBootstrapRecord(
1307
- state.view.pageInfo,
1308
- 'cached bootstrap view.pageInfo',
1309
- 'INVALID_RESPONSE',
1310
- );
1081
+
1082
+ if (expectedSeq - 1n !== BigInt(params.currentSeq)) {
1083
+ failSheetBootstrap('INVALID_SEQUENCE', 'openSheet changes do not end at currentSeq.');
1084
+ }
1085
+
1086
+ return patches;
1311
1087
  }
1312
1088
 
1313
1089
  /*
1314
- * Build one SheetView-compatible value without mutating its decoded base.
1090
+ * Validate the topology rows (S-4) of one SNAPSHOT answer to a request with
1091
+ * `afterSeq`: STRUCTURE rows of the selected tab, in strictly increasing seq
1092
+ * order within (afterSeq, throughSeq], each read for its op. Null when the
1093
+ * request sent no applied seq or the answer carries no verdict. A set the
1094
+ * server marked incomplete, or one that fails validation, is returned empty
1095
+ * and incomplete: the client fails its pending work closed, as without it.
1315
1096
  */
1316
- function buildSheetBootstrapView(params: {
1317
- baseView?: SheetViewGQL | null;
1318
- decodedView?: ReturnType<typeof decodeSheetSnapshot> | null;
1319
- selectedTab: SheetTabGQL;
1320
- currentSeq: SheetJournalSeq;
1321
- cells: SheetAuthoritativeCellGQL[];
1322
- }): SheetViewGQL {
1323
- const source = params.baseView || params.decodedView;
1324
- if (!source) {
1325
- return failSheetBootstrap(
1326
- 'INVALID_RESPONSE',
1327
- 'No SheetView-compatible replay base was provided.',
1328
- );
1097
+ export function validateSheetBootstrapTopology(params: {
1098
+ afterSeq: SheetJournalSeq | null;
1099
+ complete: unknown;
1100
+ sheetTabId: string;
1101
+ throughSeq: SheetJournalSeq;
1102
+ value: unknown;
1103
+ }): SheetBootstrapTopology | null {
1104
+ const { afterSeq } = params;
1105
+ if (!afterSeq || typeof params.complete !== 'boolean') {
1106
+ return null;
1329
1107
  }
1330
- const sheetTabId = requireSheetBootstrapId(
1331
- params.selectedTab.id,
1332
- 'selected tab id',
1333
- );
1334
- const sheetId = requireSheetBootstrapId(
1335
- params.selectedTab.sheetId,
1336
- 'selected tab sheetId',
1337
- );
1338
- const designRevision = requireSheetBootstrapSeq(
1339
- params.selectedTab.designRevision,
1340
- 'selected tab designRevision',
1341
- );
1342
-
1343
- return {
1344
- ...(source as SheetViewGQL),
1345
- id: sheetTabId,
1346
- sheetId,
1347
- sheetTabId,
1348
- cellsRevision: params.currentSeq,
1349
- designRevision,
1350
- fromSeq: null,
1351
- toSeq: null,
1352
- requiresSnapshot: false,
1353
- sheetTab: {
1354
- ...(source.sheetTab || {}),
1355
- ...params.selectedTab,
1356
- cellsRevision: params.currentSeq,
1357
- designRevision,
1358
- },
1359
- cells: params.cells,
1360
- ranges: [...(source.ranges || [])],
1361
- regions: [...(source.regions || [])] as SheetAuthoritativeRegionGQL[],
1362
- pageInfo: source.pageInfo ? { ...source.pageInfo } : null,
1108
+ const incomplete: SheetBootstrapTopology = {
1109
+ afterSeq,
1110
+ complete: false,
1111
+ rows: [],
1363
1112
  };
1113
+ if (!params.complete || !Array.isArray(params.value)) {
1114
+ return incomplete;
1115
+ }
1116
+ try {
1117
+ let previousSeq = afterSeq;
1118
+ const rows = params.value.map((item, index) => {
1119
+ const change = requireSheetBootstrapRecord(item, `openSheet.topologyChanges[${index}]`, 'INVALID_CHANGE') as SheetTabChangeGQL;
1120
+ const seq = requireSheetBootstrapSeq(change.seq, `openSheet.topologyChanges[${index}].seq`, 'INVALID_CHANGE');
1121
+ if (
1122
+ change.kind !== 'STRUCTURE' ||
1123
+ requireSheetBootstrapId(change.sheetTabId, `openSheet.topologyChanges[${index}].sheetTabId`, 'INVALID_CHANGE') !==
1124
+ params.sheetTabId ||
1125
+ compareSheetJournalSeq(seq, previousSeq) <= 0 ||
1126
+ compareSheetJournalSeq(seq, params.throughSeq) > 0
1127
+ ) {
1128
+ failSheetBootstrap(
1129
+ 'INVALID_CHANGE',
1130
+ `openSheet.topologyChanges[${index}] is not an ordered STRUCTURE row of the image's gap.`,
1131
+ );
1132
+ }
1133
+ previousSeq = seq;
1134
+ return parseSheetBootstrapStructurePatch(change, index, seq, true);
1135
+ });
1136
+ return { afterSeq, complete: true, rows };
1137
+ } catch (error) {
1138
+ if (error instanceof SheetBootstrapValidationError) {
1139
+ return incomplete;
1140
+ }
1141
+ throw error;
1142
+ }
1364
1143
  }
1365
1144
 
1366
1145
  /*
1367
- * Freeze the immutable identity used for every future delta negotiation.
1146
+ * Return the replay scope's grid: the full-tab viewport widened to the grid
1147
+ * caps, so a tail row written before a later row shrank the grid still
1148
+ * validates (the reducer, not the validator, owns geometry).
1368
1149
  */
1369
- function createSheetBootstrapBaseSnapshotIdentity(params: {
1370
- scope: SheetBootstrapScope;
1371
- seq: SheetJournalSeq;
1372
- encodingVersion: number;
1373
- checksum: string;
1374
- }): SheetBootstrapBaseSnapshotIdentity {
1375
- const viewport = Object.freeze({ ...params.scope.viewport });
1376
-
1377
- return Object.freeze({
1378
- organizationId: params.scope.organizationId,
1379
- sheetId: params.scope.sheetId,
1380
- sheetTabId: params.scope.sheetTabId,
1381
- seq: params.seq,
1382
- encodingVersion: params.encodingVersion,
1383
- checksum: params.checksum,
1384
- viewport,
1385
- });
1150
+ function getSheetBootstrapReplayScope(scope: SheetBootstrapScope): SheetBootstrapScope {
1151
+ return {
1152
+ ...scope,
1153
+ viewport: {
1154
+ columnCount: Math.max(scope.viewport.columnCount, SHEET_MAX_COLUMN_COUNT),
1155
+ rowCount: Math.max(scope.viewport.rowCount, SHEET_MAX_ROW_COUNT),
1156
+ startColumnIndex: 1,
1157
+ startRowIndex: 1,
1158
+ },
1159
+ };
1386
1160
  }
1387
1161
 
1388
1162
  /*
1389
- * Apply a validated SNAPSHOT response and its complete journal tail.
1163
+ * Apply a validated SNAPSHOT response: decode and verify the snapshot image,
1164
+ * then validate the tail after its seq. The client's tab reducer installs the
1165
+ * image and replays the tail rows.
1390
1166
  */
1391
1167
  async function applySnapshotSheetBootstrap(params: {
1392
1168
  bootstrap: SheetBootstrapGQL;
1393
- selectedTab: SheetTabGQL;
1394
1169
  currentSeq: SheetJournalSeq;
1395
1170
  scope: SheetBootstrapScope;
1396
- }): Promise<SheetBootstrapTabState> {
1171
+ selectedTab: SheetTabGQL;
1172
+ }): Promise<{ image: SheetBootstrapTabImage; rows: SheetBootstrapRowPatch[] }> {
1397
1173
  const snapshot = await decodeVerifiedSheetBootstrapSnapshot({
1398
1174
  snapshot: params.bootstrap.snapshot,
1399
1175
  currentSeq: params.currentSeq,
1400
1176
  scope: params.scope,
1401
1177
  });
1402
- if (
1403
- requireSheetBootstrapSeq(
1404
- snapshot.data.sheetTab.designRevision,
1405
- 'snapshot.sheetTab.designRevision',
1406
- ) !==
1407
- requireSheetBootstrapSeq(
1408
- params.selectedTab.designRevision,
1409
- 'openSheet.selectedTab.designRevision',
1410
- )
1411
- ) {
1412
- failSheetBootstrap(
1413
- 'INVALID_SEQUENCE',
1414
- 'Snapshot and selected-tab design revisions do not agree.',
1415
- );
1416
- }
1417
- const patches = validateSheetBootstrapChanges({
1178
+ const rows = validateSheetBootstrapChanges({
1418
1179
  value: params.bootstrap.changes,
1419
1180
  afterSeq: snapshot.seq,
1420
1181
  currentSeq: params.currentSeq,
1421
- scope: params.scope,
1422
- });
1423
- const cells = applySheetBootstrapCellPatches(
1424
- snapshot.data.cells as SheetAuthoritativeCellGQL[],
1425
- patches,
1426
- );
1427
- const baseSnapshot = createSheetBootstrapBaseSnapshotIdentity({
1428
- scope: params.scope,
1429
- seq: snapshot.seq,
1430
- encodingVersion: snapshot.encodingVersion,
1431
- checksum: snapshot.checksum,
1432
- });
1433
-
1434
- return {
1435
- organizationId: params.scope.organizationId,
1436
- sheetId: params.scope.sheetId,
1437
- sheetTabId: params.scope.sheetTabId,
1438
- baseSnapshot,
1439
- appliedSeq: params.currentSeq,
1440
- view: buildSheetBootstrapView({
1441
- decodedView: snapshot.data,
1442
- selectedTab: params.selectedTab,
1443
- currentSeq: params.currentSeq,
1444
- cells,
1445
- }),
1446
- };
1447
- }
1448
-
1449
- /*
1450
- * Apply a validated DELTA response while retaining the exact base identity.
1451
- */
1452
- function applyDeltaSheetBootstrap(params: {
1453
- bootstrap: SheetBootstrapGQL;
1454
- selectedTab: SheetTabGQL;
1455
- currentSeq: SheetJournalSeq;
1456
- scope: SheetBootstrapScope;
1457
- currentState: SheetBootstrapTabState | null | undefined;
1458
- }): SheetBootstrapTabState {
1459
- if (!params.currentState) {
1460
- return failSheetBootstrap(
1461
- 'INVALID_RESPONSE',
1462
- 'openSheet DELTA requires a decoded local base state.',
1463
- );
1464
- }
1465
- if (
1466
- params.bootstrap.snapshot !== null &&
1467
- params.bootstrap.snapshot !== undefined
1468
- ) {
1469
- failSheetBootstrap(
1470
- 'INVALID_RESPONSE',
1471
- 'openSheet DELTA must not include a replacement snapshot.',
1472
- );
1473
- }
1474
- validateCurrentSheetBootstrapState(params.currentState, params.scope);
1475
- if (
1476
- requireSheetBootstrapSeq(
1477
- params.currentState.view.designRevision,
1478
- 'cached bootstrap view.designRevision',
1479
- ) !==
1480
- requireSheetBootstrapSeq(
1481
- params.selectedTab.designRevision,
1482
- 'openSheet.selectedTab.designRevision',
1483
- )
1484
- ) {
1485
- failSheetBootstrap(
1486
- 'INVALID_SEQUENCE',
1487
- 'Cached and selected-tab design revisions do not agree.',
1488
- );
1489
- }
1490
- const patches = validateSheetBootstrapChanges({
1491
- value: params.bootstrap.changes,
1492
- afterSeq: params.currentState.appliedSeq,
1493
- currentSeq: params.currentSeq,
1494
- scope: params.scope,
1182
+ scope: getSheetBootstrapReplayScope(params.scope),
1495
1183
  });
1496
- const cells = applySheetBootstrapCellPatches(
1497
- params.currentState.view.cells || [],
1498
- patches,
1499
- );
1184
+ const snapshotTab = snapshot.data.sheetTab;
1185
+ requireSheetBootstrapSeq(snapshotTab.designRevision, 'snapshot.sheetTab.designRevision');
1500
1186
 
1501
1187
  return {
1502
- organizationId: params.scope.organizationId,
1503
- sheetId: params.scope.sheetId,
1504
- sheetTabId: params.scope.sheetTabId,
1505
- baseSnapshot: params.currentState.baseSnapshot,
1506
- appliedSeq: params.currentSeq,
1507
- view: buildSheetBootstrapView({
1508
- baseView: params.currentState.view,
1509
- selectedTab: params.selectedTab,
1510
- currentSeq: params.currentSeq,
1511
- cells,
1512
- }),
1188
+ image: {
1189
+ cells: snapshot.data.cells as SheetAuthoritativeCellGQL[],
1190
+ organizationId: params.scope.organizationId,
1191
+ pageInfo: snapshot.data.pageInfo ? { ...snapshot.data.pageInfo } : null,
1192
+
1193
+ seq: snapshot.seq,
1194
+ sheetId: params.scope.sheetId,
1195
+ sheetTab: {
1196
+ ...params.selectedTab,
1197
+ ...snapshotTab,
1198
+ cellsRevision: snapshot.seq,
1199
+ designRevision: String(snapshotTab.designRevision),
1200
+ } as SheetTabGQL,
1201
+ sheetTabId: params.scope.sheetTabId,
1202
+ },
1203
+ rows,
1513
1204
  };
1514
1205
  }
1515
1206
 
1516
1207
  /*
1517
- * Validate and atomically apply one access-aware openSheet response.
1208
+ * Validate and atomically decode one access-aware openSheet / syncSheetTab
1209
+ * response (contract 4). A DELTA carries the rows after the caller's
1210
+ * `sinceSeq` (the client's live applied seq, DESIGN §0 D10) and no image; a
1211
+ * SNAPSHOT carries the decoded image and its tail. Nothing here merges into
1212
+ * client state: the tab reducer applies the image and rows.
1518
1213
  */
1519
1214
  export async function applySheetBootstrap(params: {
1520
1215
  bootstrap: unknown;
1521
1216
  expectedSheetId: string;
1522
- currentState?: SheetBootstrapTabState | null;
1217
+ /* The applied seq the request was negotiated from (DELTA base). */
1218
+ sinceSeq?: SheetJournalSeq | null;
1523
1219
  }): Promise<SheetBootstrapApplyResult> {
1524
- const expectedSheetId = requireSheetBootstrapId(
1525
- params.expectedSheetId,
1526
- 'expectedSheetId',
1527
- 'INVALID_RESPONSE',
1528
- );
1529
- const bootstrap = requireSheetBootstrapRecord(
1530
- params.bootstrap,
1531
- 'openSheet',
1532
- ) as SheetBootstrapGQL;
1220
+ const expectedSheetId = requireSheetBootstrapId(params.expectedSheetId, 'expectedSheetId', 'INVALID_RESPONSE');
1221
+ const bootstrap = requireSheetBootstrapRecord(params.bootstrap, 'openSheet') as SheetBootstrapGQL;
1533
1222
  const contract = validateSheetBootstrapContract(bootstrap);
1534
- const access = validateSheetBootstrapAccess(
1535
- bootstrap.access,
1536
- expectedSheetId,
1537
- );
1223
+ const access = validateSheetBootstrapAccess(bootstrap.access, expectedSheetId);
1538
1224
  if (!access.canView) {
1539
1225
  if (bootstrap.status === 'DENIED') {
1540
- if (
1541
- bootstrap.unavailableReason ||
1542
- sheetBootstrapHasScopedReadData(bootstrap)
1543
- ) {
1544
- failSheetBootstrap(
1545
- 'INVALID_ACCESS',
1546
- 'Denied openSheet response exposed scoped workbook data.',
1547
- );
1226
+ if (bootstrap.unavailableReason || sheetBootstrapHasScopedReadData(bootstrap)) {
1227
+ failSheetBootstrap('INVALID_ACCESS', 'Denied openSheet response exposed scoped workbook data.');
1548
1228
  }
1549
1229
  return { ...contract, status: 'DENIED', access };
1550
1230
  }
1551
- if (
1552
- bootstrap.status !== 'RETRY' ||
1553
- typeof bootstrap.unavailableReason !== 'string' ||
1554
- !bootstrap.unavailableReason.trim()
1555
- ) {
1556
- failSheetBootstrap(
1557
- 'INVALID_STATUS',
1558
- 'Denied openSheet responses require DENIED or an explicit RETRY status.',
1559
- );
1231
+ if (bootstrap.status !== 'RETRY' || typeof bootstrap.unavailableReason !== 'string' || !bootstrap.unavailableReason.trim()) {
1232
+ failSheetBootstrap('INVALID_STATUS', 'Denied openSheet responses require DENIED or an explicit RETRY status.');
1560
1233
  }
1561
1234
  if (sheetBootstrapHasScopedReadData(bootstrap)) {
1562
- failSheetBootstrap(
1563
- 'INVALID_ACCESS',
1564
- 'Denied openSheet retry exposed scoped workbook data.',
1565
- );
1235
+ failSheetBootstrap('INVALID_ACCESS', 'Denied openSheet retry exposed scoped workbook data.');
1566
1236
  }
1567
1237
  return {
1568
1238
  ...contract,
@@ -1572,57 +1242,24 @@ export async function applySheetBootstrap(params: {
1572
1242
  sheet: null,
1573
1243
  tabs: [],
1574
1244
  selectedTab: null,
1575
- referencedDataTables: [],
1576
1245
  };
1577
1246
  }
1578
1247
 
1579
- if (
1580
- bootstrap.status !== 'READY' &&
1581
- bootstrap.status !== 'RETRY' &&
1582
- bootstrap.status !== 'UNAVAILABLE'
1583
- ) {
1584
- return failSheetBootstrap(
1585
- 'INVALID_STATUS',
1586
- 'openSheet returned an unknown or missing status.',
1587
- );
1248
+ if (bootstrap.status !== 'READY' && bootstrap.status !== 'RETRY' && bootstrap.status !== 'UNAVAILABLE') {
1249
+ return failSheetBootstrap('INVALID_STATUS', 'openSheet returned an unknown or missing status.');
1588
1250
  }
1589
1251
  if (bootstrap.status !== 'READY') {
1590
- if (
1591
- bootstrap.realtimeToken !== null &&
1592
- bootstrap.realtimeToken !== undefined
1593
- ) {
1594
- failSheetBootstrap(
1595
- 'INVALID_ACCESS',
1596
- 'Non-ready openSheet responses cannot carry a realtime capability.',
1597
- );
1252
+ if (bootstrap.realtimeToken !== null && bootstrap.realtimeToken !== undefined) {
1253
+ failSheetBootstrap('INVALID_ACCESS', 'Non-ready openSheet responses cannot carry a realtime capability.');
1598
1254
  }
1599
- if (
1600
- typeof bootstrap.unavailableReason !== 'string' ||
1601
- !bootstrap.unavailableReason.trim()
1602
- ) {
1603
- failSheetBootstrap(
1604
- 'INVALID_STATUS',
1605
- 'Non-ready openSheet responses require an unavailable reason.',
1606
- );
1255
+ if (typeof bootstrap.unavailableReason !== 'string' || !bootstrap.unavailableReason.trim()) {
1256
+ failSheetBootstrap('INVALID_STATUS', 'Non-ready openSheet responses require an unavailable reason.');
1607
1257
  }
1608
1258
  const sheet =
1609
- bootstrap.sheet === null || bootstrap.sheet === undefined
1610
- ? null
1611
- : validateSheetBootstrapWorkbook(bootstrap.sheet, access);
1612
- const tabs =
1613
- bootstrap.tabs === null || bootstrap.tabs === undefined
1614
- ? []
1615
- : validateSheetBootstrapTabSummaries(bootstrap.tabs);
1616
- const selectedTab = bootstrap.selectedTab
1617
- ? validateSelectedSheetBootstrapTab(bootstrap.selectedTab, access, tabs)
1618
- : null;
1619
- const referencedDataTables =
1620
- bootstrap.referencedDataTables === null ||
1621
- bootstrap.referencedDataTables === undefined
1622
- ? []
1623
- : validateSheetBootstrapReferencedTables(
1624
- bootstrap.referencedDataTables,
1625
- );
1259
+ bootstrap.sheet === null || bootstrap.sheet === undefined ? null : validateSheetBootstrapWorkbook(bootstrap.sheet, access);
1260
+ const tabs = bootstrap.tabs === null || bootstrap.tabs === undefined ? [] : validateSheetBootstrapTabSummaries(bootstrap.tabs);
1261
+ const selectedTab = bootstrap.selectedTab ? validateSelectedSheetBootstrapTab(bootstrap.selectedTab, access, tabs) : null;
1262
+
1626
1263
  return {
1627
1264
  ...contract,
1628
1265
  status: bootstrap.status,
@@ -1631,60 +1268,43 @@ export async function applySheetBootstrap(params: {
1631
1268
  sheet,
1632
1269
  tabs,
1633
1270
  selectedTab,
1634
- referencedDataTables,
1635
1271
  };
1636
1272
  }
1637
- const realtimeToken = requireSheetBootstrapRealtimeToken(
1638
- bootstrap.realtimeToken,
1639
- 'openSheet.realtimeToken',
1640
- );
1641
- const sheet = validateSheetBootstrapWorkbook(bootstrap.sheet, access);
1642
- const tabs = validateSheetBootstrapTabSummaries(bootstrap.tabs);
1273
+ // syncSheetTab responses carry no workbook, tab list or token: the caller
1274
+ // composes them with its cached manifest (lean transport).
1275
+ const realtimeToken =
1276
+ bootstrap.realtimeToken === null || bootstrap.realtimeToken === undefined
1277
+ ? ''
1278
+ : requireSheetBootstrapRealtimeToken(bootstrap.realtimeToken, 'openSheet.realtimeToken');
1279
+ const sheet =
1280
+ bootstrap.sheet === null || bootstrap.sheet === undefined ? null : validateSheetBootstrapWorkbook(bootstrap.sheet, access);
1281
+ const tabs = bootstrap.tabs === null || bootstrap.tabs === undefined ? null : validateSheetBootstrapTabSummaries(bootstrap.tabs);
1643
1282
  const selectedTab = bootstrap.selectedTab
1644
- ? validateSelectedSheetBootstrapTab(bootstrap.selectedTab, access, tabs)
1283
+ ? validateSelectedSheetBootstrapTab(
1284
+ bootstrap.selectedTab,
1285
+ access,
1286
+ tabs || [{ id: String(bootstrap.selectedTab.id || '') } as SheetTabSummaryGQL],
1287
+ )
1645
1288
  : null;
1646
1289
  if (bootstrap.unavailableReason) {
1647
- failSheetBootstrap(
1648
- 'INVALID_STATUS',
1649
- 'READY openSheet responses cannot have an unavailable reason.',
1650
- );
1290
+ failSheetBootstrap('INVALID_STATUS', 'READY openSheet responses cannot have an unavailable reason.');
1651
1291
  }
1652
1292
  if (bootstrap.mode !== 'SNAPSHOT' && bootstrap.mode !== 'DELTA') {
1653
- return failSheetBootstrap(
1654
- 'INVALID_STATUS',
1655
- 'READY openSheet responses require a known mode.',
1656
- );
1293
+ return failSheetBootstrap('INVALID_STATUS', 'READY openSheet responses require a known mode.');
1657
1294
  }
1658
- const currentSeq = requireSheetBootstrapSeq(
1659
- bootstrap.currentSeq,
1660
- 'openSheet.currentSeq',
1661
- );
1662
- const servedViewport = requireSheetBootstrapViewport(
1663
- bootstrap.servedViewport,
1664
- 'openSheet.servedViewport',
1665
- );
1666
- const referencedDataTables = validateSheetBootstrapReferencedTables(
1667
- bootstrap.referencedDataTables,
1668
- );
1295
+ const currentSeq = requireSheetBootstrapSeq(bootstrap.currentSeq, 'openSheet.currentSeq');
1669
1296
 
1670
1297
  if (!selectedTab) {
1671
- requireMatchingSheetBootstrapViewport(
1672
- servedViewport,
1673
- normalizeSheetViewport({}),
1674
- 'Empty-workbook servedViewport',
1675
- );
1676
1298
  if (
1677
- tabs.length ||
1299
+ !sheet ||
1300
+ (tabs && tabs.length) ||
1678
1301
  bootstrap.mode !== 'SNAPSHOT' ||
1679
1302
  currentSeq !== SHEET_JOURNAL_ZERO_SEQ ||
1680
1303
  bootstrap.snapshot ||
1681
1304
  !Array.isArray(bootstrap.changes) ||
1682
1305
  bootstrap.changes.length
1683
1306
  ) {
1684
- failSheetBootstrap(
1685
- 'INVALID_RESPONSE',
1686
- 'Empty-workbook openSheet response is internally inconsistent.',
1687
- );
1307
+ failSheetBootstrap('INVALID_RESPONSE', 'Empty-workbook openSheet response is internally inconsistent.');
1688
1308
  }
1689
1309
 
1690
1310
  return {
@@ -1692,78 +1312,91 @@ export async function applySheetBootstrap(params: {
1692
1312
  status: 'READY',
1693
1313
  access,
1694
1314
  realtimeToken,
1695
- sheet,
1696
- tabs,
1315
+ sheet: sheet as SheetGQL,
1316
+ tabs: tabs || [],
1697
1317
  selectedTab: null,
1698
1318
  mode: 'SNAPSHOT',
1699
1319
  currentSeq,
1700
- servedViewport,
1701
- referencedDataTables,
1702
- state: null,
1320
+ servedViewport: normalizeSheetViewport({}),
1321
+
1322
+ image: null,
1323
+ rows: [],
1324
+ rowsAfterSeq: currentSeq,
1325
+ topology: null,
1703
1326
  };
1704
1327
  }
1705
1328
 
1706
- const sheetTabId = requireSheetBootstrapId(
1707
- selectedTab.id,
1708
- 'openSheet.selectedTab.id',
1709
- );
1710
- const selectedTabSeq = requireSheetBootstrapSeq(
1711
- selectedTab.cellsRevision,
1712
- 'openSheet.selectedTab.cellsRevision',
1713
- );
1714
- const selectedSummary = tabs.find((tab) => tab.id === sheetTabId);
1329
+ const sheetTabId = requireSheetBootstrapId(selectedTab.id, 'openSheet.selectedTab.id');
1330
+ const selectedTabSeq = requireSheetBootstrapSeq(selectedTab.cellsRevision, 'openSheet.selectedTab.cellsRevision');
1331
+ const selectedSummary = tabs?.find((tab) => tab.id === sheetTabId);
1715
1332
  if (
1716
1333
  selectedTabSeq !== currentSeq ||
1717
- requireSheetBootstrapSeq(
1718
- selectedSummary?.currentSeq,
1719
- 'openSheet selected tab summary currentSeq',
1720
- ) !== currentSeq
1334
+ (tabs && requireSheetBootstrapSeq(selectedSummary?.currentSeq, 'openSheet selected tab summary currentSeq') !== currentSeq)
1721
1335
  ) {
1722
- failSheetBootstrap(
1723
- 'INVALID_SEQUENCE',
1724
- 'openSheet selected-tab cursors do not agree.',
1725
- );
1336
+ failSheetBootstrap('INVALID_SEQUENCE', 'openSheet selected-tab cursors do not agree.');
1726
1337
  }
1727
- const expectedViewport = getExpectedSheetBootstrapViewport(selectedTab);
1728
- requireMatchingSheetBootstrapViewport(
1729
- servedViewport,
1730
- expectedViewport,
1731
- 'openSheet servedViewport',
1732
- );
1338
+ const servedViewport =
1339
+ bootstrap.servedViewport === null || bootstrap.servedViewport === undefined
1340
+ ? getExpectedSheetBootstrapViewport(selectedTab)
1341
+ : requireSheetBootstrapViewport(bootstrap.servedViewport, 'openSheet.servedViewport');
1733
1342
  const scope: SheetBootstrapScope = {
1734
1343
  organizationId: access.organizationId as string,
1735
1344
  sheetId: access.sheetId,
1736
1345
  sheetTabId,
1737
1346
  viewport: servedViewport,
1738
1347
  };
1739
- const state =
1740
- bootstrap.mode === 'SNAPSHOT'
1741
- ? await applySnapshotSheetBootstrap({
1742
- bootstrap,
1743
- selectedTab,
1744
- currentSeq,
1745
- scope,
1746
- })
1747
- : applyDeltaSheetBootstrap({
1748
- bootstrap,
1749
- selectedTab,
1750
- currentSeq,
1751
- scope,
1752
- currentState: params.currentState,
1753
- });
1754
-
1755
- return {
1348
+ const ready = {
1756
1349
  ...contract,
1757
- status: 'READY',
1350
+ status: 'READY' as const,
1758
1351
  access,
1759
1352
  realtimeToken,
1760
- sheet,
1761
- tabs,
1353
+ sheet: sheet as SheetGQL,
1354
+ tabs: tabs || [],
1762
1355
  selectedTab,
1763
- mode: bootstrap.mode,
1764
1356
  currentSeq,
1765
1357
  servedViewport,
1766
- referencedDataTables,
1767
- state,
1358
+ };
1359
+ if (bootstrap.mode === 'SNAPSHOT') {
1360
+ const snapshot = await applySnapshotSheetBootstrap({
1361
+ bootstrap,
1362
+ currentSeq,
1363
+ scope,
1364
+ selectedTab,
1365
+ });
1366
+ return {
1367
+ ...ready,
1368
+ mode: 'SNAPSHOT',
1369
+ image: snapshot.image,
1370
+ rows: snapshot.rows,
1371
+ rowsAfterSeq: snapshot.image.seq,
1372
+ topology: validateSheetBootstrapTopology({
1373
+ afterSeq: parseSheetJournalSeq(params.sinceSeq),
1374
+ complete: bootstrap.topologyComplete,
1375
+ sheetTabId,
1376
+ throughSeq: snapshot.image.seq,
1377
+ value: bootstrap.topologyChanges,
1378
+ }),
1379
+ };
1380
+ }
1381
+ if (bootstrap.snapshot !== null && bootstrap.snapshot !== undefined) {
1382
+ failSheetBootstrap('INVALID_RESPONSE', 'openSheet DELTA must not include a replacement snapshot.');
1383
+ }
1384
+ const sinceSeq = parseSheetJournalSeq(params.sinceSeq);
1385
+ if (!sinceSeq) {
1386
+ return failSheetBootstrap('INVALID_RESPONSE', 'openSheet DELTA requires the applied seq the request was negotiated from.');
1387
+ }
1388
+
1389
+ return {
1390
+ ...ready,
1391
+ mode: 'DELTA',
1392
+ image: null,
1393
+ rows: validateSheetBootstrapChanges({
1394
+ value: bootstrap.changes,
1395
+ afterSeq: sinceSeq,
1396
+ currentSeq,
1397
+ scope: getSheetBootstrapReplayScope(scope),
1398
+ }),
1399
+ rowsAfterSeq: sinceSeq,
1400
+ topology: null,
1768
1401
  };
1769
1402
  }