@jsb188/mday 1.1.10 → 1.1.11

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 (119) hide show
  1. package/package.json +105 -54
  2. package/src/constants/agentDoc.ts +12 -0
  3. package/src/constants/agentMemory.ts +154 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/campaign.ts +127 -0
  6. package/src/constants/dataTable.ts +35 -9
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +20 -4
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/integration.ts +8 -9
  13. package/src/constants/log.ts +7 -410
  14. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  15. package/src/constants/logTaxonomy.generated.ts +1103 -0
  16. package/src/constants/noteDoc.ts +77 -0
  17. package/src/constants/organization.ts +13 -15
  18. package/src/constants/pageRoute.ts +23 -0
  19. package/src/constants/schedule.ts +220 -0
  20. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  21. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  22. package/src/constants/sheet.ts +154 -6
  23. package/src/constants/sheetRegionSources.generated.ts +578 -0
  24. package/src/constants/square.ts +6 -6
  25. package/src/constants/storage.ts +56 -7
  26. package/src/constants/usage.ts +79 -0
  27. package/src/schemas/editLogEntry.ts +1010 -777
  28. package/src/schemas/fieldDocsQuery.ts +12 -0
  29. package/src/schemas/inboundContact.ts +60 -55
  30. package/src/schemas/logsQuery.ts +55 -49
  31. package/src/schemas/organization.ts +49 -46
  32. package/src/types/account.d.ts +4 -1
  33. package/src/types/agentDoc.d.ts +64 -0
  34. package/src/types/agentMemory.d.ts +74 -0
  35. package/src/types/campaign.d.ts +683 -0
  36. package/src/types/dataTable.d.ts +175 -256
  37. package/src/types/docAccess.d.ts +96 -0
  38. package/src/types/email.d.ts +83 -12
  39. package/src/types/fieldDoc.d.ts +273 -0
  40. package/src/types/inboundContact.d.ts +2 -1
  41. package/src/types/log.d.ts +209 -341
  42. package/src/types/noteDoc.d.ts +86 -0
  43. package/src/types/organization.d.ts +83 -40
  44. package/src/types/pageRoute.d.ts +48 -0
  45. package/src/types/schedule.d.ts +391 -0
  46. package/src/types/sheet.d.ts +862 -30
  47. package/src/types/storage.d.ts +206 -125
  48. package/src/types/usage.d.ts +106 -0
  49. package/src/types/workflow.d.ts +149 -18
  50. package/src/utils/agentDoc.ts +109 -0
  51. package/src/utils/aiChat.ts +26 -0
  52. package/src/utils/campaign.ts +741 -0
  53. package/src/utils/campaignFormEditor.ts +871 -0
  54. package/src/utils/dataTable.ts +425 -410
  55. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  56. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  57. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  58. package/src/utils/dataTableRowDocument.ts +508 -0
  59. package/src/utils/dataTableSource.ts +230 -0
  60. package/src/utils/docAccess.ts +383 -0
  61. package/src/utils/documentName.ts +53 -0
  62. package/src/utils/email.ts +112 -53
  63. package/src/utils/fieldDoc.ts +113 -0
  64. package/src/utils/log.ts +169 -176
  65. package/src/utils/logRegistryValue.ts +90 -0
  66. package/src/utils/logStoreRead.ts +266 -0
  67. package/src/utils/logTaxonomy.ts +76 -0
  68. package/src/utils/logTaxonomyDisplay.ts +439 -0
  69. package/src/utils/noteDoc.ts +827 -0
  70. package/src/utils/organization.ts +510 -91
  71. package/src/utils/pageRoute.ts +71 -0
  72. package/src/utils/schedule.ts +799 -0
  73. package/src/utils/scheduleEvaluation.ts +1994 -0
  74. package/src/utils/scheduleICS.ts +246 -0
  75. package/src/utils/scheduleRuleTemplates.ts +188 -0
  76. package/src/utils/sheet.ts +4842 -39
  77. package/src/utils/sheetAxisMove.ts +830 -0
  78. package/src/utils/sheetBootstrap.ts +1769 -0
  79. package/src/utils/sheetCommand.ts +423 -0
  80. package/src/utils/sheetExport.ts +238 -0
  81. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  82. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  83. package/src/utils/sheetJournal.ts +78 -0
  84. package/src/utils/sheetNumberFormat.ts +1211 -0
  85. package/src/utils/sheetRegion.ts +374 -0
  86. package/src/utils/sheetRegionFilter.ts +1259 -0
  87. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  88. package/src/utils/sheetSequence.ts +148 -0
  89. package/src/utils/sheetSnapshot.ts +992 -0
  90. package/src/utils/sheetStructureEdit.ts +1284 -0
  91. package/src/utils/square.ts +22 -12
  92. package/src/utils/storage.ts +152 -0
  93. package/src/utils/table-route.ts +127 -11
  94. package/src/utils/workflow.ts +191 -23
  95. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  96. package/tests/docAccess.test.ts +525 -0
  97. package/tests/editLogEntry.test.ts +112 -0
  98. package/tests/noteDoc.test.ts +669 -0
  99. package/tests/schedule.test.ts +693 -0
  100. package/tests/scheduleEvaluation.test.ts +1970 -0
  101. package/tests/scheduleICS.test.ts +208 -0
  102. package/tests/scheduleRuleTemplates.test.ts +176 -0
  103. package/tests/scheduleSweepInvariants.test.ts +428 -0
  104. package/tests/sheetAxisMove.test.ts +343 -0
  105. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  106. package/tests/sheetRegionFilter.test.ts +1135 -0
  107. package/tests/sheetSequence.test.ts +41 -0
  108. package/tests/sheetStructureEdit.test.ts +82 -0
  109. package/tsconfig.json +10 -10
  110. package/vitest.config.ts +8 -0
  111. package/src/constants/log-activityTexts.ts +0 -235
  112. package/src/constants/product.ts +0 -42
  113. package/src/constants/report.ts +0 -44
  114. package/src/schemas/productsQuery.ts +0 -53
  115. package/src/schemas/reportsQuery.ts +0 -20
  116. package/src/types/product.d.ts +0 -84
  117. package/src/types/report.d.ts +0 -290
  118. package/src/utils/product-calEvent.ts +0 -455
  119. package/src/utils/report.ts +0 -158
@@ -0,0 +1,914 @@
1
+ import { DateTime } from 'luxon';
2
+ import type { SheetFormulaDateTimeShorthandName } from './sheet.ts';
3
+
4
+ export type SheetFormulaBuiltinFunctionName =
5
+ | 'ABS'
6
+ | 'AVERAGE'
7
+ | 'CEILING'
8
+ | 'COUNT'
9
+ | 'COUNTA'
10
+ | 'DATE'
11
+ | 'DAY'
12
+ | 'FLOOR'
13
+ | 'IF'
14
+ | 'IFERROR'
15
+ | 'IFNA'
16
+ | 'INCLUDES'
17
+ | 'MAX'
18
+ | 'MIN'
19
+ | 'MOD'
20
+ | 'MONTH'
21
+ | 'NOW'
22
+ | 'POWER'
23
+ | 'ROUND'
24
+ | 'ROUNDDOWN'
25
+ | 'ROUNDUP'
26
+ | 'REGEXMATCH'
27
+ | 'SUM'
28
+ | 'TODAY'
29
+ | 'YEAR';
30
+
31
+ export type SheetFormulaPureEvaluationError = {
32
+ code: string;
33
+ message: string;
34
+ };
35
+
36
+ export type SheetFormulaPureEvaluationResult = {
37
+ error?: SheetFormulaPureEvaluationError;
38
+ value: unknown;
39
+ };
40
+
41
+ export type SheetFormulaRangeLikeValue = {
42
+ kind: 'SHEET_RANGE_VALUE';
43
+ values: unknown[];
44
+ };
45
+
46
+ export type SheetFormulaFunctionGuideArg = {
47
+ descriptionI18nKey: string;
48
+ key: string;
49
+ };
50
+
51
+ export type SheetFormulaFunctionGuide = {
52
+ args: readonly SheetFormulaFunctionGuideArg[];
53
+ descriptionI18nKey: string;
54
+ name: SheetFormulaBuiltinFunctionName;
55
+ signature: string;
56
+ };
57
+
58
+ type SheetFormulaValueEntry = {
59
+ fromRange: boolean;
60
+ value: unknown;
61
+ };
62
+
63
+ export const SHEET_FORMULA_BUILTIN_FUNCTION_NAMES: readonly SheetFormulaBuiltinFunctionName[] =
64
+ [
65
+ 'ABS',
66
+ 'AVERAGE',
67
+ 'CEILING',
68
+ 'COUNT',
69
+ 'COUNTA',
70
+ 'DATE',
71
+ 'DAY',
72
+ 'FLOOR',
73
+ 'IF',
74
+ 'IFERROR',
75
+ 'IFNA',
76
+ 'INCLUDES',
77
+ 'MAX',
78
+ 'MIN',
79
+ 'MOD',
80
+ 'MONTH',
81
+ 'NOW',
82
+ 'POWER',
83
+ 'ROUND',
84
+ 'ROUNDDOWN',
85
+ 'ROUNDUP',
86
+ 'REGEXMATCH',
87
+ 'SUM',
88
+ 'TODAY',
89
+ 'YEAR',
90
+ ];
91
+
92
+ export const SHEET_FORMULA_FUNCTION_GUIDES: Partial<
93
+ Record<SheetFormulaBuiltinFunctionName, SheetFormulaFunctionGuide>
94
+ > = {
95
+ IF: {
96
+ args: [
97
+ {
98
+ descriptionI18nKey:
99
+ 'sheet.formula_function_if_arg_condition_description',
100
+ key: 'condition',
101
+ },
102
+ {
103
+ descriptionI18nKey:
104
+ 'sheet.formula_function_if_arg_value_if_true_description',
105
+ key: 'value_if_true',
106
+ },
107
+ {
108
+ descriptionI18nKey:
109
+ 'sheet.formula_function_if_arg_value_if_false_description',
110
+ key: 'value_if_false',
111
+ },
112
+ ],
113
+ descriptionI18nKey: 'sheet.formula_function_if_description',
114
+ name: 'IF',
115
+ signature: 'IF(condition, value_if_true, value_if_false)',
116
+ },
117
+ IFERROR: {
118
+ args: [
119
+ {
120
+ descriptionI18nKey:
121
+ 'sheet.formula_function_iferror_arg_value_description',
122
+ key: 'value',
123
+ },
124
+ {
125
+ descriptionI18nKey:
126
+ 'sheet.formula_function_iferror_arg_fallback_description',
127
+ key: 'fallback',
128
+ },
129
+ ],
130
+ descriptionI18nKey: 'sheet.formula_function_iferror_description',
131
+ name: 'IFERROR',
132
+ signature: 'IFERROR(value, fallback)',
133
+ },
134
+ IFNA: {
135
+ args: [
136
+ {
137
+ descriptionI18nKey: 'sheet.formula_function_ifna_arg_value_description',
138
+ key: 'value',
139
+ },
140
+ {
141
+ descriptionI18nKey:
142
+ 'sheet.formula_function_ifna_arg_fallback_description',
143
+ key: 'fallback',
144
+ },
145
+ ],
146
+ descriptionI18nKey: 'sheet.formula_function_ifna_description',
147
+ name: 'IFNA',
148
+ signature: 'IFNA(value, fallback)',
149
+ },
150
+ INCLUDES: {
151
+ args: [
152
+ {
153
+ descriptionI18nKey:
154
+ 'sheet.formula_function_includes_arg_needle_description',
155
+ key: 'value',
156
+ },
157
+ {
158
+ descriptionI18nKey:
159
+ 'sheet.formula_function_includes_arg_range_description',
160
+ key: 'range',
161
+ },
162
+ {
163
+ descriptionI18nKey:
164
+ 'sheet.formula_function_includes_arg_value_if_true_description',
165
+ key: 'value_if_true',
166
+ },
167
+ {
168
+ descriptionI18nKey:
169
+ 'sheet.formula_function_includes_arg_value_if_false_description',
170
+ key: 'value_if_false',
171
+ },
172
+ ],
173
+ descriptionI18nKey: 'sheet.formula_function_includes_description',
174
+ name: 'INCLUDES',
175
+ signature: 'INCLUDES(value, range, [value_if_true, value_if_false])',
176
+ },
177
+ REGEXMATCH: {
178
+ args: [
179
+ {
180
+ descriptionI18nKey:
181
+ 'sheet.formula_function_regexmatch_arg_range_description',
182
+ key: 'range',
183
+ },
184
+ {
185
+ descriptionI18nKey:
186
+ 'sheet.formula_function_regexmatch_arg_pattern_description',
187
+ key: 'pattern',
188
+ },
189
+ ],
190
+ descriptionI18nKey: 'sheet.formula_function_regexmatch_description',
191
+ name: 'REGEXMATCH',
192
+ signature: 'REGEXMATCH(range, pattern)',
193
+ },
194
+ };
195
+
196
+ const FILE_CONSTANTS = {
197
+ builtinFunctionNameSet: new Set<string>(SHEET_FORMULA_BUILTIN_FUNCTION_NAMES),
198
+ conditionalFunctionNameSet: new Set<string>([
199
+ 'IF',
200
+ 'IFERROR',
201
+ 'IFNA',
202
+ 'INCLUDES',
203
+ ]),
204
+ numericStringPattern: /^[-+]?\d+(?:\.\d+)?$/,
205
+ };
206
+
207
+ /*
208
+ * Return a normalized builtin formula function name.
209
+ */
210
+ export function getSheetFormulaBuiltinFunctionName(
211
+ name: string,
212
+ ): SheetFormulaBuiltinFunctionName | null {
213
+ const normalizedName = name.replace(/^@/, '').toUpperCase();
214
+ return FILE_CONSTANTS.builtinFunctionNameSet.has(normalizedName)
215
+ ? (normalizedName as SheetFormulaBuiltinFunctionName)
216
+ : null;
217
+ }
218
+
219
+ /*
220
+ * Return shared guide metadata for one formula function, when the UI has
221
+ * explicit helper copy for that function.
222
+ */
223
+ export function getSheetFormulaFunctionGuide(
224
+ name: string,
225
+ ): SheetFormulaFunctionGuide | null {
226
+ const normalizedName = getSheetFormulaBuiltinFunctionName(name);
227
+
228
+ return normalizedName
229
+ ? SHEET_FORMULA_FUNCTION_GUIDES[normalizedName] || null
230
+ : null;
231
+ }
232
+
233
+ /*
234
+ * Return whether one builtin function must control evaluation of its arguments.
235
+ */
236
+ export function isSheetFormulaConditionalFunctionName(name: string) {
237
+ const normalizedName = name.replace(/^@/, '').toUpperCase();
238
+ return FILE_CONSTANTS.conditionalFunctionNameSet.has(normalizedName);
239
+ }
240
+
241
+ /*
242
+ * Return whether one formula scalar should be treated as blank.
243
+ */
244
+ export function isSheetFormulaBlankValue(value: unknown) {
245
+ return value === null || value === undefined || value === '';
246
+ }
247
+
248
+ /*
249
+ * Return a string value for formula concatenation and lookups.
250
+ */
251
+ export function getSheetFormulaStringValue(value: unknown) {
252
+ return value === null || value === undefined ? '' : String(value);
253
+ }
254
+
255
+ /*
256
+ * Return a numeric value from a scalar formula value when it can be coerced.
257
+ */
258
+ export function getSheetFormulaNumericValue(value: unknown) {
259
+ if (typeof value === 'number' && Number.isFinite(value)) {
260
+ return value;
261
+ }
262
+
263
+ if (typeof value === 'boolean') {
264
+ return value ? 1 : 0;
265
+ }
266
+
267
+ if (
268
+ typeof value === 'string' &&
269
+ value.trim() &&
270
+ FILE_CONSTANTS.numericStringPattern.test(value.trim())
271
+ ) {
272
+ return Number(value.trim());
273
+ }
274
+
275
+ return null;
276
+ }
277
+
278
+ /*
279
+ * Return a strict numeric value without coercing strings or booleans.
280
+ */
281
+ export function getSheetFormulaStrictNumberValue(value: unknown) {
282
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
283
+ }
284
+
285
+ /*
286
+ * Return a logical boolean value from a formula scalar, or null when unsupported.
287
+ */
288
+ export function getSheetFormulaLogicalBooleanValue(value: unknown) {
289
+ if (typeof value === 'boolean') {
290
+ return value;
291
+ }
292
+
293
+ const numberValue = getSheetFormulaNumericValue(value);
294
+ if (numberValue !== null) {
295
+ return numberValue !== 0;
296
+ }
297
+
298
+ if (typeof value === 'string') {
299
+ const normalized = value.trim().toUpperCase();
300
+ if (normalized === 'TRUE') {
301
+ return true;
302
+ }
303
+
304
+ if (normalized === 'FALSE' || normalized === '') {
305
+ return false;
306
+ }
307
+ }
308
+
309
+ if (value === null || value === undefined) {
310
+ return false;
311
+ }
312
+
313
+ return null;
314
+ }
315
+
316
+ /*
317
+ * Return whether one evaluated formula value is a range-like value.
318
+ */
319
+ export function isSheetFormulaRangeLikeValue(
320
+ value: unknown,
321
+ ): value is SheetFormulaRangeLikeValue {
322
+ return Boolean(
323
+ value &&
324
+ typeof value === 'object' &&
325
+ (value as SheetFormulaRangeLikeValue).kind === 'SHEET_RANGE_VALUE' &&
326
+ Array.isArray((value as SheetFormulaRangeLikeValue).values),
327
+ );
328
+ }
329
+
330
+ /*
331
+ * Return a timezone-aware DateTime for one formula date-like value.
332
+ */
333
+ export function getSheetFormulaDateTimeValue(value: unknown, timeZone: string) {
334
+ if (value instanceof Date && Number.isFinite(value.getTime())) {
335
+ return DateTime.fromJSDate(value, { zone: timeZone });
336
+ }
337
+
338
+ if (typeof value === 'string' && value.trim()) {
339
+ const dateTime = DateTime.fromISO(value.trim(), { zone: timeZone });
340
+ return dateTime.isValid ? dateTime : null;
341
+ }
342
+
343
+ return null;
344
+ }
345
+
346
+ /*
347
+ * Return a canonical sheet date string.
348
+ */
349
+ export function formatSheetFormulaDateValue(dateTime: DateTime) {
350
+ return dateTime.toFormat('yyyy-MM-dd');
351
+ }
352
+
353
+ /*
354
+ * Return the organization-zoned current value for a formula date/time shorthand.
355
+ */
356
+ export function getSheetFormulaDateTimeShorthandValue(
357
+ name: SheetFormulaDateTimeShorthandName,
358
+ now: Date,
359
+ timeZone: string,
360
+ ) {
361
+ const dateTime = DateTime.fromJSDate(now, { zone: timeZone });
362
+
363
+ return name === 'CURRENT_DATE'
364
+ ? formatSheetFormulaDateValue(dateTime)
365
+ : dateTime.toISO();
366
+ }
367
+
368
+ /*
369
+ * Return a stable freshness-key value for one date/time shorthand.
370
+ */
371
+ export function getSheetFormulaDateTimeShorthandKeyValue(
372
+ name: SheetFormulaDateTimeShorthandName,
373
+ now: Date,
374
+ timeZone: string,
375
+ ) {
376
+ const dateTime = DateTime.fromJSDate(now, { zone: timeZone });
377
+
378
+ return name === 'CURRENT_DATE'
379
+ ? formatSheetFormulaDateValue(dateTime)
380
+ : dateTime.toFormat("yyyy-MM-dd'T'HH:mm");
381
+ }
382
+
383
+ /*
384
+ * Return a formula pure evaluation error result.
385
+ */
386
+ export function getSheetFormulaPureErrorResult(
387
+ code: string,
388
+ message: string,
389
+ ): SheetFormulaPureEvaluationResult {
390
+ return {
391
+ error: {
392
+ code,
393
+ message,
394
+ },
395
+ value: code === 'NOT_FOUND' ? '#N/A' : '#ERROR!',
396
+ };
397
+ }
398
+
399
+ /*
400
+ * Return whether one formula error is the spreadsheet not-found error.
401
+ */
402
+ export function isSheetFormulaNotFoundError(
403
+ error?: SheetFormulaPureEvaluationError | null,
404
+ ) {
405
+ return error?.code === 'NOT_FOUND';
406
+ }
407
+
408
+ /*
409
+ * Flatten scalar and range formula values into function argument entries.
410
+ */
411
+ function flattenSheetFormulaValueEntries(values: unknown[]) {
412
+ return values.flatMap((value): SheetFormulaValueEntry[] => {
413
+ if (isSheetFormulaRangeLikeValue(value)) {
414
+ return value.values.map((rangeValue) => ({
415
+ fromRange: true,
416
+ value: rangeValue,
417
+ }));
418
+ }
419
+
420
+ return [
421
+ {
422
+ fromRange: false,
423
+ value,
424
+ },
425
+ ];
426
+ });
427
+ }
428
+
429
+ /*
430
+ * Return numeric entries for aggregate functions, ignoring range blanks and range text.
431
+ */
432
+ function getSheetFormulaAggregateNumericValues(values: unknown[]) {
433
+ const numbers: number[] = [];
434
+ const entries = flattenSheetFormulaValueEntries(values);
435
+ for (const entry of entries) {
436
+ if (isSheetFormulaBlankValue(entry.value)) {
437
+ continue;
438
+ }
439
+
440
+ const numberValue = getSheetFormulaNumericValue(entry.value);
441
+ if (numberValue !== null) {
442
+ numbers.push(numberValue);
443
+ continue;
444
+ }
445
+
446
+ if (!entry.fromRange) {
447
+ return null;
448
+ }
449
+ }
450
+
451
+ return numbers;
452
+ }
453
+
454
+ /*
455
+ * Return nonblank entries for COUNTA.
456
+ */
457
+ function getSheetFormulaCountAValue(values: unknown[]) {
458
+ return flattenSheetFormulaValueEntries(values).filter(
459
+ (entry) => !isSheetFormulaBlankValue(entry.value),
460
+ ).length;
461
+ }
462
+
463
+ /*
464
+ * Return the count of strict numeric values for COUNT.
465
+ */
466
+ function getSheetFormulaCountValue(values: unknown[]) {
467
+ return flattenSheetFormulaValueEntries(values).filter(
468
+ (entry) => getSheetFormulaStrictNumberValue(entry.value) !== null,
469
+ ).length;
470
+ }
471
+
472
+ /*
473
+ * Return scalar numeric function arguments with range values flattened.
474
+ */
475
+ function getSheetFormulaNumericFunctionArgs(
476
+ values: unknown[],
477
+ minCount: number,
478
+ maxCount: number,
479
+ ) {
480
+ const entries = flattenSheetFormulaValueEntries(values).filter(
481
+ (entry) => !isSheetFormulaBlankValue(entry.value),
482
+ );
483
+ if (entries.length < minCount || entries.length > maxCount) {
484
+ return null;
485
+ }
486
+
487
+ const numbers = entries.map((entry) =>
488
+ getSheetFormulaNumericValue(entry.value),
489
+ );
490
+ return numbers.every((value) => value !== null)
491
+ ? (numbers as number[])
492
+ : null;
493
+ }
494
+
495
+ /*
496
+ * Evaluate an aggregate formula function from already-evaluated argument values.
497
+ */
498
+ export function evaluateSheetFormulaAggregateFunction(
499
+ name: string,
500
+ values: unknown[],
501
+ ): SheetFormulaPureEvaluationResult | null {
502
+ if (!['AVERAGE', 'COUNT', 'COUNTA', 'MAX', 'MIN', 'SUM'].includes(name)) {
503
+ return null;
504
+ }
505
+
506
+ if (name === 'COUNT') {
507
+ return {
508
+ value: getSheetFormulaCountValue(values),
509
+ };
510
+ }
511
+
512
+ if (name === 'COUNTA') {
513
+ return {
514
+ value: getSheetFormulaCountAValue(values),
515
+ };
516
+ }
517
+
518
+ const numbers = getSheetFormulaAggregateNumericValues(values);
519
+ if (!numbers) {
520
+ return getSheetFormulaPureErrorResult(
521
+ 'INVALID_FORMULA',
522
+ 'Formula function requires numeric values.',
523
+ );
524
+ }
525
+
526
+ if (name === 'SUM') {
527
+ return {
528
+ value: numbers.reduce((sum, value) => sum + value, 0),
529
+ };
530
+ }
531
+
532
+ if (name === 'AVERAGE') {
533
+ return numbers.length
534
+ ? {
535
+ value:
536
+ numbers.reduce((sum, value) => sum + value, 0) / numbers.length,
537
+ }
538
+ : getSheetFormulaPureErrorResult(
539
+ 'DIVIDE_BY_ZERO',
540
+ 'Formula average requires at least one numeric value.',
541
+ );
542
+ }
543
+
544
+ if (name === 'MIN') {
545
+ return numbers.length
546
+ ? {
547
+ value: Math.min(...numbers),
548
+ }
549
+ : getSheetFormulaPureErrorResult(
550
+ 'INVALID_FORMULA',
551
+ 'Formula function requires numeric values.',
552
+ );
553
+ }
554
+
555
+ if (name === 'MAX') {
556
+ return numbers.length
557
+ ? {
558
+ value: Math.max(...numbers),
559
+ }
560
+ : getSheetFormulaPureErrorResult(
561
+ 'INVALID_FORMULA',
562
+ 'Formula function requires numeric values.',
563
+ );
564
+ }
565
+
566
+ return null;
567
+ }
568
+
569
+ /*
570
+ * Return a rounded number at a decimal precision.
571
+ */
572
+ function roundSheetFormulaNumber(value: number, places = 0) {
573
+ const factor = 10 ** Math.trunc(places);
574
+ return Math.round((value + Number.EPSILON) * factor) / factor;
575
+ }
576
+
577
+ /*
578
+ * Return a number rounded away from zero at a decimal precision.
579
+ */
580
+ function roundUpSheetFormulaNumber(value: number, places = 0) {
581
+ const factor = 10 ** Math.trunc(places);
582
+ return (Math.sign(value || 1) * Math.ceil(Math.abs(value) * factor)) / factor;
583
+ }
584
+
585
+ /*
586
+ * Return a number rounded toward zero at a decimal precision.
587
+ */
588
+ function roundDownSheetFormulaNumber(value: number, places = 0) {
589
+ const factor = 10 ** Math.trunc(places);
590
+ return (
591
+ (Math.sign(value || 1) * Math.floor(Math.abs(value) * factor)) / factor
592
+ );
593
+ }
594
+
595
+ /*
596
+ * Evaluate a numeric formula function from already-evaluated argument values.
597
+ */
598
+ export function evaluateSheetFormulaMathFunction(
599
+ name: string,
600
+ values: unknown[],
601
+ ): SheetFormulaPureEvaluationResult | null {
602
+ const unaryArgs = ['ABS'].includes(name)
603
+ ? getSheetFormulaNumericFunctionArgs(values, 1, 1)
604
+ : null;
605
+ if (unaryArgs) {
606
+ return {
607
+ value: Math.abs(unaryArgs[0]),
608
+ };
609
+ }
610
+
611
+ const roundedArgs = ['ROUND', 'ROUNDUP', 'ROUNDDOWN'].includes(name)
612
+ ? getSheetFormulaNumericFunctionArgs(values, 1, 2)
613
+ : null;
614
+ if (roundedArgs) {
615
+ const places = roundedArgs[1] || 0;
616
+ const roundFn =
617
+ name === 'ROUNDUP'
618
+ ? roundUpSheetFormulaNumber
619
+ : name === 'ROUNDDOWN'
620
+ ? roundDownSheetFormulaNumber
621
+ : roundSheetFormulaNumber;
622
+
623
+ return {
624
+ value: roundFn(roundedArgs[0], places),
625
+ };
626
+ }
627
+
628
+ const ceilingFloorArgs = ['CEILING', 'FLOOR'].includes(name)
629
+ ? getSheetFormulaNumericFunctionArgs(values, 1, 2)
630
+ : null;
631
+ if (ceilingFloorArgs) {
632
+ const significance = ceilingFloorArgs[1] || 1;
633
+ if (significance === 0) {
634
+ return getSheetFormulaPureErrorResult(
635
+ 'DIVIDE_BY_ZERO',
636
+ 'Formula significance cannot be zero.',
637
+ );
638
+ }
639
+
640
+ return {
641
+ value:
642
+ (name === 'CEILING' ? Math.ceil : Math.floor)(
643
+ ceilingFloorArgs[0] / significance,
644
+ ) * significance,
645
+ };
646
+ }
647
+
648
+ const binaryArgs = ['MOD', 'POWER'].includes(name)
649
+ ? getSheetFormulaNumericFunctionArgs(values, 2, 2)
650
+ : null;
651
+ if (binaryArgs && name === 'MOD') {
652
+ if (binaryArgs[1] === 0) {
653
+ return getSheetFormulaPureErrorResult(
654
+ 'DIVIDE_BY_ZERO',
655
+ 'Formula cannot divide by zero.',
656
+ );
657
+ }
658
+
659
+ return {
660
+ value: ((binaryArgs[0] % binaryArgs[1]) + binaryArgs[1]) % binaryArgs[1],
661
+ };
662
+ }
663
+
664
+ if (binaryArgs && name === 'POWER') {
665
+ return {
666
+ value: binaryArgs[0] ** binaryArgs[1],
667
+ };
668
+ }
669
+
670
+ return [
671
+ 'ABS',
672
+ 'CEILING',
673
+ 'FLOOR',
674
+ 'MOD',
675
+ 'POWER',
676
+ 'ROUND',
677
+ 'ROUNDDOWN',
678
+ 'ROUNDUP',
679
+ ].includes(name)
680
+ ? getSheetFormulaPureErrorResult(
681
+ 'INVALID_FORMULA',
682
+ 'Formula function requires numeric values.',
683
+ )
684
+ : null;
685
+ }
686
+
687
+ /*
688
+ * Evaluate a date or time formula function from already-evaluated argument values.
689
+ */
690
+ export function evaluateSheetFormulaDateFunction(
691
+ name: string,
692
+ values: unknown[],
693
+ timeZone: string,
694
+ now: Date,
695
+ ): SheetFormulaPureEvaluationResult | null {
696
+ if (name === 'TODAY') {
697
+ return values.length
698
+ ? getSheetFormulaPureErrorResult(
699
+ 'INVALID_FORMULA',
700
+ 'TODAY does not accept arguments.',
701
+ )
702
+ : {
703
+ value: formatSheetFormulaDateValue(
704
+ DateTime.fromJSDate(now, { zone: timeZone }),
705
+ ),
706
+ };
707
+ }
708
+
709
+ if (name === 'NOW') {
710
+ return values.length
711
+ ? getSheetFormulaPureErrorResult(
712
+ 'INVALID_FORMULA',
713
+ 'NOW does not accept arguments.',
714
+ )
715
+ : {
716
+ value: DateTime.fromJSDate(now, { zone: timeZone }).toISO(),
717
+ };
718
+ }
719
+
720
+ if (name === 'DATE') {
721
+ const args = getSheetFormulaNumericFunctionArgs(values, 3, 3);
722
+ const dateTime = args
723
+ ? DateTime.fromObject(
724
+ {
725
+ year: Math.trunc(args[0]),
726
+ month: Math.trunc(args[1]),
727
+ day: Math.trunc(args[2]),
728
+ },
729
+ {
730
+ zone: timeZone,
731
+ },
732
+ )
733
+ : null;
734
+
735
+ return dateTime?.isValid
736
+ ? {
737
+ value: formatSheetFormulaDateValue(dateTime),
738
+ }
739
+ : getSheetFormulaPureErrorResult(
740
+ 'INVALID_FORMULA',
741
+ 'DATE requires valid year, month, and day values.',
742
+ );
743
+ }
744
+
745
+ if (['YEAR', 'MONTH', 'DAY'].includes(name)) {
746
+ const entries = flattenSheetFormulaValueEntries(values).filter(
747
+ (entry) => !isSheetFormulaBlankValue(entry.value),
748
+ );
749
+ const dateTime =
750
+ entries.length === 1
751
+ ? getSheetFormulaDateTimeValue(entries[0].value, timeZone)
752
+ : null;
753
+ if (!dateTime?.isValid) {
754
+ return getSheetFormulaPureErrorResult(
755
+ 'INVALID_FORMULA',
756
+ 'Formula date function requires one date value.',
757
+ );
758
+ }
759
+
760
+ return {
761
+ value:
762
+ name === 'YEAR'
763
+ ? dateTime.year
764
+ : name === 'MONTH'
765
+ ? dateTime.month
766
+ : dateTime.day,
767
+ };
768
+ }
769
+
770
+ return null;
771
+ }
772
+
773
+ /*
774
+ * Return whether two formula scalars are equal using '=' comparison semantics:
775
+ * numeric compare when both coerce to numbers, otherwise string compare. Shared
776
+ * so range membership matches the binary '=' operator in both evaluators.
777
+ */
778
+ export function sheetFormulaScalarValuesEqual(
779
+ leftValue: unknown,
780
+ rightValue: unknown,
781
+ ) {
782
+ const leftNumber = getSheetFormulaNumericValue(leftValue);
783
+ const rightNumber = getSheetFormulaNumericValue(rightValue);
784
+ if (leftNumber !== null && rightNumber !== null) {
785
+ return leftNumber === rightNumber;
786
+ }
787
+
788
+ return (
789
+ getSheetFormulaStringValue(leftValue) ===
790
+ getSheetFormulaStringValue(rightValue)
791
+ );
792
+ }
793
+
794
+ /*
795
+ * Return whether a range value contains one scalar needle. Blank cells and a
796
+ * blank needle never match. Range entries are already resolved scalars, so this
797
+ * works over formula-fed and data-table region cells alike.
798
+ */
799
+ export function sheetFormulaRangeIncludesValue(
800
+ rangeValue: SheetFormulaRangeLikeValue,
801
+ needle: unknown,
802
+ ) {
803
+ if (isSheetFormulaBlankValue(needle)) {
804
+ return false;
805
+ }
806
+
807
+ return rangeValue.values.some(
808
+ (value) =>
809
+ !isSheetFormulaBlankValue(value) &&
810
+ sheetFormulaScalarValuesEqual(value, needle),
811
+ );
812
+ }
813
+
814
+ /*
815
+ * Return a case-insensitive RegExp for one search pattern, or null when the
816
+ * pattern is not valid regex (the caller falls back to substring matching).
817
+ */
818
+ function getSheetFormulaRegexMatchRegExp(pattern: string): RegExp | null {
819
+ try {
820
+ return new RegExp(pattern, 'i');
821
+ } catch {
822
+ return null;
823
+ }
824
+ }
825
+
826
+ /*
827
+ * Return the first range value (row-major) whose string form matches the search
828
+ * pattern, or a NOT_FOUND result when nothing matches (so IFNA can catch it).
829
+ */
830
+ function evaluateSheetFormulaRegexMatchFunction(
831
+ values: unknown[],
832
+ ): SheetFormulaPureEvaluationResult {
833
+ if (values.length !== 2) {
834
+ return getSheetFormulaPureErrorResult(
835
+ 'INVALID_FORMULA',
836
+ 'REGEXMATCH requires a range and a search pattern.',
837
+ );
838
+ }
839
+
840
+ const [rangeValue, patternValue] = values;
841
+ if (!isSheetFormulaRangeLikeValue(rangeValue)) {
842
+ return getSheetFormulaPureErrorResult(
843
+ 'INVALID_FORMULA',
844
+ 'REGEXMATCH requires a cell range as its first argument.',
845
+ );
846
+ }
847
+
848
+ if (
849
+ isSheetFormulaRangeLikeValue(patternValue) ||
850
+ isSheetFormulaBlankValue(patternValue)
851
+ ) {
852
+ return getSheetFormulaPureErrorResult(
853
+ 'INVALID_FORMULA',
854
+ 'REGEXMATCH requires a search pattern as its second argument.',
855
+ );
856
+ }
857
+
858
+ const pattern = getSheetFormulaStringValue(patternValue);
859
+ const regExp = getSheetFormulaRegexMatchRegExp(pattern);
860
+ const substringNeedle = pattern.toLowerCase();
861
+ for (const value of rangeValue.values) {
862
+ if (isSheetFormulaBlankValue(value)) {
863
+ continue;
864
+ }
865
+
866
+ const text = getSheetFormulaStringValue(value);
867
+ const matched = regExp
868
+ ? regExp.test(text)
869
+ : text.toLowerCase().includes(substringNeedle);
870
+ if (matched) {
871
+ return {
872
+ value,
873
+ };
874
+ }
875
+ }
876
+
877
+ return getSheetFormulaPureErrorResult(
878
+ 'NOT_FOUND',
879
+ 'REGEXMATCH found no matching value.',
880
+ );
881
+ }
882
+
883
+ /*
884
+ * Evaluate a lookup formula function from already-evaluated argument values.
885
+ */
886
+ export function evaluateSheetFormulaLookupFunction(
887
+ name: string,
888
+ values: unknown[],
889
+ ): SheetFormulaPureEvaluationResult | null {
890
+ return name === 'REGEXMATCH'
891
+ ? evaluateSheetFormulaRegexMatchFunction(values)
892
+ : null;
893
+ }
894
+
895
+ /*
896
+ * Evaluate one eager builtin formula function from already-evaluated argument values.
897
+ */
898
+ export function evaluateSheetFormulaEagerBuiltinFunction(
899
+ name: string,
900
+ values: unknown[],
901
+ timeZone: string,
902
+ now: Date,
903
+ ) {
904
+ return (
905
+ evaluateSheetFormulaAggregateFunction(name, values) ||
906
+ evaluateSheetFormulaLookupFunction(name, values) ||
907
+ evaluateSheetFormulaDateFunction(name, values, timeZone, now) ||
908
+ evaluateSheetFormulaMathFunction(name, values) ||
909
+ getSheetFormulaPureErrorResult(
910
+ 'UNKNOWN_FUNCTION',
911
+ 'Formula function is not supported.',
912
+ )
913
+ );
914
+ }