@jsb188/mday 1.1.10 → 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 +140 -54
  2. package/src/constants/agentMemory.ts +123 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +21 -21
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +125 -7
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/integration.ts +8 -9
  17. package/src/constants/log.ts +14 -408
  18. package/src/constants/logDisplay/README.md +88 -0
  19. package/src/constants/logDisplay/defaults.ts +39 -0
  20. package/src/constants/logDisplay/index.ts +27 -0
  21. package/src/constants/logDisplay/operations/arable.ts +16 -0
  22. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  23. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  24. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  25. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  26. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  27. package/src/constants/logTaxonomy.generated.ts +2207 -0
  28. package/src/constants/noteDoc.ts +77 -0
  29. package/src/constants/organization.ts +18 -21
  30. package/src/constants/pageRoute.ts +23 -0
  31. package/src/constants/qrCode.ts +30 -0
  32. package/src/constants/sheet.ts +126 -14
  33. package/src/constants/sms.ts +18 -0
  34. package/src/constants/square.ts +6 -6
  35. package/src/constants/storage.ts +80 -7
  36. package/src/constants/usage.ts +82 -0
  37. package/src/constants/workflowSteps.ts +60 -0
  38. package/src/schemas/editLogEntry.ts +836 -780
  39. package/src/schemas/inboundContact.ts +60 -55
  40. package/src/schemas/logsQuery.ts +55 -49
  41. package/src/types/account.d.ts +4 -1
  42. package/src/types/agentMemory.d.ts +98 -0
  43. package/src/types/agentNote.d.ts +443 -0
  44. package/src/types/billing.d.ts +537 -0
  45. package/src/types/campaign.d.ts +1533 -0
  46. package/src/types/contact.d.ts +15 -0
  47. package/src/types/csvExport.d.ts +213 -0
  48. package/src/types/dataAnalysis.d.ts +44 -0
  49. package/src/types/dataTable.d.ts +115 -403
  50. package/src/types/definitionElement.d.ts +35 -0
  51. package/src/types/docAccess.d.ts +96 -0
  52. package/src/types/dt.d.ts +257 -0
  53. package/src/types/email.d.ts +184 -24
  54. package/src/types/emailReplyReport.d.ts +76 -0
  55. package/src/types/fieldDoc.d.ts +702 -0
  56. package/src/types/fieldDocContract.d.ts +90 -0
  57. package/src/types/inboundContact.d.ts +10 -1
  58. package/src/types/log.d.ts +254 -295
  59. package/src/types/logDisplay.types.ts +85 -0
  60. package/src/types/organization.d.ts +91 -43
  61. package/src/types/pageRoute.d.ts +48 -0
  62. package/src/types/qrCode.d.ts +96 -0
  63. package/src/types/richText.d.ts +81 -0
  64. package/src/types/sheet.d.ts +678 -129
  65. package/src/types/sms.d.ts +38 -0
  66. package/src/types/storage.d.ts +449 -129
  67. package/src/types/usage.d.ts +106 -0
  68. package/src/types/workflow.d.ts +315 -54
  69. package/src/utils/agentMemory.ts +15 -0
  70. package/src/utils/agentNote.ts +850 -0
  71. package/src/utils/aiChat.ts +43 -0
  72. package/src/utils/aiChatWork.ts +64 -0
  73. package/src/utils/billing.ts +37 -0
  74. package/src/utils/campaign.ts +1174 -0
  75. package/src/utils/campaignAI.ts +72 -0
  76. package/src/utils/campaignAccess.ts +239 -0
  77. package/src/utils/campaignEmail.ts +601 -0
  78. package/src/utils/campaignEmailCompiler.ts +372 -0
  79. package/src/utils/campaignEmailImages.ts +60 -0
  80. package/src/utils/campaignEmailStyles.ts +544 -0
  81. package/src/utils/campaignLifecycle.ts +104 -0
  82. package/src/utils/campaignPreview.ts +285 -0
  83. package/src/utils/contact.ts +50 -0
  84. package/src/utils/csvExport.ts +19 -0
  85. package/src/utils/dataTable.ts +95 -618
  86. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  87. package/src/utils/dataTableRelativeDate.ts +447 -0
  88. package/src/utils/definitionElement.ts +84 -0
  89. package/src/utils/docAccess.ts +383 -0
  90. package/src/utils/documentName.ts +53 -0
  91. package/src/utils/email.ts +317 -51
  92. package/src/utils/emailReplyReport.test.ts +187 -0
  93. package/src/utils/emailReplyReport.ts +143 -0
  94. package/src/utils/fieldDoc.ts +157 -0
  95. package/src/utils/fieldDocAnswers.ts +128 -0
  96. package/src/utils/fieldDocDefaults.ts +36 -0
  97. package/src/utils/fieldDocProgram.ts +36 -0
  98. package/src/utils/fieldDocSummary.ts +30 -0
  99. package/src/utils/log.ts +276 -192
  100. package/src/utils/logDisplay.helpers.ts +177 -0
  101. package/src/utils/logDisplay.ts +87 -0
  102. package/src/utils/logRegistryValue.ts +90 -0
  103. package/src/utils/logStoreRead.ts +262 -0
  104. package/src/utils/logTaxonomy.helpers.ts +17 -0
  105. package/src/utils/logTaxonomy.ts +76 -0
  106. package/src/utils/logTaxonomyDisplay.ts +395 -0
  107. package/src/utils/noteDoc.ts +609 -0
  108. package/src/utils/organization.ts +337 -84
  109. package/src/utils/pageRoute.ts +71 -0
  110. package/src/utils/qrCode.helpers.ts +189 -0
  111. package/src/utils/qrCode.test.ts +519 -0
  112. package/src/utils/qrCode.ts +273 -0
  113. package/src/utils/richTextHTML.ts +385 -0
  114. package/src/utils/sheet.ts +199 -107
  115. package/src/utils/sheetAxisMove.ts +616 -0
  116. package/src/utils/sheetBootstrap.ts +1402 -0
  117. package/src/utils/sheetCellLiteral.ts +101 -0
  118. package/src/utils/sheetCommand.ts +358 -0
  119. package/src/utils/sheetDesign.ts +705 -0
  120. package/src/utils/sheetExport.ts +186 -0
  121. package/src/utils/sheetFeatureReference.ts +183 -0
  122. package/src/utils/sheetFormulaArgs.ts +168 -0
  123. package/src/utils/sheetFormulaCompile.ts +475 -0
  124. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  125. package/src/utils/sheetFormulaCriteria.ts +656 -0
  126. package/src/utils/sheetFormulaDate.ts +444 -0
  127. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  128. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  129. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  130. package/src/utils/sheetFormulaLogical.ts +116 -0
  131. package/src/utils/sheetFormulaLookup.ts +488 -0
  132. package/src/utils/sheetFormulaMath.ts +48 -0
  133. package/src/utils/sheetFormulaParser.ts +729 -0
  134. package/src/utils/sheetFormulaRange.ts +330 -0
  135. package/src/utils/sheetFormulaReference.ts +703 -0
  136. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  137. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  138. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  139. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  140. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  141. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  142. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  143. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  144. package/src/utils/sheetFormulaText.ts +430 -0
  145. package/src/utils/sheetJournal.ts +200 -0
  146. package/src/utils/sheetNumberFormat.ts +1012 -0
  147. package/src/utils/sheetPreview.ts +68 -0
  148. package/src/utils/sheetSequence.ts +118 -0
  149. package/src/utils/sheetSnapshot.ts +739 -0
  150. package/src/utils/sheetStructureEdit.ts +914 -0
  151. package/src/utils/sheetStructureReferences.ts +389 -0
  152. package/src/utils/square.ts +22 -12
  153. package/src/utils/storage.ts +198 -0
  154. package/src/utils/table-route.ts +127 -11
  155. package/src/utils/time.ts +12 -0
  156. package/src/utils/workflow.ts +334 -40
  157. package/src/utils/workflowLogFingerprint.ts +302 -0
  158. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  159. package/src/utils/workflowProgress.ts +280 -0
  160. package/src/utils/workflowTriggers.ts +61 -0
  161. package/tests/agentNote.test.ts +395 -0
  162. package/tests/campaignAI.test.ts +119 -0
  163. package/tests/campaignAccess.test.ts +239 -0
  164. package/tests/campaignEmail.test.ts +441 -0
  165. package/tests/campaignLifecycle.test.ts +134 -0
  166. package/tests/campaignPublication.test.ts +309 -0
  167. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  168. package/tests/dataTableRelativeDate.test.ts +412 -0
  169. package/tests/docAccess.test.ts +525 -0
  170. package/tests/editLogEntry.test.ts +112 -0
  171. package/tests/email.test.ts +39 -0
  172. package/tests/fieldDocProgram.test.ts +114 -0
  173. package/tests/logDisplay.fixtures.ts +67 -0
  174. package/tests/logDisplay.test.ts +227 -0
  175. package/tests/noteDoc.test.ts +514 -0
  176. package/tests/richTextHTML.test.ts +185 -0
  177. package/tests/sheetAxisMove.test.ts +352 -0
  178. package/tests/sheetBootstrap.test.ts +1967 -0
  179. package/tests/sheetFeatureReference.test.ts +22 -0
  180. package/tests/sheetFormulaCriteria.test.ts +269 -0
  181. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  182. package/tests/sheetFormulaFunctions.test.ts +538 -0
  183. package/tests/sheetFormulaLanguage.test.ts +361 -0
  184. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  185. package/tests/sheetFormulaParity.test.ts +188 -0
  186. package/tests/sheetFormulaRange.test.ts +167 -0
  187. package/tests/sheetFormulaReference.test.ts +78 -0
  188. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  189. package/tests/sheetFormulaTextDate.test.ts +512 -0
  190. package/tests/sheetSequence.test.ts +22 -0
  191. package/tests/sheetSnapshot.test.ts +134 -0
  192. package/tests/sheetStructureEdit.test.ts +537 -0
  193. package/tests/sheetStructureReferences.test.ts +589 -0
  194. package/tests/workflowLifecycleStatus.test.ts +60 -0
  195. package/tests/workflowLogFingerprint.test.ts +203 -0
  196. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  197. package/tests/workflowProgress.test.ts +180 -0
  198. package/tests/workflowTriggers.test.ts +29 -0
  199. package/tsconfig.json +10 -10
  200. package/vitest.config.ts +8 -0
  201. package/src/constants/log-activityTexts.ts +0 -235
  202. package/src/constants/product.ts +0 -42
  203. package/src/constants/report.ts +0 -44
  204. package/src/schemas/organization.ts +0 -65
  205. package/src/schemas/productsQuery.ts +0 -53
  206. package/src/schemas/reportsQuery.ts +0 -20
  207. package/src/types/product.d.ts +0 -84
  208. package/src/types/report.d.ts +0 -290
  209. package/src/utils/product-calEvent.ts +0 -455
  210. package/src/utils/report.ts +0 -158
@@ -0,0 +1,430 @@
1
+ import { DateTime } from 'luxon';
2
+ import { SHEET_CELL_TEXT_MAX_CHARS } from '../constants/sheet.ts';
3
+ import {
4
+ flattenSheetFormulaArgValues,
5
+ getSheetFormulaBooleanArg,
6
+ getSheetFormulaIntegerArg,
7
+ getSheetFormulaInvalidArgResult,
8
+ getSheetFormulaTextArg,
9
+ getSheetFormulaTextResult,
10
+ getSheetFormulaTextTooLongResult,
11
+ joinSheetFormulaTextPieces,
12
+ type SheetFormulaArgResult,
13
+ } from './sheetFormulaArgs.ts';
14
+ import { findSheetFormulaWildcardTextIndex } from './sheetFormulaCriteria.ts';
15
+ import {
16
+ getSheetFormulaDateTimeValue,
17
+ getSheetFormulaNumericValue,
18
+ getSheetFormulaPureErrorResult,
19
+ getSheetFormulaTextValue,
20
+ isSheetFormulaBlankValue,
21
+ isSheetFormulaRangeLikeValue,
22
+ type SheetFormulaPureEvaluationResult,
23
+ } from './sheetFormulaEvaluation.ts';
24
+ import { formatSheetCellValue, parseSheetNumberFormatPattern, type SheetNumberFormatCellValues } from './sheetNumberFormat.ts';
25
+
26
+ const FILE_CONSTANTS = {
27
+ isoDatePattern: /^\d{4}-\d{2}-\d{2}$/,
28
+ isoDateTimePattern: /^\d{4}-\d{2}-\d{2}T/,
29
+ letterPattern: /\p{L}/u,
30
+ markPattern: /\p{M}/u,
31
+ // TEXT renders month and weekday names in one fixed locale, so client and
32
+ // server (browser and Deno ICU) always agree
33
+ textFormatLocale: 'en-US',
34
+ valueNumberPattern: /^([+-]?)\s*(\$?)\s*((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?\s*(%?)$/i,
35
+ };
36
+
37
+ /*
38
+ * Return the text arguments of a builtin, stopping at the first invalid one.
39
+ */
40
+ function getSheetFormulaTextArgs(name: string, values: unknown[], labels: string[]): SheetFormulaArgResult<string[]> {
41
+ const texts: string[] = [];
42
+ for (let index = 0; index < labels.length; index++) {
43
+ const arg = getSheetFormulaTextArg(name, values[index], labels[index]);
44
+ if (!arg.ok) {
45
+ return arg;
46
+ }
47
+
48
+ texts.push(arg.value);
49
+ }
50
+
51
+ return { ok: true, value: texts };
52
+ }
53
+
54
+ /*
55
+ * Evaluate CONCAT or CONCATENATE: every argument's text, with ranges and
56
+ * arrays flattened row-major and blanks joining as ''.
57
+ */
58
+ export function evaluateSheetFormulaConcatFunction(
59
+ name: 'CONCAT' | 'CONCATENATE',
60
+ values: unknown[],
61
+ ): SheetFormulaPureEvaluationResult {
62
+ return joinSheetFormulaTextPieces(name, flattenSheetFormulaArgValues(values).map(getSheetFormulaTextValue));
63
+ }
64
+
65
+ /*
66
+ * Evaluate TEXTJOIN(delimiter, ignore_empty, text1, ...): the texts of the
67
+ * remaining arguments (ranges flattened) joined by the delimiter, skipping
68
+ * empty texts when ignore_empty is TRUE.
69
+ */
70
+ export function evaluateSheetFormulaTextJoinFunction(values: unknown[]): SheetFormulaPureEvaluationResult {
71
+ const delimiter = getSheetFormulaTextArg('TEXTJOIN', values[0], 'delimiter');
72
+ if (!delimiter.ok) {
73
+ return delimiter.result;
74
+ }
75
+
76
+ const ignoreEmpty = getSheetFormulaBooleanArg('TEXTJOIN', values[1], 'ignore_empty');
77
+ if (!ignoreEmpty.ok) {
78
+ return ignoreEmpty.result;
79
+ }
80
+
81
+ const texts = flattenSheetFormulaArgValues(values.slice(2)).map(getSheetFormulaTextValue);
82
+ return joinSheetFormulaTextPieces('TEXTJOIN', ignoreEmpty.value ? texts.filter(Boolean) : texts, delimiter.value);
83
+ }
84
+
85
+ /*
86
+ * Evaluate LEFT(text, [count=1]) or RIGHT(text, [count=1]); a negative count
87
+ * is INVALID_VALUE.
88
+ */
89
+ export function evaluateSheetFormulaLeftRightFunction(name: 'LEFT' | 'RIGHT', values: unknown[]): SheetFormulaPureEvaluationResult {
90
+ const text = getSheetFormulaTextArg(name, values[0], 'text');
91
+ if (!text.ok) {
92
+ return text.result;
93
+ }
94
+
95
+ const count =
96
+ values.length > 1 ? getSheetFormulaIntegerArg(name, values[1], 'number_of_characters', 0) : { ok: true as const, value: 1 };
97
+ if (!count.ok) {
98
+ return count.result;
99
+ }
100
+
101
+ if (name === 'LEFT') {
102
+ return { value: text.value.slice(0, count.value) };
103
+ }
104
+
105
+ return {
106
+ value: count.value ? text.value.slice(Math.max(0, text.value.length - count.value)) : '',
107
+ };
108
+ }
109
+
110
+ /*
111
+ * Evaluate MID(text, start, count): count characters from the 1-based start.
112
+ */
113
+ export function evaluateSheetFormulaMidFunction(values: unknown[]): SheetFormulaPureEvaluationResult {
114
+ const text = getSheetFormulaTextArg('MID', values[0], 'text');
115
+ if (!text.ok) {
116
+ return text.result;
117
+ }
118
+
119
+ const start = getSheetFormulaIntegerArg('MID', values[1], 'starting_at', 1);
120
+ if (!start.ok) {
121
+ return start.result;
122
+ }
123
+
124
+ const count = getSheetFormulaIntegerArg('MID', values[2], 'extract_length', 0);
125
+ if (!count.ok) {
126
+ return count.result;
127
+ }
128
+
129
+ return {
130
+ value: text.value.slice(start.value - 1, start.value - 1 + count.value),
131
+ };
132
+ }
133
+
134
+ /*
135
+ * Return one text with the first letter of every word upper-cased and the
136
+ * other letters lower-cased. A word starts at the first letter after any
137
+ * non-letter; combining marks continue the current word.
138
+ */
139
+ function getSheetFormulaProperText(text: string) {
140
+ let result = '';
141
+ let inWord = false;
142
+ for (const character of text) {
143
+ if (FILE_CONSTANTS.letterPattern.test(character)) {
144
+ result += inWord ? character.toLowerCase() : character.toUpperCase();
145
+ inWord = true;
146
+ } else {
147
+ result += character;
148
+ inWord = inWord && FILE_CONSTANTS.markPattern.test(character);
149
+ }
150
+ }
151
+
152
+ return result;
153
+ }
154
+
155
+ /*
156
+ * Evaluate one single-text builtin: LEN, UPPER, LOWER, PROPER or TRIM (TRIM
157
+ * removes ASCII spaces at both ends and collapses inner runs to one space).
158
+ */
159
+ export function evaluateSheetFormulaTextTransformFunction(
160
+ name: 'LEN' | 'LOWER' | 'PROPER' | 'TRIM' | 'UPPER',
161
+ values: unknown[],
162
+ ): SheetFormulaPureEvaluationResult {
163
+ const text = getSheetFormulaTextArg(name, values[0], 'text');
164
+ if (!text.ok) {
165
+ return text.result;
166
+ }
167
+
168
+ switch (name) {
169
+ case 'LEN':
170
+ return { value: text.value.length };
171
+ case 'LOWER':
172
+ return getSheetFormulaTextResult(name, text.value.toLowerCase());
173
+ case 'UPPER':
174
+ return getSheetFormulaTextResult(name, text.value.toUpperCase());
175
+ case 'PROPER':
176
+ return getSheetFormulaTextResult(name, getSheetFormulaProperText(text.value));
177
+ default: {
178
+ // Trim ASCII spaces with a linear scan, not a backtracking regex
179
+ // (/ +$/ is quadratic on long interior runs of spaces)
180
+ const value = text.value;
181
+ let start = 0;
182
+ while (start < value.length && value.charCodeAt(start) === 32) {
183
+ start++;
184
+ }
185
+
186
+ let end = value.length;
187
+ while (end > start && value.charCodeAt(end - 1) === 32) {
188
+ end--;
189
+ }
190
+
191
+ return { value: value.slice(start, end).replace(/ {2,}/g, ' ') };
192
+ }
193
+ }
194
+ }
195
+
196
+ /*
197
+ * Return the index of the nth (1-based) non-overlapping occurrence of a
198
+ * search text, or -1 when there are fewer occurrences.
199
+ */
200
+ function getSheetFormulaOccurrenceIndex(text: string, search: string, occurrence: number) {
201
+ let index = -1;
202
+ let from = 0;
203
+ for (let count = 0; count < occurrence; count++) {
204
+ index = text.indexOf(search, from);
205
+ if (index < 0) {
206
+ return -1;
207
+ }
208
+
209
+ from = index + search.length;
210
+ }
211
+
212
+ return index;
213
+ }
214
+
215
+ /*
216
+ * Return the number of non-overlapping occurrences of a search text.
217
+ */
218
+ function countSheetFormulaOccurrences(text: string, search: string) {
219
+ let count = 0;
220
+ for (let index = text.indexOf(search); index >= 0; index = text.indexOf(search, index + search.length)) {
221
+ count++;
222
+ }
223
+
224
+ return count;
225
+ }
226
+
227
+ /*
228
+ * Evaluate SUBSTITUTE(text, search_for, replace_with, [occurrence]): literal,
229
+ * case-sensitive replacement of every occurrence, or only the nth. An empty
230
+ * search text returns the text unchanged. The result length is checked
231
+ * before it is built.
232
+ */
233
+ export function evaluateSheetFormulaSubstituteFunction(values: unknown[]): SheetFormulaPureEvaluationResult {
234
+ const texts = getSheetFormulaTextArgs('SUBSTITUTE', values, ['text_to_search', 'search_for', 'replace_with']);
235
+ if (!texts.ok) {
236
+ return texts.result;
237
+ }
238
+
239
+ const [text, search, replacement] = texts.value;
240
+ const occurrence = values.length > 3 ? getSheetFormulaIntegerArg('SUBSTITUTE', values[3], 'occurrence_number', 1) : null;
241
+ if (occurrence && !occurrence.ok) {
242
+ return occurrence.result;
243
+ }
244
+
245
+ if (!search) {
246
+ return { value: text };
247
+ }
248
+
249
+ if (occurrence) {
250
+ const index = getSheetFormulaOccurrenceIndex(text, search, occurrence.value);
251
+ return index < 0
252
+ ? { value: text }
253
+ : getSheetFormulaTextResult('SUBSTITUTE', text.slice(0, index) + replacement + text.slice(index + search.length));
254
+ }
255
+
256
+ const count = countSheetFormulaOccurrences(text, search);
257
+ return text.length + count * (replacement.length - search.length) > SHEET_CELL_TEXT_MAX_CHARS
258
+ ? getSheetFormulaTextTooLongResult('SUBSTITUTE')
259
+ : { value: text.split(search).join(replacement) };
260
+ }
261
+
262
+ /*
263
+ * Evaluate REPLACE(text, position, length, new_text): replaces length
264
+ * characters from the 1-based position.
265
+ */
266
+ export function evaluateSheetFormulaReplaceFunction(values: unknown[]): SheetFormulaPureEvaluationResult {
267
+ const text = getSheetFormulaTextArg('REPLACE', values[0], 'text');
268
+ if (!text.ok) {
269
+ return text.result;
270
+ }
271
+
272
+ const position = getSheetFormulaIntegerArg('REPLACE', values[1], 'position', 1);
273
+ if (!position.ok) {
274
+ return position.result;
275
+ }
276
+
277
+ const length = getSheetFormulaIntegerArg('REPLACE', values[2], 'length', 0);
278
+ if (!length.ok) {
279
+ return length.result;
280
+ }
281
+
282
+ const newText = getSheetFormulaTextArg('REPLACE', values[3], 'new_text');
283
+ if (!newText.ok) {
284
+ return newText.result;
285
+ }
286
+
287
+ const start = Math.min(position.value - 1, text.value.length);
288
+ return getSheetFormulaTextResult('REPLACE', text.value.slice(0, start) + newText.value + text.value.slice(start + length.value));
289
+ }
290
+
291
+ /*
292
+ * Evaluate FIND (case-sensitive, literal) or SEARCH (case-insensitive, with
293
+ * * ? ~ wildcards): the 1-based position of search_for in the text at or after
294
+ * the start position. Not found is INVALID_VALUE (#VALUE!), as in Excel.
295
+ */
296
+ export function evaluateSheetFormulaFindFunction(name: 'FIND' | 'SEARCH', values: unknown[]): SheetFormulaPureEvaluationResult {
297
+ const texts = getSheetFormulaTextArgs(name, values, ['search_for', 'text_to_search']);
298
+ if (!texts.ok) {
299
+ return texts.result;
300
+ }
301
+
302
+ const [search, text] = texts.value;
303
+ const start = values.length > 2 ? getSheetFormulaIntegerArg(name, values[2], 'starting_at', 1) : { ok: true as const, value: 1 };
304
+ if (!start.ok) {
305
+ return start.result;
306
+ }
307
+
308
+ if (start.value > text.length + 1) {
309
+ return getSheetFormulaPureErrorResult('INVALID_VALUE', `${name} starting_at is past the end of the text.`);
310
+ }
311
+
312
+ const offset = start.value - 1;
313
+ const found =
314
+ name === 'FIND'
315
+ ? { index: text.indexOf(search, offset), ok: true as const }
316
+ : findSheetFormulaWildcardTextIndex(search, text.slice(offset));
317
+ if (!found.ok) {
318
+ return found.result;
319
+ }
320
+
321
+ if (found.index < 0) {
322
+ return getSheetFormulaPureErrorResult('INVALID_VALUE', `${name} did not find "${search.slice(0, 50)}" in the text.`);
323
+ }
324
+
325
+ return { value: (name === 'FIND' ? found.index : found.index + offset) + 1 };
326
+ }
327
+
328
+ /*
329
+ * Return the typed cell values TEXT formats one value as: booleans are not
330
+ * formatted, numbers and numeric text are numbers (blank is 0), ISO dates and
331
+ * datetimes are dates (datetimes pinned to the organization time zone), and
332
+ * other text stays text.
333
+ */
334
+ function getSheetFormulaTextFormatCell(value: unknown, timeZone: string): SheetNumberFormatCellValues | null {
335
+ if (typeof value === 'boolean') {
336
+ return null;
337
+ }
338
+
339
+ const numberValue = isSheetFormulaBlankValue(value) ? 0 : getSheetFormulaNumericValue(value);
340
+ if (numberValue !== null) {
341
+ return { numberValue };
342
+ }
343
+
344
+ const text = String(value).trim();
345
+ if (FILE_CONSTANTS.isoDatePattern.test(text)) {
346
+ return DateTime.fromISO(text).isValid ? { dateValue: text } : { textValue: String(value) };
347
+ }
348
+
349
+ const dateTime = FILE_CONSTANTS.isoDateTimePattern.test(text) ? getSheetFormulaDateTimeValue(text, timeZone) : null;
350
+ return dateTime ? { datetimeValue: dateTime.toISO() } : { textValue: String(value) };
351
+ }
352
+
353
+ /*
354
+ * Evaluate TEXT(value, format): formats a number or ISO date/datetime with a
355
+ * spreadsheet number format pattern through the shared format engine (dates
356
+ * in the organization time zone, English month names). Text is returned
357
+ * unchanged unless the pattern has an @ text section; TRUE/FALSE are returned
358
+ * as text. An unusable pattern is INVALID_VALUE.
359
+ */
360
+ export function evaluateSheetFormulaTextFunction(values: unknown[], timeZone: string): SheetFormulaPureEvaluationResult {
361
+ if (isSheetFormulaRangeLikeValue(values[0])) {
362
+ return getSheetFormulaInvalidArgResult('TEXT requires a single value, not a range.').result;
363
+ }
364
+
365
+ const pattern = getSheetFormulaTextArg('TEXT', values[1], 'format');
366
+ if (!pattern.ok) {
367
+ return pattern.result;
368
+ }
369
+
370
+ const cell = getSheetFormulaTextFormatCell(values[0], timeZone);
371
+ if (!cell || !pattern.value) {
372
+ return { value: cell ? '' : getSheetFormulaTextValue(values[0]) };
373
+ }
374
+
375
+ const parsed = parseSheetNumberFormatPattern(pattern.value);
376
+ if (!parsed) {
377
+ return getSheetFormulaPureErrorResult('INVALID_VALUE', 'TEXT format is not a valid number format pattern.');
378
+ }
379
+
380
+ // A pattern made only of @ text sections formats every value as text
381
+ const formatCell = parsed.sections.every((section) => section.kind === 'text')
382
+ ? { textValue: getSheetFormulaTextValue(values[0]) }
383
+ : cell;
384
+ const formatted = formatSheetCellValue(
385
+ formatCell,
386
+ { numberFormat: { pattern: pattern.value, type: 'CUSTOM' } },
387
+ timeZone,
388
+ FILE_CONSTANTS.textFormatLocale,
389
+ );
390
+ if (formatted !== null) {
391
+ return getSheetFormulaTextResult('TEXT', formatted);
392
+ }
393
+
394
+ return formatCell.textValue !== undefined
395
+ ? { value: formatCell.textValue }
396
+ : getSheetFormulaPureErrorResult('INVALID_VALUE', 'TEXT cannot format this value with the format pattern.');
397
+ }
398
+
399
+ /*
400
+ * Evaluate VALUE(text): a number from numeric text, allowing thousands
401
+ * separators, a leading $, a trailing % (divided by 100), an exponent, and
402
+ * (123) for negatives. Numbers pass through, TRUE/FALSE are 1/0 and blank is
403
+ * 0. Dates and other text are INVALID_VALUE (the dialect has no serials).
404
+ */
405
+ export function evaluateSheetFormulaValueFunction(values: unknown[]): SheetFormulaPureEvaluationResult {
406
+ const [value] = values;
407
+ if (isSheetFormulaRangeLikeValue(value)) {
408
+ return getSheetFormulaInvalidArgResult('VALUE requires a single value, not a range.').result;
409
+ }
410
+
411
+ if (typeof value === 'number' || typeof value === 'boolean') {
412
+ return { value: Number(value) };
413
+ }
414
+
415
+ const text = getSheetFormulaTextValue(value).trim();
416
+ if (!text) {
417
+ return { value: 0 };
418
+ }
419
+
420
+ const negated = /^\(.*\)$/.test(text);
421
+ const match = FILE_CONSTANTS.valueNumberPattern.exec(negated ? text.slice(1, -1).trim() : text);
422
+
423
+ const [, sign, , mantissa, exponent, percent] = match || [];
424
+ const parsed = match ? Number(`${mantissa.replaceAll(',', '')}e${exponent || 0}`) / (percent ? 100 : 1) : Number.NaN;
425
+ if (!Number.isFinite(parsed) || (negated && sign)) {
426
+ return getSheetFormulaPureErrorResult('INVALID_VALUE', 'VALUE requires text that reads as a number.');
427
+ }
428
+
429
+ return { value: (sign === '-') !== negated ? -parsed : parsed };
430
+ }
@@ -0,0 +1,200 @@
1
+ import { parseSheetJournalSeq, sheetJournalSeqIsPositive } from './sheetSequence.ts';
2
+
3
+ export const SHEET_CELLS_JOURNAL_VERSION = 3;
4
+ export const SHEET_COMPUTED_JOURNAL_VERSION = 1;
5
+
6
+ /* The two design-bearing kinds share one payload version on both sides of the
7
+ * wire: the server's open-path SQL and the client's tail applier accept
8
+ * exactly these shapes, and the dense revision walk reads their top-level
9
+ * `designRevision`. */
10
+ export const SHEET_DESIGN_JOURNAL_VERSION = 2;
11
+ export const SHEET_STRUCTURE_JOURNAL_VERSION = 2;
12
+
13
+ /*
14
+ * Wire/journal item for one derived (recalc) write-back. It carries the
15
+ * computed columns of one stored cell and never a user-authored field
16
+ * (rawInput, formulaText, style, format, note) : derived writes may only ever update what they
17
+ * computed. Ids are serialized exactly like $sheetCellFragment so the client
18
+ * can match the item to its confirmed cell by coordinate + id.
19
+ */
20
+ export type SheetComputedCellPayload = {
21
+ id: string;
22
+ sheetTabId: string;
23
+ rowIndex: number;
24
+ columnIndex: number;
25
+ revision: string;
26
+ value: string | null;
27
+ textValue: string | null;
28
+ numberValue: number | null;
29
+ booleanValue: boolean | null;
30
+ dateValue: string | null;
31
+ datetimeValue: string | null;
32
+ errorCode: string | null;
33
+ errorMessage: string | null;
34
+ computedAt: string | null;
35
+ };
36
+
37
+ const FILE_CONSTANTS = {
38
+ computedCellKeys: [
39
+ 'id',
40
+ 'sheetTabId',
41
+ 'rowIndex',
42
+ 'columnIndex',
43
+ 'revision',
44
+ 'value',
45
+ 'textValue',
46
+ 'numberValue',
47
+ 'booleanValue',
48
+ 'dateValue',
49
+ 'datetimeValue',
50
+ 'errorCode',
51
+ 'errorMessage',
52
+ 'computedAt',
53
+ ] as const satisfies readonly (keyof SheetComputedCellPayload)[],
54
+ };
55
+
56
+ /*
57
+ * Return whether one value is a nullable primitive of the given type.
58
+ */
59
+ function isNullableComputedPrimitive(value: unknown, type: 'string' | 'number' | 'boolean'): boolean {
60
+ if (value === null) {
61
+ return true;
62
+ }
63
+ if (type === 'number') {
64
+ return typeof value === 'number' && Number.isFinite(value);
65
+ }
66
+
67
+ return typeof value === type;
68
+ }
69
+
70
+ /*
71
+ * Return whether one unknown value is an exact COMPUTED journal item: every
72
+ * SheetComputedCellPayload key present with the right primitive type, positive
73
+ * coordinates, a canonical positive revision, and NO other key. A payload that
74
+ * smuggles rawInput/formulaText/style/format/note fails closed. When a
75
+ * sheetTabId is supplied the item must belong to that tab.
76
+ */
77
+ export function isSheetComputedJournalCell(value: unknown, sheetTabId?: string | null): value is SheetComputedCellPayload {
78
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
79
+ return false;
80
+ }
81
+ const record = value as Record<string, unknown>;
82
+ const keys = Object.keys(record);
83
+ if (keys.length !== FILE_CONSTANTS.computedCellKeys.length || FILE_CONSTANTS.computedCellKeys.some((key) => !(key in record))) {
84
+ return false;
85
+ }
86
+
87
+ const revision = typeof record.revision === 'string' ? parseSheetJournalSeq(record.revision) : null;
88
+ return (
89
+ typeof record.id === 'string' &&
90
+ Boolean(record.id) &&
91
+ record.id.trim() === record.id &&
92
+ typeof record.sheetTabId === 'string' &&
93
+ Boolean(record.sheetTabId) &&
94
+ (sheetTabId === undefined || sheetTabId === null || record.sheetTabId === sheetTabId) &&
95
+ typeof record.rowIndex === 'number' &&
96
+ Number.isSafeInteger(record.rowIndex) &&
97
+ record.rowIndex >= 1 &&
98
+ typeof record.columnIndex === 'number' &&
99
+ Number.isSafeInteger(record.columnIndex) &&
100
+ record.columnIndex >= 1 &&
101
+ revision !== null &&
102
+ revision === record.revision &&
103
+ sheetJournalSeqIsPositive(revision) &&
104
+ isNullableComputedPrimitive(record.value, 'string') &&
105
+ isNullableComputedPrimitive(record.textValue, 'string') &&
106
+ isNullableComputedPrimitive(record.numberValue, 'number') &&
107
+ isNullableComputedPrimitive(record.booleanValue, 'boolean') &&
108
+ isNullableComputedPrimitive(record.dateValue, 'string') &&
109
+ isNullableComputedPrimitive(record.datetimeValue, 'string') &&
110
+ isNullableComputedPrimitive(record.errorCode, 'string') &&
111
+ isNullableComputedPrimitive(record.errorMessage, 'string') &&
112
+ isNullableComputedPrimitive(record.computedAt, 'string')
113
+ );
114
+ }
115
+
116
+ /*
117
+ * Return whether one journal payload is a replayable v1 COMPUTED payload:
118
+ * {v: 1, cells: [...]} that is neither truncated nor snapshot-forcing. Item
119
+ * validation belongs to the scoped tail validators, which also check the
120
+ * served viewport.
121
+ */
122
+ export function isReplayableSheetComputedJournalPayload(payload: unknown): boolean {
123
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
124
+ return false;
125
+ }
126
+ const record = payload as Record<string, unknown>;
127
+
128
+ return record.v === SHEET_COMPUTED_JOURNAL_VERSION && Array.isArray(record.cells) && !record.truncated && !record.requiresSnapshot;
129
+ }
130
+
131
+ /* One id-stamped journal tombstone, exactly as CELLS rows carry them. */
132
+ export type SheetJournalTombstonePayload = {
133
+ rowIndex: number;
134
+ columnIndex: number;
135
+ id: string | null;
136
+ revision: string | null;
137
+ sheetTabId: string;
138
+ };
139
+
140
+ /*
141
+ * Return whether optional CELLS journal ordering metadata has the exact
142
+ * hard-NEW v3 shape emitted by the authoritative journal writer.
143
+ */
144
+ export function isHardNewSheetCellsJournalOrderedTargetGroups(value: unknown): boolean {
145
+ if (value === undefined) {
146
+ return true;
147
+ }
148
+ if (!Array.isArray(value) || !value.length) {
149
+ return false;
150
+ }
151
+
152
+ const serverSeqs = new Set<string>();
153
+ for (const groupValue of value) {
154
+ if (!groupValue || typeof groupValue !== 'object' || Array.isArray(groupValue)) {
155
+ return false;
156
+ }
157
+ const group = groupValue as Record<string, unknown>;
158
+ const normalizedServerSeq = typeof group.serverSeq === 'string' ? parseSheetJournalSeq(group.serverSeq) : null;
159
+ if (
160
+ Object.keys(group).length !== 2 ||
161
+ !normalizedServerSeq ||
162
+ !sheetJournalSeqIsPositive(normalizedServerSeq) ||
163
+ serverSeqs.has(normalizedServerSeq) ||
164
+ !Array.isArray(group.targets) ||
165
+ !group.targets.length
166
+ ) {
167
+ return false;
168
+ }
169
+ serverSeqs.add(normalizedServerSeq);
170
+
171
+ const coordinates = new Set<string>();
172
+ for (const compactTarget of group.targets) {
173
+ if (!Array.isArray(compactTarget) || compactTarget.length !== 3) {
174
+ return false;
175
+ }
176
+ const [rowIndex, columnIndex, propertyMask] = compactTarget;
177
+ if (
178
+ typeof rowIndex !== 'number' ||
179
+ !Number.isSafeInteger(rowIndex) ||
180
+ rowIndex < 1 ||
181
+ typeof columnIndex !== 'number' ||
182
+ !Number.isSafeInteger(columnIndex) ||
183
+ columnIndex < 1 ||
184
+ typeof propertyMask !== 'number' ||
185
+ !Number.isSafeInteger(propertyMask) ||
186
+ propertyMask < 1 ||
187
+ propertyMask > 31
188
+ ) {
189
+ return false;
190
+ }
191
+ const coordinate = `${rowIndex}:${columnIndex}`;
192
+ if (coordinates.has(coordinate)) {
193
+ return false;
194
+ }
195
+ coordinates.add(coordinate);
196
+ }
197
+ }
198
+
199
+ return true;
200
+ }