@jsb188/mday 1.1.2

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 (202) hide show
  1. package/package.json +142 -0
  2. package/src/constants/agentMemory.ts +166 -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 +22 -0
  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 +146 -0
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/inboundContact.ts +8 -0
  17. package/src/constants/integration.ts +13 -0
  18. package/src/constants/log.ts +21 -0
  19. package/src/constants/logDisplay/README.md +88 -0
  20. package/src/constants/logDisplay/defaults.ts +39 -0
  21. package/src/constants/logDisplay/index.ts +27 -0
  22. package/src/constants/logDisplay/operations/arable.ts +16 -0
  23. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  24. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  25. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  26. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  27. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  28. package/src/constants/logTaxonomy.generated.ts +2199 -0
  29. package/src/constants/noteDoc.ts +77 -0
  30. package/src/constants/organization.ts +60 -0
  31. package/src/constants/pageRoute.ts +23 -0
  32. package/src/constants/qrCode.ts +30 -0
  33. package/src/constants/sheet.ts +132 -0
  34. package/src/constants/sms.ts +18 -0
  35. package/src/constants/square.ts +16 -0
  36. package/src/constants/storage.ts +85 -0
  37. package/src/constants/usage.ts +82 -0
  38. package/src/constants/workflowSteps.ts +60 -0
  39. package/src/schemas/editLogEntry.ts +879 -0
  40. package/src/schemas/inboundContact.ts +77 -0
  41. package/src/schemas/logsQuery.ts +93 -0
  42. package/src/types/account.d.ts +81 -0
  43. package/src/types/agentMemory.d.ts +100 -0
  44. package/src/types/agentNote.d.ts +441 -0
  45. package/src/types/billing.d.ts +537 -0
  46. package/src/types/campaign.d.ts +1533 -0
  47. package/src/types/contact.d.ts +15 -0
  48. package/src/types/csvExport.d.ts +213 -0
  49. package/src/types/dataAnalysis.d.ts +44 -0
  50. package/src/types/dataTable.d.ts +159 -0
  51. package/src/types/definitionElement.d.ts +35 -0
  52. package/src/types/docAccess.d.ts +96 -0
  53. package/src/types/dt.d.ts +257 -0
  54. package/src/types/email.d.ts +231 -0
  55. package/src/types/emailReplyReport.d.ts +76 -0
  56. package/src/types/fieldDoc.d.ts +702 -0
  57. package/src/types/fieldDocContract.d.ts +90 -0
  58. package/src/types/inboundContact.d.ts +65 -0
  59. package/src/types/integration.d.ts +42 -0
  60. package/src/types/log.d.ts +338 -0
  61. package/src/types/logDisplay.types.ts +85 -0
  62. package/src/types/organization.d.ts +350 -0
  63. package/src/types/pageRoute.d.ts +48 -0
  64. package/src/types/qrCode.d.ts +96 -0
  65. package/src/types/richText.d.ts +81 -0
  66. package/src/types/sheet.d.ts +847 -0
  67. package/src/types/sms.d.ts +38 -0
  68. package/src/types/storage.d.ts +481 -0
  69. package/src/types/usage.d.ts +106 -0
  70. package/src/types/workflow.d.ts +435 -0
  71. package/src/utils/agentMemory.ts +15 -0
  72. package/src/utils/agentNote.ts +850 -0
  73. package/src/utils/aiChat.ts +43 -0
  74. package/src/utils/aiChatWork.ts +64 -0
  75. package/src/utils/billing.ts +37 -0
  76. package/src/utils/campaign.ts +1173 -0
  77. package/src/utils/campaignAI.ts +72 -0
  78. package/src/utils/campaignAccess.ts +239 -0
  79. package/src/utils/campaignEmail.ts +601 -0
  80. package/src/utils/campaignEmailCompiler.ts +372 -0
  81. package/src/utils/campaignEmailImages.ts +60 -0
  82. package/src/utils/campaignEmailStyles.ts +544 -0
  83. package/src/utils/campaignLifecycle.ts +104 -0
  84. package/src/utils/campaignPreview.ts +285 -0
  85. package/src/utils/contact.ts +50 -0
  86. package/src/utils/csvExport.ts +19 -0
  87. package/src/utils/dataTable.ts +311 -0
  88. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  89. package/src/utils/dataTableRelativeDate.ts +447 -0
  90. package/src/utils/definitionElement.ts +84 -0
  91. package/src/utils/docAccess.ts +383 -0
  92. package/src/utils/documentName.ts +53 -0
  93. package/src/utils/email.ts +379 -0
  94. package/src/utils/emailReplyReport.test.ts +187 -0
  95. package/src/utils/emailReplyReport.ts +143 -0
  96. package/src/utils/fieldDoc.ts +157 -0
  97. package/src/utils/fieldDocAnswers.ts +128 -0
  98. package/src/utils/fieldDocDefaults.ts +36 -0
  99. package/src/utils/fieldDocProgram.ts +36 -0
  100. package/src/utils/fieldDocSummary.ts +30 -0
  101. package/src/utils/log.ts +357 -0
  102. package/src/utils/logDisplay.helpers.ts +177 -0
  103. package/src/utils/logDisplay.ts +87 -0
  104. package/src/utils/logRegistryValue.ts +90 -0
  105. package/src/utils/logStoreRead.ts +262 -0
  106. package/src/utils/logTaxonomy.helpers.ts +17 -0
  107. package/src/utils/logTaxonomy.ts +76 -0
  108. package/src/utils/logTaxonomyDisplay.ts +395 -0
  109. package/src/utils/noteDoc.ts +609 -0
  110. package/src/utils/organization.ts +669 -0
  111. package/src/utils/pageRoute.ts +71 -0
  112. package/src/utils/qrCode.helpers.ts +189 -0
  113. package/src/utils/qrCode.test.ts +519 -0
  114. package/src/utils/qrCode.ts +273 -0
  115. package/src/utils/richTextHTML.ts +385 -0
  116. package/src/utils/sheet.ts +262 -0
  117. package/src/utils/sheetAxisMove.ts +616 -0
  118. package/src/utils/sheetBootstrap.ts +1402 -0
  119. package/src/utils/sheetCellLiteral.ts +101 -0
  120. package/src/utils/sheetCommand.ts +358 -0
  121. package/src/utils/sheetDesign.ts +705 -0
  122. package/src/utils/sheetExport.ts +186 -0
  123. package/src/utils/sheetFeatureReference.ts +183 -0
  124. package/src/utils/sheetFormulaArgs.ts +168 -0
  125. package/src/utils/sheetFormulaCompile.ts +475 -0
  126. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  127. package/src/utils/sheetFormulaCriteria.ts +656 -0
  128. package/src/utils/sheetFormulaDate.ts +444 -0
  129. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  130. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  131. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  132. package/src/utils/sheetFormulaLogical.ts +116 -0
  133. package/src/utils/sheetFormulaLookup.ts +488 -0
  134. package/src/utils/sheetFormulaMath.ts +48 -0
  135. package/src/utils/sheetFormulaParser.ts +729 -0
  136. package/src/utils/sheetFormulaRange.ts +330 -0
  137. package/src/utils/sheetFormulaReference.ts +703 -0
  138. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  139. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  140. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  141. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  142. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  143. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  144. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  145. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  146. package/src/utils/sheetFormulaText.ts +430 -0
  147. package/src/utils/sheetJournal.ts +200 -0
  148. package/src/utils/sheetNumberFormat.ts +1012 -0
  149. package/src/utils/sheetPreview.ts +68 -0
  150. package/src/utils/sheetSequence.ts +118 -0
  151. package/src/utils/sheetSnapshot.ts +739 -0
  152. package/src/utils/sheetStructureEdit.ts +914 -0
  153. package/src/utils/sheetStructureReferences.ts +389 -0
  154. package/src/utils/square.ts +32 -0
  155. package/src/utils/storage.ts +198 -0
  156. package/src/utils/table-route.ts +262 -0
  157. package/src/utils/time.ts +12 -0
  158. package/src/utils/workflow.ts +506 -0
  159. package/src/utils/workflowLogFingerprint.ts +302 -0
  160. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  161. package/src/utils/workflowProgress.ts +280 -0
  162. package/src/utils/workflowTriggers.ts +61 -0
  163. package/tests/agentNote.test.ts +395 -0
  164. package/tests/campaignAI.test.ts +119 -0
  165. package/tests/campaignAccess.test.ts +239 -0
  166. package/tests/campaignEmail.test.ts +441 -0
  167. package/tests/campaignLifecycle.test.ts +134 -0
  168. package/tests/campaignPublication.test.ts +309 -0
  169. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  170. package/tests/dataTableRelativeDate.test.ts +412 -0
  171. package/tests/docAccess.test.ts +525 -0
  172. package/tests/editLogEntry.test.ts +112 -0
  173. package/tests/email.test.ts +39 -0
  174. package/tests/fieldDocProgram.test.ts +114 -0
  175. package/tests/logDisplay.fixtures.ts +67 -0
  176. package/tests/logDisplay.test.ts +227 -0
  177. package/tests/noteDoc.test.ts +514 -0
  178. package/tests/richTextHTML.test.ts +185 -0
  179. package/tests/sheetAxisMove.test.ts +352 -0
  180. package/tests/sheetBootstrap.test.ts +1967 -0
  181. package/tests/sheetFeatureReference.test.ts +22 -0
  182. package/tests/sheetFormulaCriteria.test.ts +269 -0
  183. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  184. package/tests/sheetFormulaFunctions.test.ts +538 -0
  185. package/tests/sheetFormulaLanguage.test.ts +361 -0
  186. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  187. package/tests/sheetFormulaParity.test.ts +188 -0
  188. package/tests/sheetFormulaRange.test.ts +167 -0
  189. package/tests/sheetFormulaReference.test.ts +78 -0
  190. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  191. package/tests/sheetFormulaTextDate.test.ts +512 -0
  192. package/tests/sheetSequence.test.ts +22 -0
  193. package/tests/sheetSnapshot.test.ts +134 -0
  194. package/tests/sheetStructureEdit.test.ts +537 -0
  195. package/tests/sheetStructureReferences.test.ts +589 -0
  196. package/tests/workflowLifecycleStatus.test.ts +60 -0
  197. package/tests/workflowLogFingerprint.test.ts +203 -0
  198. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  199. package/tests/workflowProgress.test.ts +180 -0
  200. package/tests/workflowTriggers.test.ts +29 -0
  201. package/tsconfig.json +12 -0
  202. package/vitest.config.ts +8 -0
@@ -0,0 +1,186 @@
1
+ import type { SheetCellFormatObj, SheetExportFormatEnum } from '../types/sheet.d.ts';
2
+ import { getSheetCellFormattedDisplayValue, type SheetNumberFormatCellValues } from './sheetNumberFormat.ts';
3
+
4
+ const FILE_CONSTANTS = {
5
+ // Characters that break file names across OSes/browsers plus control chars
6
+ fileNameIllegalChars: /[\\/:*?"<>|\u0000-\u001F]/g,
7
+ // Characters Excel forbids inside worksheet (tab) names
8
+ tabNameIllegalChars: /[\\/:?*[\]]/g,
9
+ maxFileNameLength: 120,
10
+ // Hard Excel limit for worksheet names
11
+ maxTabNameLength: 31,
12
+ contentTypes: {
13
+ CSV: 'text/csv',
14
+ TSV: 'text/tab-separated-values',
15
+ XLSX: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
16
+ PDF: 'application/pdf',
17
+ } as Record<SheetExportFormatEnum, string>,
18
+ };
19
+
20
+ /*
21
+ * Minimal cell shape the export display logic reads; both SheetCellGQL rows
22
+ * (client) and raw sheet_cells DB rows (server) satisfy it structurally.
23
+ */
24
+ export interface SheetExportCellValues extends SheetNumberFormatCellValues {
25
+ value?: any;
26
+ }
27
+
28
+ /*
29
+ * Return a date-like cell value as an ISO string, mirroring what the client
30
+ * receives over GraphQL. DB rows carry JS Date objects; date-only values keep
31
+ * just the calendar date.
32
+ */
33
+ function getSheetExportRawDateString(value: Date | string, isDateOnly: boolean): string {
34
+ if (value instanceof Date) {
35
+ const iso = value.toISOString();
36
+ return isDateOnly ? iso.slice(0, 10) : iso;
37
+ }
38
+
39
+ return String(value);
40
+ }
41
+
42
+ /*
43
+ * Return the raw display string for one sheet cell, mirroring the fallback
44
+ * order of the canvas renderer (getSheetCanvasCellRawDisplayValue in
45
+ * @jsb188/sheet libs/sheet-utils.ts) but tolerating raw DB rows.
46
+ */
47
+ function getSheetCellExportRawDisplayValue(cell?: SheetExportCellValues | null): string {
48
+ if (!cell) {
49
+ return '';
50
+ }
51
+
52
+ if (!cell.formulaText && cell.rawInput !== null && cell.rawInput !== undefined) {
53
+ return String(cell.rawInput);
54
+ }
55
+
56
+ if (cell.textValue !== null && cell.textValue !== undefined) {
57
+ return String(cell.textValue);
58
+ }
59
+
60
+ if (cell.numberValue !== null && cell.numberValue !== undefined) {
61
+ return String(cell.numberValue);
62
+ }
63
+
64
+ if (cell.booleanValue !== null && cell.booleanValue !== undefined) {
65
+ return cell.booleanValue ? 'TRUE' : 'FALSE';
66
+ }
67
+
68
+ if (cell.dateValue) {
69
+ return getSheetExportRawDateString(cell.dateValue, true);
70
+ }
71
+
72
+ if (cell.datetimeValue) {
73
+ return getSheetExportRawDateString(cell.datetimeValue, false);
74
+ }
75
+
76
+ if (cell.value !== null && cell.value !== undefined) {
77
+ return typeof cell.value === 'string' ? cell.value : JSON.stringify(cell.value);
78
+ }
79
+
80
+ return '';
81
+ }
82
+
83
+ /*
84
+ * MAIN ENTRY: return the user-facing display string for one sheet cell for
85
+ * file exports, applying the shared explicit-format engine first and falling
86
+ * back to the same raw display order the canvas uses.
87
+ */
88
+ export function getSheetCellExportDisplayValue(
89
+ cell: SheetExportCellValues | null | undefined,
90
+ resolvedFormat?: SheetCellFormatObj | null,
91
+ timeZone?: string | null,
92
+ ): string {
93
+ const rawDisplayValue = getSheetCellExportRawDisplayValue(cell);
94
+
95
+ if (!cell) {
96
+ return rawDisplayValue;
97
+ }
98
+
99
+ return getSheetCellFormattedDisplayValue(cell, resolvedFormat, timeZone) ?? rawDisplayValue;
100
+ }
101
+
102
+ /*
103
+ * Return one field quoted per RFC 4180 when it contains the delimiter, a
104
+ * quote, or a line break; embedded quotes are doubled.
105
+ */
106
+ function getSheetExportDelimitedField(value: string, delimiter: string): string {
107
+ if (value.includes(delimiter) || value.includes('"') || value.includes('\n') || value.includes('\r')) {
108
+ return `"${value.replaceAll('"', '""')}"`;
109
+ }
110
+
111
+ return value;
112
+ }
113
+
114
+ /*
115
+ * Serialize a dense display-value matrix into delimited text (CSV/TSV) with
116
+ * RFC 4180 quoting and CRLF line endings.
117
+ */
118
+ export function buildSheetDelimitedText(matrix: string[][], delimiter: ',' | '\t'): string {
119
+ return matrix.map((row) => row.map((value) => getSheetExportDelimitedField(value, delimiter)).join(delimiter)).join('\r\n');
120
+ }
121
+
122
+ /*
123
+ * Return the lowercase file extension for one export format.
124
+ */
125
+ export function getSheetExportFileExtension(format: SheetExportFormatEnum): string {
126
+ return format.toLowerCase();
127
+ }
128
+
129
+ /*
130
+ * Return the HTTP content type for one export format.
131
+ */
132
+ export function getSheetExportContentType(format: SheetExportFormatEnum): string {
133
+ return FILE_CONSTANTS.contentTypes[format];
134
+ }
135
+
136
+ /*
137
+ * Return a base name stripped of characters that are unsafe in download file
138
+ * names, collapsed and capped so Content-Disposition stays sane.
139
+ */
140
+ function getSheetExportSafeBaseName(name: string): string {
141
+ const safeName = name
142
+ .replace(FILE_CONSTANTS.fileNameIllegalChars, ' ')
143
+ .replace(/\s+/g, ' ')
144
+ .trim()
145
+ .slice(0, FILE_CONSTANTS.maxFileNameLength)
146
+ .trim();
147
+
148
+ return safeName || 'Sheet';
149
+ }
150
+
151
+ /*
152
+ * Return the download file name for one export: "Title.xlsx" for whole-workbook
153
+ * exports, "Title - TabName.csv|tsv|pdf" for single-tab exports.
154
+ */
155
+ export function getSheetExportFileName(sheetTitle: string, tabName: string | null | undefined, format: SheetExportFormatEnum): string {
156
+ const baseName = format === 'XLSX' || !tabName ? sheetTitle : `${sheetTitle} - ${tabName}`;
157
+
158
+ return `${getSheetExportSafeBaseName(baseName)}.${getSheetExportFileExtension(format)}`;
159
+ }
160
+
161
+ /*
162
+ * Return an XLSX-legal worksheet name for one sheet tab: illegal characters
163
+ * removed, capped at 31 chars, non-empty, and deduped case-insensitively with
164
+ * " (2)"-style suffixes. Mutates usedNames so callers can loop over tabs.
165
+ */
166
+ export function getSheetExportTabName(name: string | null | undefined, usedNames: Set<string>): string {
167
+ const safeName =
168
+ (name || '')
169
+ .replace(FILE_CONSTANTS.tabNameIllegalChars, ' ')
170
+ .replace(/\s+/g, ' ')
171
+ .trim()
172
+ .slice(0, FILE_CONSTANTS.maxTabNameLength)
173
+ .trim() || 'Sheet1';
174
+
175
+ let uniqueName = safeName;
176
+ let suffixNumber = 2;
177
+
178
+ while (usedNames.has(uniqueName.toLowerCase())) {
179
+ const suffix = ` (${suffixNumber})`;
180
+ uniqueName = safeName.slice(0, FILE_CONSTANTS.maxTabNameLength - suffix.length).trimEnd() + suffix;
181
+ suffixNumber += 1;
182
+ }
183
+
184
+ usedNames.add(uniqueName.toLowerCase());
185
+ return uniqueName;
186
+ }
@@ -0,0 +1,183 @@
1
+ import {
2
+ SHEET_CELL_NOTE_MAX_CHARS,
3
+ SHEET_CELL_NUMBER_FORMAT_TYPE_ENUMS,
4
+ SHEET_CELL_TEXT_MAX_CHARS,
5
+ SHEET_DEFAULT_COLUMN_COUNT,
6
+ SHEET_DEFAULT_ROW_COUNT,
7
+ SHEET_MAX_COLUMN_COUNT,
8
+ SHEET_MAX_ROW_COUNT,
9
+ } from '../constants/sheet.ts';
10
+
11
+ export type SheetFeatureReferenceTopicId = 'references' | 'layout' | 'calculation';
12
+
13
+ export interface SheetFeatureReferenceExample {
14
+ description: string;
15
+ expression?: string;
16
+ value?: unknown;
17
+ }
18
+
19
+ export interface SheetFeatureReferenceTopic {
20
+ id: SheetFeatureReferenceTopicId;
21
+ title: string;
22
+ summary: string;
23
+ engineSupported: readonly string[];
24
+ syntax: readonly string[];
25
+ examples: readonly SheetFeatureReferenceExample[];
26
+ rules: readonly string[];
27
+ limits: Readonly<Record<string, string | number>>;
28
+ }
29
+
30
+ /* Engine reference shared by product help and agent discovery. Tool availability belongs to the caller. */
31
+ export const SHEET_FEATURE_REFERENCE: Readonly<Record<SheetFeatureReferenceTopicId, SheetFeatureReferenceTopic>> = {
32
+ references: {
33
+ id: 'references',
34
+ title: 'Sheet cell and range references',
35
+ summary:
36
+ 'Formulas support A1 cells, closed rectangles, absolute $ anchors, same-workbook tab references and an open ending row such as C3:C.',
37
+ engineSupported: [
38
+ 'Read relative, absolute and mixed row/column references.',
39
+ 'Reference another tab in the same spreadsheet and pass rectangular ranges to supported functions.',
40
+ ],
41
+ syntax: ['A1', '$A$1', '$A1', 'A$1', 'tab_name!B6', "'tab_name'!B6", 'A2:D20', 'C3:C'],
42
+ examples: [
43
+ {
44
+ description: 'Keep the multiplier fixed when a formula is copied.',
45
+ expression: '=A2 * $B$1',
46
+ },
47
+ {
48
+ description: 'Read another tab in this spreadsheet.',
49
+ expression: '=season_attendance!B6',
50
+ },
51
+ {
52
+ description: 'Sum a range on the tab created as "Sales Plan", which is stored as sales_plan.',
53
+ expression: '=SUM(sales_plan!C3:C20)',
54
+ },
55
+ {
56
+ description: 'Sum from row 3 to the shared sheet row limit.',
57
+ expression: '=SUM(C3:C)',
58
+ },
59
+ ],
60
+ rules: [
61
+ 'Rows and columns are one-based. $ fixes the marked row or column during relative-copy transformations; it is not a read/write permission.',
62
+ 'Tab references resolve within the current workbook. They do not address another spreadsheet or an external workbook URL.',
63
+ 'Tab names are stored lowercase snake_case ([a-z0-9_]): a tab created or renamed as "Q3 Sales" is saved as q3_sales. Put that stored name before !, as in q3_sales!B2, and read it from view_sheet or the tab tool results. A name with spaces or other characters outside [a-z0-9_] never resolves; quote a stored name that starts with a digit, as in \'2026_01\'!B2 (unquoted 2026_01!B2 does not parse). Quoting any stored name is allowed.',
64
+ 'An open ending row needs a starting cell, as in C3:C or C3:F. Whole-column C:C, whole-row 3:3 and open ending columns are not this range grammar.',
65
+ 'A range is a collection of cell values. Use a supported range-consuming function when a scalar result is needed. Lookup and criteria functions (VLOOKUP, INDEX, SUMIFS, ...) use its row/column shape, so ranges passed together must be the same size.',
66
+ 'A range reads at most the sheet caps (row 500, column 256); any part past them is empty. Prefer bounded ranges.',
67
+ 'A directly referenced error cell passes its error on (IFERROR/IFNA can catch it). Error cells inside a range read as blank, except cells in a circular reference chain, which make the whole range an error.',
68
+ 'Named ranges can be saved in layout metadata, but formula identifiers do not currently resolve named-range aliases. Use A1 coordinates in formulas.',
69
+ 'Prefer <> for not-equal comparisons after cell references; ! also introduces tab-reference syntax.',
70
+ ],
71
+ limits: {
72
+ openRangeEndRow: SHEET_MAX_ROW_COUNT,
73
+ workbookRows: SHEET_MAX_ROW_COUNT,
74
+ workbookColumns: SHEET_MAX_COLUMN_COUNT,
75
+ },
76
+ },
77
+
78
+ layout: {
79
+ id: 'layout',
80
+ title: 'Sheet layout and formatting',
81
+ summary:
82
+ 'The sheet design stores dimensions, frozen/hidden axes, defaults, cell presentation, merged ranges and named-range metadata separately from cell contents.',
83
+ engineSupported: [
84
+ 'Apply text/fill colors, font size, emphasis, alignment, wrapping and per-edge borders.',
85
+ 'Apply number, currency, percent, date/time and custom number-format patterns without changing underlying values.',
86
+ 'Configure row heights, column widths, visibility, frozen axes, rectangular merges and named-range metadata.',
87
+ ],
88
+ syntax: [
89
+ 'Style: {bold,textColor,fillColor,textAlign,verticalAlign,textWrap,...}',
90
+ 'Format: {numberFormat:{type,pattern?,currency?}}',
91
+ 'Named range: {name,startRowIndex,startColumnIndex,endRowIndex,endColumnIndex}',
92
+ ],
93
+ examples: [
94
+ {
95
+ description: 'Give a header a solid fill and bold centered text.',
96
+ value: {
97
+ bold: true,
98
+ fillColor: '#17324D',
99
+ textColor: '#FFFFFF',
100
+ textAlign: 'CENTER',
101
+ },
102
+ },
103
+ {
104
+ description: 'Display a numeric fraction as a percentage.',
105
+ value: { numberFormat: { type: 'PERCENT' } },
106
+ },
107
+ {
108
+ description: 'Save a bounded named range as design metadata.',
109
+ value: {
110
+ name: 'Revenue',
111
+ startRowIndex: 2,
112
+ startColumnIndex: 3,
113
+ endRowIndex: 20,
114
+ endColumnIndex: 3,
115
+ },
116
+ },
117
+ ],
118
+ rules: [
119
+ `Number format types: ${SHEET_CELL_NUMBER_FORMAT_TYPE_ENUMS.join(
120
+ ', ',
121
+ )}. CUSTOM requires a pattern; currency-family formats can specify an ISO currency code.`,
122
+ 'Formatting controls display and does not convert text into a number, date or formula. Keep stored typing separate from presentation.',
123
+ 'Merged cells display their anchor value. Preserve relevant content when changing a merge.',
124
+ 'Named ranges are stored as bounded design entities, but are not currently accepted as formula reference aliases.',
125
+ 'Grid edits, structure changes and cell content edits are separate command families. A content-only write must not be treated as an implicit resize or presentation edit.',
126
+ 'Inserting, deleting or moving rows and columns rewrites formula references on every tab and named ranges like a spreadsheet: a range grows when lines are inserted inside it and shrinks when lines inside it are deleted, and a reference to a deleted cell or fully deleted range (or one pushed past the grid limit) becomes #REF!.',
127
+ 'This reference does not define chart, pivot-table, conditional-formatting or arbitrary script APIs.',
128
+ ],
129
+ limits: {
130
+ defaultRows: SHEET_DEFAULT_ROW_COUNT,
131
+ defaultColumns: SHEET_DEFAULT_COLUMN_COUNT,
132
+ maximumRows: SHEET_MAX_ROW_COUNT,
133
+ maximumColumns: SHEET_MAX_COLUMN_COUNT,
134
+ noteCharacters: SHEET_CELL_NOTE_MAX_CHARS,
135
+ },
136
+ },
137
+ calculation: {
138
+ id: 'calculation',
139
+ title: 'Saved values, calculation and previews',
140
+ summary:
141
+ 'Authored content, computed formula results and formatted display values are distinct. A committed edit or preview image alone does not prove every dependent calculation or projection has finished.',
142
+ engineSupported: [
143
+ 'Compile and evaluate supported formulas, track dependencies and publish computed changes through sheet journals.',
144
+ 'Produce bounded read-only formula previews over pending literal edits, without persisting those edits.',
145
+ 'Read committed sheet rectangles and optionally render a version-matched image.',
146
+ ],
147
+ syntax: [
148
+ 'Authored formula: rawInput beginning with = without an explicit TEXT literal type.',
149
+ 'Literal text: {rawInput:"=A1",literalType:"TEXT"}',
150
+ 'Closed preview rectangle: C2:G10',
151
+ ],
152
+ examples: [
153
+ {
154
+ description: 'Calculate a scalar from a known rectangle.',
155
+ expression: '=SUM(C2:C10)',
156
+ },
157
+ {
158
+ description: 'Store formula-looking text without executing it.',
159
+ value: { rawInput: '=SUM(C2:C10)', literalType: 'TEXT' },
160
+ },
161
+ ],
162
+ rules: [
163
+ 'Keep rawInput/formula text, typed values, computed result, display text and errors distinct. Formatting or an image is not the authoritative underlying value.',
164
+ 'Saved commands return calculation status; pending work may require a subsequent current read.',
165
+ 'The existing formula-preview service evaluates saved formulas with a bounded overlay of pending literal changes. It is not a general validator for newly invented formulas.',
166
+ 'Clock-dependent or errored formula evaluations are not eligible for ordinary short result reuse. TODAY/NOW behavior uses the evaluator clock and organization timezone.',
167
+ 'Operators: + - * / ^ (power, left-associative: 2^3^2 is 64, -2^2 is 4), & (joins text: TRUE/FALSE, numbers at 15 significant digits) and comparisons = <> != < <= > >=. + joins text only when a side is not numeric, so use & for text.',
168
+ 'Formula errors display #N/A (not found), #VALUE! (wrong kind of value), #REF! (a reference to a deleted cell or range), #NUM! (invalid or non-finite number), #DIV/0! (division by zero) or #ERROR! (any other failure, including circular references). IFERROR catches every error; IFNA catches only #N/A.',
169
+ 'Committed image previews accept a single closed A1 rectangle, not open formula ranges or cross-tab references. Large overviews are truncated; use explicit ranges for more detail.',
170
+ 'Image previews fail or must be retried if versions change or linked projections are unpublished. A stale thumbnail or unavailable image must not be used as proof of current cell contents.',
171
+ ],
172
+ // These service-local bounds mirror sheetOps-formulaPreview.helpers.ts and sheetOps-previewSnapshot.helpers.ts.
173
+ limits: {
174
+ pendingLiteralInputs: 1000,
175
+ formulaPreviewCells: 1000,
176
+ formulaPreviewSnapshotCells: 10000,
177
+ imagePreviewRows: 100,
178
+ imagePreviewColumns: 100,
179
+ imagePreviewCells: 10000,
180
+ formulaTextCharacters: SHEET_CELL_TEXT_MAX_CHARS,
181
+ },
182
+ },
183
+ };
@@ -0,0 +1,168 @@
1
+ import type { DateTime } from 'luxon';
2
+ import { SHEET_CELL_TEXT_MAX_CHARS } from '../constants/sheet.ts';
3
+ import {
4
+ getSheetFormulaDateTimeValue,
5
+ getSheetFormulaLogicalBooleanValue,
6
+ getSheetFormulaNumericValue,
7
+ getSheetFormulaPureErrorResult,
8
+ getSheetFormulaTextValue,
9
+ isSheetFormulaBlankValue,
10
+ isSheetFormulaRangeLikeValue,
11
+ type SheetFormulaPureEvaluationResult,
12
+ } from './sheetFormulaEvaluation.ts';
13
+
14
+ /**
15
+ * Types
16
+ */
17
+
18
+ /* One validated scalar builtin argument, or the error result to return. */
19
+ export type SheetFormulaArgResult<T> = { ok: true; value: T } | { ok: false; result: SheetFormulaPureEvaluationResult };
20
+
21
+ /*
22
+ * Return a failed argument result with an INVALID_VALUE (#VALUE!) error.
23
+ */
24
+ export function getSheetFormulaInvalidArgResult(message: string): {
25
+ ok: false;
26
+ result: SheetFormulaPureEvaluationResult;
27
+ } {
28
+ return {
29
+ ok: false,
30
+ result: getSheetFormulaPureErrorResult('INVALID_VALUE', message),
31
+ };
32
+ }
33
+
34
+ /*
35
+ * Return the INVALID_VALUE argument result for a range passed where a single
36
+ * value is required.
37
+ */
38
+ function getSheetFormulaRangeArgResult(name: string, label: string) {
39
+ return getSheetFormulaInvalidArgResult(`${name} requires a single value for ${label}, not a range.`);
40
+ }
41
+
42
+ /*
43
+ * Return one numeric argument: numbers, booleans (TRUE = 1) and numeric text,
44
+ * with a blank argument read as 0 (as in Excel). Ranges and other text are
45
+ * INVALID_VALUE.
46
+ */
47
+ export function getSheetFormulaNumberArg(name: string, value: unknown, label: string): SheetFormulaArgResult<number> {
48
+ if (isSheetFormulaRangeLikeValue(value)) {
49
+ return getSheetFormulaRangeArgResult(name, label);
50
+ }
51
+
52
+ const numberValue = isSheetFormulaBlankValue(value) ? 0 : getSheetFormulaNumericValue(value);
53
+ return numberValue === null
54
+ ? getSheetFormulaInvalidArgResult(`${name} requires a number for ${label}.`)
55
+ : { ok: true, value: numberValue };
56
+ }
57
+
58
+ /*
59
+ * Return one whole-number argument (numbers truncate toward zero), with an
60
+ * optional minimum; below the minimum is INVALID_VALUE.
61
+ */
62
+ export function getSheetFormulaIntegerArg(
63
+ name: string,
64
+ value: unknown,
65
+ label: string,
66
+ min = Number.NEGATIVE_INFINITY,
67
+ ): SheetFormulaArgResult<number> {
68
+ const numberArg = getSheetFormulaNumberArg(name, value, label);
69
+ if (!numberArg.ok) {
70
+ return numberArg;
71
+ }
72
+
73
+ const integer = Math.trunc(numberArg.value);
74
+ return integer < min
75
+ ? getSheetFormulaInvalidArgResult(`${name} requires ${label} of at least ${min}.`)
76
+ : { ok: true, value: integer };
77
+ }
78
+
79
+ /*
80
+ * Return one text argument in its spreadsheet text form (blank is '',
81
+ * TRUE/FALSE, numbers at 15 significant digits); a range is INVALID_VALUE.
82
+ */
83
+ export function getSheetFormulaTextArg(name: string, value: unknown, label: string): SheetFormulaArgResult<string> {
84
+ return isSheetFormulaRangeLikeValue(value)
85
+ ? getSheetFormulaRangeArgResult(name, label)
86
+ : { ok: true, value: getSheetFormulaTextValue(value) };
87
+ }
88
+
89
+ /*
90
+ * Return one TRUE/FALSE argument (blank is FALSE); a range or text other than
91
+ * TRUE/FALSE is INVALID_VALUE.
92
+ */
93
+ export function getSheetFormulaBooleanArg(name: string, value: unknown, label: string): SheetFormulaArgResult<boolean> {
94
+ if (isSheetFormulaRangeLikeValue(value)) {
95
+ return getSheetFormulaRangeArgResult(name, label);
96
+ }
97
+
98
+ const booleanValue = getSheetFormulaLogicalBooleanValue(value);
99
+ return booleanValue === null
100
+ ? getSheetFormulaInvalidArgResult(`${name} requires TRUE or FALSE for ${label}.`)
101
+ : { ok: true, value: booleanValue };
102
+ }
103
+
104
+ /*
105
+ * Return one date argument as the start of its calendar day in the
106
+ * organization time zone. Text must start with a full yyyy-MM-dd date (an ISO
107
+ * date or datetime); numeric serials, blanks, partial ISO text such as "2026"
108
+ * or a bare time (which would read as today) are INVALID_VALUE.
109
+ */
110
+ export function getSheetFormulaDateArg(
111
+ name: string,
112
+ value: unknown,
113
+ label: string,
114
+ timeZone: string,
115
+ ): SheetFormulaArgResult<DateTime> {
116
+ if (isSheetFormulaRangeLikeValue(value)) {
117
+ return getSheetFormulaRangeArgResult(name, label);
118
+ }
119
+
120
+ const dateTime =
121
+ typeof value === 'string' && /^\s*\d{4}-\d{2}-\d{2}/.test(value) ? getSheetFormulaDateTimeValue(value, timeZone) : null;
122
+ return dateTime
123
+ ? { ok: true, value: dateTime.startOf('day') }
124
+ : getSheetFormulaInvalidArgResult(`${name} requires an ISO date such as "2026-01-31" for ${label}.`);
125
+ }
126
+
127
+ /*
128
+ * Return the scalar entries of builtin arguments with ranges and arrays
129
+ * flattened row-major.
130
+ */
131
+ export function flattenSheetFormulaArgValues(values: unknown[]) {
132
+ return values.flatMap((value) => (isSheetFormulaRangeLikeValue(value) ? value.values : [value]));
133
+ }
134
+
135
+ /*
136
+ * Return the INVALID_VALUE result for a text result over the per-cell cap.
137
+ */
138
+ export function getSheetFormulaTextTooLongResult(name: string) {
139
+ return getSheetFormulaPureErrorResult('INVALID_VALUE', `${name} result is longer than ${SHEET_CELL_TEXT_MAX_CHARS} characters.`);
140
+ }
141
+
142
+ /*
143
+ * Return a text result, or INVALID_VALUE when it is longer than the per-cell
144
+ * text cap.
145
+ */
146
+ export function getSheetFormulaTextResult(name: string, text: string): SheetFormulaPureEvaluationResult {
147
+ return text.length > SHEET_CELL_TEXT_MAX_CHARS ? getSheetFormulaTextTooLongResult(name) : { value: text };
148
+ }
149
+
150
+ /*
151
+ * Join text pieces with a delimiter, or return INVALID_VALUE as soon as the
152
+ * running length passes the per-cell text cap, so a join over a large range
153
+ * never builds an oversized string.
154
+ */
155
+ export function joinSheetFormulaTextPieces(name: string, pieces: Iterable<string>, delimiter = ''): SheetFormulaPureEvaluationResult {
156
+ const kept: string[] = [];
157
+ let length = 0;
158
+ for (const piece of pieces) {
159
+ length += piece.length + (kept.length ? delimiter.length : 0);
160
+ if (length > SHEET_CELL_TEXT_MAX_CHARS) {
161
+ return getSheetFormulaTextTooLongResult(name);
162
+ }
163
+
164
+ kept.push(piece);
165
+ }
166
+
167
+ return { value: kept.join(delimiter) };
168
+ }