@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
@@ -0,0 +1,512 @@
1
+ import { DateTime } from 'luxon';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { collectSheetFormulaStaticReferences } from '../src/utils/sheetFormulaCompile.ts';
4
+ import { parseSheetFormulaExpression } from '../src/utils/sheetFormulaParser.ts';
5
+ import { getSheetFormulaColumnLabel, type SheetFormulaASTNode } from '../src/utils/sheetFormulaSyntax.ts';
6
+ import { findSheetFormulaWildcardTextIndex } from '../src/utils/sheetFormulaCriteria.ts';
7
+ import {
8
+ evaluateSheetFormulaExpressionAsync,
9
+ evaluateSheetFormulaExpressionSync,
10
+ type SheetFormulaEvaluatorResult,
11
+ type SheetFormulaReferenceResolver,
12
+ } from '../src/utils/sheetFormulaEvaluator.ts';
13
+ import { getSheetFormulaFunctionNameSuggestions } from '../src/utils/sheetFormulaReference.ts';
14
+
15
+ /**
16
+ * Types
17
+ */
18
+
19
+ type TestCells = Record<string, unknown>;
20
+
21
+ /* Per-test context: literal cells keyed by A1 plus the keys read so far, so
22
+ * tests can prove what the IS* functions evaluate. A cell holding an Error
23
+ * resolves as that formula error; the string 'LOADING' resolves as loading. */
24
+ type TestContext = {
25
+ cells: TestCells;
26
+ reads: string[];
27
+ };
28
+
29
+ const TEST_NOW = new Date('2026-01-02T03:04:05.000Z');
30
+
31
+ /*
32
+ * Return the A1 key of one cell coordinate.
33
+ */
34
+ function getTestA1(rowIndex: number, columnIndex: number) {
35
+ return `${getSheetFormulaColumnLabel(columnIndex)}${rowIndex}`;
36
+ }
37
+
38
+ /* Dense in-memory resolver over A1-keyed literal cells (error cells inside
39
+ * ranges read as blank, as in both production resolvers). */
40
+ const TEST_RESOLVER: SheetFormulaReferenceResolver<TestContext> = {
41
+ resolveCellReference(context, node) {
42
+ const key = getTestA1(node.reference.rowIndex, node.reference.columnIndex);
43
+ context.reads.push(key);
44
+ const value = context.cells[key];
45
+ if (value === 'LOADING') {
46
+ return { loading: true, references: [], value: null };
47
+ }
48
+
49
+ return value instanceof Error
50
+ ? {
51
+ error: { code: value.message, message: value.message },
52
+ references: [],
53
+ value: '#ERROR!',
54
+ }
55
+ : { references: [], value: value ?? null };
56
+ },
57
+ resolveRangeReference(context, node) {
58
+ const values: unknown[] = [];
59
+ for (let row = node.reference.startRowIndex; row <= Math.min(node.reference.endRowIndex, 500); row++) {
60
+ for (let column = node.reference.startColumnIndex; column <= Math.min(node.reference.endColumnIndex, 256); column++) {
61
+ const value = context.cells[getTestA1(row, column)];
62
+ values.push(value instanceof Error ? null : (value ?? null));
63
+ }
64
+ }
65
+ return { references: [], value: { kind: 'SHEET_RANGE_VALUE', values } };
66
+ },
67
+ };
68
+
69
+ /*
70
+ * Evaluate one formula against literal cells.
71
+ */
72
+ function evaluate(formula: string, cells: TestCells = {}, timeZone = 'UTC'): SheetFormulaEvaluatorResult {
73
+ return evaluateSheetFormulaExpressionSync({
74
+ expression: formula.replace(/^=/, ''),
75
+ now: TEST_NOW,
76
+ resolver: TEST_RESOLVER,
77
+ resolverContext: { cells, reads: [] },
78
+ timeZone,
79
+ });
80
+ }
81
+
82
+ /*
83
+ * Assert one formula evaluates to a value without an error.
84
+ */
85
+ function expectValue(formula: string, cells: TestCells, expected: unknown, timeZone = 'UTC') {
86
+ const result = evaluate(formula, cells, timeZone);
87
+ expect(result.error, `${formula}: ${result.error?.message}`).toBeFalsy();
88
+ expect(result.value, formula).toEqual(expected);
89
+ }
90
+
91
+ /*
92
+ * Assert one formula evaluates to an error code and, optionally, its token.
93
+ */
94
+ function expectError(formula: string, cells: TestCells, code: string, display?: string) {
95
+ const result = evaluate(formula, cells);
96
+ expect(result.error?.code, formula).toBe(code);
97
+ if (display) {
98
+ expect(result.value, formula).toBe(display);
99
+ }
100
+ }
101
+
102
+ /*
103
+ * Return A1-keyed cells for one column of values starting at a row.
104
+ */
105
+ function column(label: string, values: unknown[], startRow = 1): TestCells {
106
+ return Object.fromEntries(values.map((value, index) => [`${label}${startRow + index}`, value]));
107
+ }
108
+
109
+ /*
110
+ * Return the Monday-Friday day count between two ISO dates by walking every
111
+ * day (the reference for the whole-week arithmetic).
112
+ */
113
+ function bruteForceNetworkDays(start: string, end: string, holidays: string[]) {
114
+ const from = DateTime.fromISO(start, { zone: 'utc' });
115
+ const to = DateTime.fromISO(end, { zone: 'utc' });
116
+ const direction = to < from ? -1 : 1;
117
+ const skip = new Set(holidays);
118
+ let count = 0;
119
+ for (let day = from; direction > 0 ? day <= to : day >= to; day = day.plus({ days: direction })) {
120
+ if (day.weekday <= 5 && !skip.has(day.toISODate() as string)) {
121
+ count++;
122
+ }
123
+ }
124
+
125
+ return direction * count;
126
+ }
127
+
128
+ /*
129
+ * Return the WORKDAY result by stepping one day at a time (the reference for
130
+ * the week-jumping implementation).
131
+ */
132
+ function bruteForceWorkday(start: string, days: number, holidays: string[]) {
133
+ const skip = new Set(holidays);
134
+ const direction = days < 0 ? -1 : 1;
135
+ let remaining = Math.abs(days);
136
+ let day = DateTime.fromISO(start, { zone: 'utc' });
137
+ while (remaining > 0) {
138
+ day = day.plus({ days: direction });
139
+ if (day.weekday <= 5 && !skip.has(day.toISODate() as string)) {
140
+ remaining--;
141
+ }
142
+ }
143
+
144
+ return day.toISODate();
145
+ }
146
+
147
+ describe('text functions', () => {
148
+ it('join values and ranges with text forms and the length cap', () => {
149
+ expectValue('=CONCAT("a", 1, TRUE, A1:A3)', column('A', ['x', null, 2.5]), 'a1TRUEx2.5');
150
+ expectValue('=CONCATENATE(0.1 + 0.2, "")', {}, '0.3');
151
+ expectValue('=TEXTJOIN("-", FALSE, A1:A3)', column('A', ['x', null, 'y']), 'x--y');
152
+ expectValue('=TEXTJOIN("-", TRUE, A1:A4)', column('A', ['x', null, '', 'y']), 'x-y');
153
+ expectError('=TEXTJOIN("-", "maybe", "a")', {}, 'INVALID_VALUE');
154
+ expectError('=TEXTJOIN("-")', {}, 'INVALID_FORMULA');
155
+ const longCells = column(
156
+ 'A',
157
+ Array.from({ length: 30 }, () => 'x'.repeat(400)),
158
+ );
159
+ expectError('=CONCAT(A1:A30)', longCells, 'INVALID_VALUE', '#VALUE!');
160
+ expectValue('=LEN(CONCAT(A1:A25))', longCells, 10_000);
161
+ expectError('=SUBSTITUTE(A1, "x", "xx")', { A1: 'x'.repeat(6000) }, 'INVALID_VALUE');
162
+ });
163
+
164
+ it('slice by UTF-16 code units and validate counts', () => {
165
+ expectValue('=LEFT("hello")', {}, 'h');
166
+ expectValue('=LEFT("hello", 10)', {}, 'hello');
167
+ expectValue('=RIGHT("hello", 0)', {}, '');
168
+ expectValue('=RIGHT(12345, 2)', {}, '45');
169
+ expectValue('=MID("hello", 4, 10)', {}, 'lo');
170
+ expectValue('=MID("hello", 9, 2)', {}, '');
171
+ expectValue('=LEN("😀a")', {}, 3);
172
+ expectValue('=LEN(A1)', {}, 0);
173
+ expectValue('=LEFT(A1, B1)', { A1: 'abc' }, '');
174
+ expectError('=LEFT("abc", -1)', {}, 'INVALID_VALUE');
175
+ expectError('=MID("abc", 0, 1)', {}, 'INVALID_VALUE');
176
+ expectError('=MID("abc", 1, "x")', {}, 'INVALID_VALUE');
177
+ expectError('=LEFT(A1:A2, 1)', {}, 'INVALID_VALUE');
178
+ expectError('=LEN("a", "b")', {}, 'INVALID_FORMULA');
179
+ });
180
+
181
+ it('change case locale-independently and trim ASCII spaces', () => {
182
+ expectValue('=UPPER("straße")', {}, 'STRASSE');
183
+ expectValue('=LOWER("ÉCOLE")', {}, 'école');
184
+ expectValue('=PROPER("élan VITAL o\'neil 2nd")', {}, "Élan Vital O'Neil 2Nd");
185
+ // A combining mark continues the word
186
+ expectValue('=PROPER("cafés bar")', {}, 'Cafés Bar');
187
+ expectValue('=TRIM(" a b ")', {}, 'a b');
188
+ expectValue('=TRIM(A1)', { A1: '\ta b\t' }, '\ta b\t');
189
+ });
190
+
191
+ it('substitute and replace literally', () => {
192
+ expectValue('=SUBSTITUTE("aAaA", "a", "x")', {}, 'xAxA');
193
+ expectValue('=SUBSTITUTE("a-b-c", "-", "", 2)', {}, 'a-bc');
194
+ expectValue('=SUBSTITUTE("a-b", "-", "+", 5)', {}, 'a-b');
195
+ expectValue('=SUBSTITUTE("aaa", "aa", "b")', {}, 'ba');
196
+ expectValue('=SUBSTITUTE("abc", "", "x")', {}, 'abc');
197
+ expectError('=SUBSTITUTE("abc", "b", "x", 0)', {}, 'INVALID_VALUE');
198
+ expectValue('=REPLACE("abcdef", 1, 0, "X")', {}, 'Xabcdef');
199
+ expectValue('=REPLACE("abc", 10, 1, "x")', {}, 'abcx');
200
+ expectError('=REPLACE("abc", 0, 1, "x")', {}, 'INVALID_VALUE');
201
+ });
202
+
203
+ it('find case-sensitively and search with wildcards', () => {
204
+ expectValue('=FIND("b", "abcb")', {}, 2);
205
+ expectValue('=FIND("b", "abcb", 3)', {}, 4);
206
+ expectValue('=FIND("", "abc")', {}, 1);
207
+ expectValue('=FIND("", "abc", 4)', {}, 4);
208
+ expectError('=FIND("", "abc", 5)', {}, 'INVALID_VALUE');
209
+ expectError('=FIND("B", "abc")', {}, 'INVALID_VALUE', '#VALUE!');
210
+ expectValue('=SEARCH("B", "abc")', {}, 2);
211
+ expectValue('=SEARCH("b*d", "xxbcd")', {}, 3);
212
+ expectValue('=SEARCH("*c", "abc")', {}, 1);
213
+ expectValue('=SEARCH("?c", "abcabc", 4)', {}, 5);
214
+ expectValue('=SEARCH("~*", "a*b")', {}, 2);
215
+ expectValue('=SEARCH("~?", "why?")', {}, 4);
216
+ expectValue('=SEARCH("é", "CAFÉ")', {}, 4);
217
+ expectValue('=SEARCH("a", "😀a")', {}, 3);
218
+ expectError('=SEARCH("z", "abc")', {}, 'INVALID_VALUE');
219
+ expectError(`=SEARCH("*${'x'.repeat(260)}", "abc")`, {}, 'INVALID_VALUE');
220
+ });
221
+
222
+ it('search in linear time on adversarial wildcard patterns', () => {
223
+ const text = 'a'.repeat(10_000);
224
+ const started = performance.now();
225
+ expect(findSheetFormulaWildcardTextIndex('*a*a*a*a*b', text)).toEqual({
226
+ index: -1,
227
+ ok: true,
228
+ });
229
+ expect(findSheetFormulaWildcardTextIndex(`*${'a*'.repeat(100)}b`, text)).toEqual({ index: -1, ok: true });
230
+ expect(findSheetFormulaWildcardTextIndex('a?a*a', `${text}b`)).toEqual({
231
+ index: 0,
232
+ ok: true,
233
+ });
234
+ expect(performance.now() - started).toBeLessThan(250);
235
+ });
236
+
237
+ it('trim in linear time on long interior runs of spaces', () => {
238
+ const cells = { ...column('A', ['a']), A500: 'x' };
239
+ expectValue('=TRIM(TEXTJOIN(" ", FALSE, A1:A500))', cells, 'a x');
240
+ const padded = { A1: ` a${' '.repeat(9994)}x ` };
241
+ const started = performance.now();
242
+ // A backtracking / +$/ trim takes ~150 ms per call at this length
243
+ for (let index = 0; index < 10; index++) {
244
+ expectValue('=TRIM(A1)', padded, 'a x');
245
+ }
246
+ expect(performance.now() - started).toBeLessThan(250);
247
+ });
248
+
249
+ it('pick the leftmost match start for wildcard patterns', () => {
250
+ const cases: Array<[string, string, number]> = [
251
+ ['b?d', 'abcbxd', 3],
252
+ ['b*', 'aab', 2],
253
+ ['*', 'abc', 0],
254
+ ['', 'abc', 0],
255
+ ['a*z', 'xa-a-z', 1],
256
+ ['?', '', -1],
257
+ ['z*', 'abc', -1],
258
+ ];
259
+ for (const [pattern, text, index] of cases) {
260
+ expect(findSheetFormulaWildcardTextIndex(pattern, text), pattern).toEqual({ index, ok: true });
261
+ }
262
+ });
263
+
264
+ it('format numbers and dates with TEXT through the shared engine', () => {
265
+ expectValue('=TEXT(1234.567, "#,##0.00")', {}, '1,234.57');
266
+ expectValue('=TEXT(-5, "0.0;(0.0)")', {}, '(5.0)');
267
+ expectValue('=TEXT("12.5", "0.00")', {}, '12.50');
268
+ expectValue('=TEXT(A1, "0")', {}, '0');
269
+ expectValue('=TEXT("2026-01-05", "dddd, mmmm d")', {}, 'Monday, January 5');
270
+ expectValue('=TEXT("2026-01-05", "0")', {}, '46027');
271
+ expectValue('=TEXT("2026-01-02T03:04:05Z", "yyyy-mm-dd hh:mm")', {}, '2026-01-01 22:04', 'America/Toronto');
272
+ expectValue('=TEXT("2026-01-02T03:04:05", "hh:mm")', {}, '03:04', 'America/Toronto');
273
+ expectValue('=TEXT("abc", "0.00")', {}, 'abc');
274
+ expectValue('=TEXT("abc", A1)', { A1: '0;0;0;@" units"' }, 'abc units');
275
+ expectValue('=TEXT(5, "@")', {}, '5');
276
+ expectValue('=TEXT(TRUE, "0")', {}, 'TRUE');
277
+ expectValue('=TEXT(5, "")', {}, '');
278
+ expectError('=TEXT(5, "[[[")', {}, 'INVALID_VALUE');
279
+ expectError('=TEXT(A1:A2, "0")', {}, 'INVALID_VALUE');
280
+ });
281
+
282
+ it('read numbers with VALUE', () => {
283
+ expectValue('=VALUE("1,234.5")', {}, 1234.5);
284
+ expectValue('=VALUE(" $12 ")', {}, 12);
285
+ expectValue('=VALUE("-$3.5")', {}, -3.5);
286
+ expectValue('=VALUE("15%")', {}, 0.15);
287
+ expectValue('=VALUE("(12)")', {}, -12);
288
+ expectValue('=VALUE("1e3")', {}, 1000);
289
+ expectValue('=VALUE(".5")', {}, 0.5);
290
+ expectValue('=VALUE(A1)', {}, 0);
291
+ expectValue('=VALUE(FALSE)', {}, 0);
292
+ expectValue('=VALUE(7)', {}, 7);
293
+ for (const text of ['2026-01-01', '12,34', 'abc', '(-1)', '1e999', '$']) {
294
+ expectError(`=VALUE("${text}")`, {}, 'INVALID_VALUE');
295
+ }
296
+ });
297
+ });
298
+
299
+ describe('date functions', () => {
300
+ it('shift months with month-end clamping and leap years', () => {
301
+ expectValue('=EDATE("2026-01-31", 1)', {}, '2026-02-28');
302
+ expectValue('=EDATE("2024-01-31", 1)', {}, '2024-02-29');
303
+ expectValue('=EDATE("2024-02-29", 12)', {}, '2025-02-28');
304
+ expectValue('=EDATE("2026-03-31", -1.9)', {}, '2026-02-28');
305
+ expectValue('=EOMONTH("2024-02-10", 0)', {}, '2024-02-29');
306
+ expectValue('=EOMONTH("2026-12-15", 1)', {}, '2027-01-31');
307
+ expectValue('=EDATE("2026-01-02T03:00:00Z", 1)', {}, '2026-02-02');
308
+ expectValue('=EDATE("2026-01-02T03:00:00Z", 1)', {}, '2026-02-01', 'America/Toronto');
309
+ expectError('=EDATE(45000, 1)', {}, 'INVALID_VALUE');
310
+ // Partial ISO text and bare times are not dates (a time would read as today)
311
+ expectError('=EDATE("2026", 1)', {}, 'INVALID_VALUE');
312
+ expectError('=DAYS("10:30", "2026-01-01")', {}, 'INVALID_VALUE');
313
+ expectError('=EDATE("soon", 1)', {}, 'INVALID_VALUE');
314
+ expectError('=EDATE("9999-12-01", 1)', {}, 'INVALID_NUMBER', '#NUM!');
315
+ expectError('=EDATE("2026-01-01", 10^12)', {}, 'INVALID_NUMBER');
316
+ });
317
+
318
+ it('number weekdays and weeks for every supported type', () => {
319
+ // 2026-01-04 is a Sunday
320
+ const expectedByType: Record<number, number> = {
321
+ 1: 1,
322
+ 2: 7,
323
+ 3: 6,
324
+ 11: 7,
325
+ 12: 6,
326
+ 13: 5,
327
+ 14: 4,
328
+ 15: 3,
329
+ 16: 2,
330
+ 17: 1,
331
+ };
332
+ for (const [type, expected] of Object.entries(expectedByType)) {
333
+ expectValue(`=WEEKDAY("2026-01-04", ${type})`, {}, expected);
334
+ }
335
+ expectError('=WEEKDAY("2026-01-04", 4)', {}, 'INVALID_NUMBER');
336
+ expectValue('=WEEKNUM("2026-01-03")', {}, 1);
337
+ expectValue('=WEEKNUM("2026-01-04")', {}, 2);
338
+ expectValue('=WEEKNUM("2026-01-04", 2)', {}, 1);
339
+ expectValue('=WEEKNUM("2026-01-05", 2)', {}, 2);
340
+ expectValue('=WEEKNUM("2026-12-31")', {}, 53);
341
+ // ISO weeks cross year boundaries
342
+ expectValue('=WEEKNUM("2027-01-01", 21)', {}, 53);
343
+ expectValue('=WEEKNUM("2024-12-30", 21)', {}, 1);
344
+ expectError('=WEEKNUM("2026-01-04", 3)', {}, 'INVALID_NUMBER');
345
+ });
346
+
347
+ it('count days and date differences', () => {
348
+ expectValue('=DAYS("2026-03-01", "2026-02-01")', {}, 28);
349
+ expectValue('=DAYS("2026-01-01", "2026-03-01")', {}, -59);
350
+ expectValue('=DAYS("2024-03-01", "2024-02-28")', {}, 2);
351
+ expectValue('=DATEDIF("2020-01-15", "2026-03-10", "y")', {}, 6);
352
+ expectValue('=DATEDIF("2020-01-15", "2026-03-10", "M")', {}, 73);
353
+ expectValue('=DATEDIF("2020-01-15", "2026-03-10", "D")', {}, 2246);
354
+ expectValue('=DATEDIF("2020-01-15", "2026-03-10", "YM")', {}, 1);
355
+ expectValue('=DATEDIF("2020-01-15", "2026-03-10", "YD")', {}, 54);
356
+ expectValue('=DATEDIF("2026-01-31", "2026-03-01", "MD")', {}, 1);
357
+ expectValue('=DATEDIF("2026-01-31", "2026-02-28", "M")', {}, 0);
358
+ expectValue('=DATEDIF("2026-01-05", "2026-01-05", "D")', {}, 0);
359
+ expectError('=DATEDIF("2026-02-01", "2026-01-01", "D")', {}, 'INVALID_NUMBER');
360
+ expectError('=DATEDIF("2026-01-01", "2026-02-01", "W")', {}, 'INVALID_NUMBER');
361
+ });
362
+
363
+ it('count working days like a day-by-day walk', () => {
364
+ const holidays = ['2026-01-01', '2026-01-19', '2026-01-24', '2026-01-19'];
365
+ const cells = column('H', holidays);
366
+ for (const [start, end] of [
367
+ ['2026-01-01', '2026-01-31'],
368
+ ['2026-01-31', '2026-01-01'],
369
+ ['2026-01-03', '2026-01-04'],
370
+ ['2026-01-05', '2026-01-05'],
371
+ ['2025-12-20', '2026-02-10'],
372
+ ]) {
373
+ expectValue(`=NETWORKDAYS("${start}", "${end}", H1:H6)`, cells, bruteForceNetworkDays(start, end, holidays));
374
+ }
375
+ expectValue('=NETWORKDAYS("2026-01-01", "2026-01-31", "2026-01-01")', {}, 21);
376
+ expectError('=NETWORKDAYS("2026-01-01", "2026-01-31", 5)', {}, 'INVALID_VALUE');
377
+ // Whole-week arithmetic keeps huge spans cheap
378
+ const started = performance.now();
379
+ expectValue('=NETWORKDAYS("0001-01-01", "9999-12-31")', {}, 2_608_615);
380
+ expect(performance.now() - started).toBeLessThan(100);
381
+ });
382
+
383
+ it('move by working days like a day-by-day walk', () => {
384
+ const holidays = ['2026-01-05', '2026-01-06', '2026-01-10', '2026-01-16'];
385
+ const cells = column('H', holidays);
386
+ for (const [start, days] of [
387
+ ['2026-01-02', 1],
388
+ ['2026-01-02', 3],
389
+ ['2026-01-03', 5],
390
+ ['2026-01-02', 12],
391
+ ['2026-01-20', -6],
392
+ ['2026-01-09', -1],
393
+ ['2026-01-01', 250],
394
+ ] as const) {
395
+ expectValue(`=WORKDAY("${start}", ${days}, H1:H4)`, cells, bruteForceWorkday(start, days, holidays));
396
+ }
397
+ expectValue('=WORKDAY("2026-01-03", 0)', {}, '2026-01-03');
398
+ // A long run of weekday holidays is skipped without walking day by day
399
+ const manyHolidays: string[] = [];
400
+ for (let day = DateTime.fromISO('2026-01-01', { zone: 'utc' }); manyHolidays.length < 400; day = day.plus({ days: 1 })) {
401
+ manyHolidays.push(day.toISODate() as string);
402
+ }
403
+ expectValue('=WORKDAY("2025-12-31", 3, H1:H400)', column('H', manyHolidays), bruteForceWorkday('2025-12-31', 3, manyHolidays));
404
+ expectError('=WORKDAY("2026-01-01", 4000000)', {}, 'INVALID_NUMBER');
405
+ });
406
+ });
407
+
408
+ describe('math functions', () => {
409
+ it('round down, sign, square roots and truncate', () => {
410
+ expectValue('=INT(7.9)', {}, 7);
411
+ expectValue('=INT(-2.5)', {}, -3);
412
+ expectValue('=INT(A1)', {}, 0);
413
+ expectValue('=INT("4.5")', {}, 4);
414
+ expectValue('=SIGN(-0.001)', {}, -1);
415
+ expectValue('=SIGN(0)', {}, 0);
416
+ expectValue('=SIGN(TRUE)', {}, 1);
417
+ expectValue('=SQRT(2.25)', {}, 1.5);
418
+ expectError('=SQRT(-1)', {}, 'INVALID_NUMBER', '#NUM!');
419
+ expectValue('=TRUNC(-2.567, 2)', {}, -2.56);
420
+ expectValue('=TRUNC(1.005, 2)', {}, 1);
421
+ expectValue('=TRUNC(1234.5, -2)', {}, 1200);
422
+ expectValue('=TRUNC(8.9)', {}, 8);
423
+ expectError('=INT("abc")', {}, 'INVALID_VALUE');
424
+ expectError('=SQRT(A1:A2)', {}, 'INVALID_VALUE');
425
+ expectError('=TRUNC()', {}, 'INVALID_FORMULA');
426
+ });
427
+ });
428
+
429
+ describe('IS* functions', () => {
430
+ it('answer with TRUE/FALSE instead of propagating errors', () => {
431
+ const divide = new Error('DIVIDE_BY_ZERO');
432
+ const notFound = new Error('NOT_FOUND');
433
+ expectValue('=ISERROR(A1)', { A1: divide }, true);
434
+ expectValue('=ISERROR(A1)', { A1: 5 }, false);
435
+ expectValue('=ISNA(A1)', { A1: notFound }, true);
436
+ expectValue('=ISNA(A1)', { A1: divide }, false);
437
+ expectValue('=ISNUMBER(A1)', { A1: divide }, false);
438
+ expectValue('=ISTEXT(A1)', { A1: divide }, false);
439
+ expectValue('=ISBLANK(A1)', { A1: divide }, false);
440
+ expectValue('=ISNUMBER(SEARCH("x", "abc"))', {}, false);
441
+ expectValue('=ISERROR(A1:A2)', {}, false);
442
+ });
443
+
444
+ it('classify values in the dialect', () => {
445
+ expectValue('=ISBLANK(A1)', {}, true);
446
+ expectValue('=ISBLANK("")', {}, true);
447
+ expectValue('=ISBLANK(" ")', {}, false);
448
+ expectValue('=ISBLANK(0)', {}, false);
449
+ expectValue('=ISNUMBER(3)', {}, true);
450
+ expectValue('=ISNUMBER("3")', {}, false);
451
+ expectValue('=ISNUMBER(TRUE)', {}, false);
452
+ expectValue('=ISTEXT("2026-01-01")', {}, true);
453
+ expectValue('=ISTEXT("")', {}, false);
454
+ expectValue('=ISTEXT(TRUE)', {}, false);
455
+ expectError('=ISBLANK(A1:A2)', {}, 'INVALID_VALUE');
456
+ expectError('=ISNUMBER(1, 2)', {}, 'INVALID_FORMULA');
457
+ });
458
+
459
+ it('propagate loading and keep references through the async driver', async () => {
460
+ const loading = evaluate('=ISERROR(A1)', { A1: 'LOADING' });
461
+ expect(loading.loading).toBe(true);
462
+ const asyncResult = await evaluateSheetFormulaExpressionAsync({
463
+ expression: 'ISNUMBER(SEARCH("b", A1)) & "-" & ISERROR(A2)',
464
+ now: TEST_NOW,
465
+ resolver: {
466
+ ...TEST_RESOLVER,
467
+ resolveCellReference: (context, node, runtime) => Promise.resolve(TEST_RESOLVER.resolveCellReference(context, node, runtime)),
468
+ },
469
+ resolverContext: {
470
+ cells: { A1: 'abc', A2: new Error('NOT_FOUND') },
471
+ reads: [],
472
+ },
473
+ timeZone: 'UTC',
474
+ });
475
+ expect(asyncResult.value).toBe('TRUE-TRUE');
476
+ });
477
+ });
478
+
479
+ describe('new builtins in the static graph and editor', () => {
480
+ it('register range and cell arguments as dependencies', () => {
481
+ const references = collectSheetFormulaStaticReferences(
482
+ parseSheetFormulaExpression(
483
+ 'TEXTJOIN(",", TRUE, A1:A9) & NETWORKDAYS(B1, B2, holidays!A2:A) & ISERROR(C1)',
484
+ ) as SheetFormulaASTNode,
485
+ );
486
+ expect(
487
+ references.ranges.map(
488
+ (range) =>
489
+ `${range.sheetName || ''}!${range.startRowIndex}:${range.startColumnIndex}-${range.endRowIndex}:${range.endColumnIndex}`,
490
+ ),
491
+ ).toEqual(['!1:1-9:1', 'holidays!2:1-500:1']);
492
+ expect(references.cells.map((cell) => cell.rowIndex)).toEqual([1, 2, 1]);
493
+ expect(references.volatile).toBe(false);
494
+ expect(collectSheetFormulaStaticReferences(parseSheetFormulaExpression('EDATE(TODAY(), 1)') as SheetFormulaASTNode).volatile).toBe(
495
+ true,
496
+ );
497
+ });
498
+
499
+ it('suggest builtin names for a typed prefix', () => {
500
+ expect(getSheetFormulaFunctionNameSuggestions('su').map((entry) => entry.name)).toEqual([
501
+ 'SUBSTITUTE',
502
+ 'SUM',
503
+ 'SUMIF',
504
+ 'SUMIFS',
505
+ 'SUMPRODUCT',
506
+ ]);
507
+ expect(getSheetFormulaFunctionNameSuggestions('sum').map((entry) => entry.name)).toEqual(['SUM', 'SUMIF', 'SUMIFS', 'SUMPRODUCT']);
508
+ expect(getSheetFormulaFunctionNameSuggestions('a1')).toEqual([]);
509
+ expect(getSheetFormulaFunctionNameSuggestions('zzz')).toEqual([]);
510
+ expect(getSheetFormulaFunctionNameSuggestions('c').length).toBe(8);
511
+ });
512
+ });
@@ -1,35 +1,16 @@
1
- import {
2
- requireSheetDesignRevision,
3
- requireSheetJournalSeq,
4
- } from '@jsb188/mday/utils/sheetSequence.ts';
1
+ import { requireSheetDesignRevision, requireSheetJournalSeq } from '@jsb188/mday/utils/sheetSequence.ts';
5
2
  import { describe, expect, it } from 'vitest';
6
3
 
7
4
  describe('requireSheetDesignRevision', () => {
8
5
  it('accepts canonical non-negative BIGINT identities including zero', () => {
9
6
  expect(requireSheetDesignRevision('0')).toBe('0');
10
7
  expect(requireSheetDesignRevision(7n)).toBe('7');
11
- expect(requireSheetDesignRevision('9223372036854775807')).toBe(
12
- '9223372036854775807',
13
- );
8
+ expect(requireSheetDesignRevision('9223372036854775807')).toBe('9223372036854775807');
14
9
  });
15
10
 
16
11
  it('rejects missing, numeric, malformed, negative, and overflowing values', () => {
17
- for (const revision of [
18
- null,
19
- undefined,
20
- 0,
21
- Number.MAX_SAFE_INTEGER,
22
- '',
23
- ' 1',
24
- '1 ',
25
- '01',
26
- '-1',
27
- '1.5',
28
- '9223372036854775808',
29
- ]) {
30
- expect(() => requireSheetDesignRevision(revision as never)).toThrow(
31
- TypeError,
32
- );
12
+ for (const revision of [null, undefined, 0, Number.MAX_SAFE_INTEGER, '', ' 1', '1 ', '01', '-1', '1.5', '9223372036854775808']) {
13
+ expect(() => requireSheetDesignRevision(revision as never)).toThrow(TypeError);
33
14
  }
34
15
  });
35
16
  });
@@ -0,0 +1,134 @@
1
+ import type { SheetCellGQL } from '@jsb188/mday/types/sheet.d.ts';
2
+ import {
3
+ decodeSheetSnapshot,
4
+ encodeSheetSnapshot,
5
+ isSupportedSheetSnapshotEncodingVersion,
6
+ SHEET_SNAPSHOT_ENCODING_VERSION,
7
+ type SheetSnapshotRawData,
8
+ } from '@jsb188/mday/utils/sheetSnapshot.ts';
9
+ import { describe, expect, it } from 'vitest';
10
+
11
+ const FILE_CONSTANTS = {
12
+ ancestry: {
13
+ organizationId: 'org-1',
14
+ sheetId: 'sheet-1',
15
+ sheetTabId: 'tab-1',
16
+ seq: '42',
17
+ },
18
+ viewport: {
19
+ startRowIndex: 1,
20
+ startColumnIndex: 1,
21
+ rowCount: 20,
22
+ columnCount: 5,
23
+ },
24
+ };
25
+
26
+ /*
27
+ * Return one GraphQL-shaped cell with the snapshot ancestry filled in.
28
+ */
29
+ function buildCell(id: string, rowIndex: number, overrides: Partial<SheetCellGQL>): SheetCellGQL {
30
+ return {
31
+ id,
32
+ organizationId: FILE_CONSTANTS.ancestry.organizationId,
33
+ sheetId: FILE_CONSTANTS.ancestry.sheetId,
34
+ sheetTabId: FILE_CONSTANTS.ancestry.sheetTabId,
35
+ rowIndex,
36
+ columnIndex: 2,
37
+ revision: '1',
38
+
39
+ ...overrides,
40
+ } as SheetCellGQL;
41
+ }
42
+
43
+ /*
44
+ * Return one raw tab image holding a user cell, a composed region value cell,
45
+ * a region header cell, a region FORMULA row, and the region itself.
46
+ */
47
+ function buildRawSnapshot(): SheetSnapshotRawData {
48
+ return {
49
+ sheetId: FILE_CONSTANTS.ancestry.sheetId,
50
+ sheetTab: {
51
+ id: FILE_CONSTANTS.ancestry.sheetTabId,
52
+ organizationId: FILE_CONSTANTS.ancestry.organizationId,
53
+ sheetId: FILE_CONSTANTS.ancestry.sheetId,
54
+ name: 'Tab',
55
+ position: 0,
56
+ designRevision: '3',
57
+ design: null,
58
+ } as unknown as SheetSnapshotRawData['sheetTab'],
59
+ cells: [
60
+ buildCell('101', 1, {
61
+ value: 'typed',
62
+ textValue: 'typed',
63
+ revision: '3',
64
+ }),
65
+ buildCell('103', 3, {
66
+ value: 'Name',
67
+ textValue: 'Name',
68
+ revision: '1727000000000',
69
+ }),
70
+ buildCell('104', 4, {
71
+ value: 'Acme',
72
+ textValue: 'Acme',
73
+ revision: '1727000000123',
74
+ }),
75
+ buildCell('202', 4, {
76
+ columnIndex: 3,
77
+ rawInput: '=B4',
78
+ formulaText: '=B4',
79
+ value: 'Acme',
80
+ formulaValue: 'Acme',
81
+ textValue: 'Acme',
82
+ revision: '5',
83
+ }),
84
+ ],
85
+
86
+ pageInfo: { hasMoreRows: false, lastContentRowIndex: 5 },
87
+ viewport: FILE_CONSTANTS.viewport,
88
+ };
89
+ }
90
+
91
+ describe('sheet snapshot codec v5', () => {
92
+ it('keeps every ordinary cell revision', () => {
93
+ const encoded = encodeSheetSnapshot(buildRawSnapshot());
94
+ const decoded = decodeSheetSnapshot(encoded.payload, FILE_CONSTANTS.ancestry, FILE_CONSTANTS.viewport);
95
+ const revisionById = new Map(decoded.cells.map((cell) => [cell.id, cell.revision]));
96
+
97
+ expect(SHEET_SNAPSHOT_ENCODING_VERSION).toBe(5);
98
+ expect(encoded.encodingVersion).toBe(5);
99
+ expect(JSON.parse(encoded.payload).v).toBe(5);
100
+ // Composed cells keep their stored revisions instead of the snapshot seq
101
+ expect(revisionById.get('103')).toBe('1727000000000');
102
+ expect(revisionById.get('104')).toBe('1727000000123');
103
+ expect(revisionById.get('202')).toBe('5');
104
+ expect(revisionById.get('101')).toBe('3');
105
+ expect(decoded.sheetTab.cellsRevision).toBe('42');
106
+ });
107
+
108
+ it('round-trips ordinary cells exactly', () => {
109
+ const raw = buildRawSnapshot();
110
+ const encoded = encodeSheetSnapshot(raw);
111
+ const decoded = decodeSheetSnapshot(encoded.payload, FILE_CONSTANTS.ancestry, FILE_CONSTANTS.viewport);
112
+ const reencoded = encodeSheetSnapshot(decoded);
113
+
114
+ expect(decoded.cells).toHaveLength(raw.cells.length);
115
+ expect(decoded.cells.find((cell) => cell.id === '202')).toMatchObject({
116
+ formulaText: '=B4',
117
+ value: 'Acme',
118
+ formulaValue: 'Acme',
119
+ });
120
+
121
+ // Canonical encoding: decoding and re-encoding is byte-identical
122
+ expect(reencoded.payload).toBe(encoded.payload);
123
+ });
124
+
125
+ it('refuses to decode an older encoding version', () => {
126
+ const payload = JSON.parse(encodeSheetSnapshot(buildRawSnapshot()).payload);
127
+ payload.v = 4;
128
+
129
+ expect(isSupportedSheetSnapshotEncodingVersion(4)).toBe(false);
130
+ expect(() => decodeSheetSnapshot(JSON.stringify(payload), FILE_CONSTANTS.ancestry, FILE_CONSTANTS.viewport)).toThrow(
131
+ /Unsupported or invalid sheet snapshot encoding/,
132
+ );
133
+ });
134
+ });