@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,609 @@
1
+ /**
2
+ * Pure helpers for note "content" documents. No DOM/browser APIs: the same
3
+ * code runs on the Deno server (sanitizing mutation input, filtering image
4
+ * blocks on read) and on the web client (sanitizing before save).
5
+ */
6
+
7
+ import {
8
+ NOTE_BLOCK_TYPES,
9
+ NOTE_COLOR_TOKENS,
10
+ NOTE_CONTAINER_BLOCK_TYPES,
11
+ NOTE_DOC_VERSION,
12
+ NOTE_LINK_HREF_REGEX,
13
+ NOTE_MARK_TYPES,
14
+ NOTE_MAX_BLOCKS,
15
+ NOTE_MAX_DEPTH,
16
+ NOTE_MAX_TEXT_CHARS,
17
+ NOTE_NESTING_RULES,
18
+ } from '../constants/noteDoc.ts';
19
+ import type {
20
+ RichTextContent,
21
+ RichTextContentType,
22
+ RichTextDocument,
23
+ RichTextHeadingLevel,
24
+ RichTextInlineContent,
25
+ RichTextMark,
26
+ RichTextMarkType,
27
+ } from '@jsb188/mday/types/richText.d.ts';
28
+
29
+ const FILE_CONSTANTS = {
30
+ // Maximum raw JSON nesting levels one sanitize walk may descend; beyond
31
+ // this the input is hostile and the remainder is dropped (legal documents
32
+ // stay far below it because NOTE_MAX_DEPTH caps the output tree)
33
+ maxRawNesting: 64,
34
+ // Maximum raw nodes the iterative over-deep-container flattener visits
35
+ flattenVisitCap: 10000,
36
+ };
37
+
38
+ /**
39
+ * Mutable doc-wide caps shared across one sanitize walk; both counters only
40
+ * ever decrease, so the tail of an oversized document is truncated.
41
+ */
42
+
43
+ interface SanitizeBudget {
44
+ blocks: number;
45
+ textChars: number;
46
+ }
47
+
48
+ /**
49
+ * Check whether one unknown value is a plain object (a JSON node candidate).
50
+ */
51
+
52
+ function isNodeObj(value: unknown): value is Record<string, any> {
53
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
54
+ }
55
+
56
+ /**
57
+ * Check whether one block type holds block children.
58
+ */
59
+
60
+ function isContainerBlockType(type: string): boolean {
61
+ return (NOTE_CONTAINER_BLOCK_TYPES as readonly string[]).includes(type);
62
+ }
63
+
64
+ /**
65
+ * Build one empty paragraph block (the non-empty guarantee filler).
66
+ */
67
+
68
+ function createEmptyParagraph(): RichTextContent {
69
+ return {
70
+ type: 'paragraph',
71
+ content: [],
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Build one empty note document: a single empty paragraph, current version.
77
+ */
78
+
79
+ export function createEmptyNoteDoc(): RichTextDocument {
80
+ return {
81
+ type: 'doc',
82
+ version: NOTE_DOC_VERSION,
83
+ content: [createEmptyParagraph()],
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Sanitize one raw mark list: whitelist mark types, validate color/highlight
89
+ * tokens against the palette, restrict link hrefs to http(s)/mailto (which
90
+ * kills javascript: URLs), rebuild attrs from scratch (stripping unknown
91
+ * props), and drop duplicate mark types. Returns undefined when nothing
92
+ * survives so clean runs omit the "marks" key entirely.
93
+ */
94
+
95
+ function sanitizeMarks(rawMarks: unknown): RichTextMark[] | undefined {
96
+ if (!Array.isArray(rawMarks)) {
97
+ return undefined;
98
+ }
99
+
100
+ const marks: RichTextMark[] = [];
101
+ const seenTypes = new Set<string>();
102
+
103
+ for (const raw of rawMarks) {
104
+ if (!isNodeObj(raw) || typeof raw.type !== 'string') {
105
+ continue;
106
+ }
107
+
108
+ const type = raw.type;
109
+ if (!(NOTE_MARK_TYPES as readonly string[]).includes(type) || seenTypes.has(type)) {
110
+ continue;
111
+ }
112
+
113
+ if (type === 'color' || type === 'highlight') {
114
+ // Palette marks must carry a known color token
115
+ const token = isNodeObj(raw.attrs) ? raw.attrs.token : undefined;
116
+ if (typeof token !== 'string' || !NOTE_COLOR_TOKENS.includes(token)) {
117
+ continue;
118
+ }
119
+ marks.push({ type: type as RichTextMarkType, attrs: { token } });
120
+ } else if (type === 'link') {
121
+ // Only http(s)/mailto links survive; anything else is dropped
122
+ const rawHref = isNodeObj(raw.attrs) ? raw.attrs.href : undefined;
123
+ const href = typeof rawHref === 'string' ? rawHref.trim() : '';
124
+ if (!NOTE_LINK_HREF_REGEX.test(href)) {
125
+ continue;
126
+ }
127
+ marks.push({ type: 'link', attrs: { href } });
128
+ } else {
129
+ // bold/italic/underline/strike/code carry no attrs
130
+ marks.push({ type: type as RichTextMarkType });
131
+ }
132
+
133
+ seenTypes.add(type);
134
+ }
135
+
136
+ return marks.length ? marks : undefined;
137
+ }
138
+
139
+ /**
140
+ * Build one order-insensitive identity key for a text run's mark set, used
141
+ * to merge adjacent runs with identical styling.
142
+ */
143
+
144
+ function getMarkSetKey(marks?: RichTextMark[]): string {
145
+ if (!marks?.length) {
146
+ return '';
147
+ }
148
+ return marks
149
+ .map((mark) => `${mark.type}:${mark.attrs?.token || mark.attrs?.href || ''}`)
150
+ .sort()
151
+ .join('|');
152
+ }
153
+
154
+ /**
155
+ * Sanitize one raw inline list: whitelist text/hardBreak nodes, sanitize
156
+ * marks, spend the doc-wide text budget (truncating the tail; hardBreaks
157
+ * cost 1 char each, matching the offset model, so a hardBreak flood cannot
158
+ * evade the caps), drop empty runs, and merge adjacent runs with identical
159
+ * mark sets.
160
+ */
161
+
162
+ function sanitizeInlineContent(rawContent: unknown, budget: SanitizeBudget): RichTextInlineContent[] {
163
+ const inline: RichTextInlineContent[] = [];
164
+ if (!Array.isArray(rawContent)) {
165
+ return inline;
166
+ }
167
+
168
+ for (const raw of rawContent) {
169
+ if (!isNodeObj(raw)) {
170
+ continue;
171
+ }
172
+
173
+ if (raw.type === 'hardBreak') {
174
+ // A hardBreak counts as 1 char in the offset model; spend the
175
+ // doc-wide text budget so unbounded hardBreak floods truncate
176
+ if (budget.textChars <= 0) {
177
+ continue;
178
+ }
179
+ budget.textChars -= 1;
180
+ inline.push({ type: 'hardBreak' });
181
+ continue;
182
+ }
183
+
184
+ if (raw.type !== 'text' || typeof raw.text !== 'string' || !raw.text) {
185
+ continue;
186
+ }
187
+
188
+ // Truncate the tail once the doc-wide character cap is spent
189
+ const text = raw.text.length > budget.textChars ? raw.text.slice(0, budget.textChars) : raw.text;
190
+ if (!text) {
191
+ continue;
192
+ }
193
+ budget.textChars -= text.length;
194
+
195
+ const marks = sanitizeMarks(raw.marks);
196
+ const prev = inline[inline.length - 1];
197
+
198
+ if (prev?.type === 'text' && getMarkSetKey(prev.marks) === getMarkSetKey(marks)) {
199
+ // Merge adjacent runs with identical styling
200
+ prev.text += text;
201
+ } else if (marks) {
202
+ inline.push({ type: 'text', text, marks });
203
+ } else {
204
+ inline.push({ type: 'text', text });
205
+ }
206
+ }
207
+
208
+ return inline;
209
+ }
210
+
211
+ /**
212
+ * Collect the raw inline nodes of one raw block subtree in document order,
213
+ * inserting one hardBreak between text-bearing blocks. Used to flatten an
214
+ * over-deep container into a single paragraph without losing its text.
215
+ * Walks with an explicit stack so hostile deeply-nested input cannot
216
+ * overflow the call stack; the returned nodes are still raw (they go
217
+ * through sanitizeInlineContent exactly once afterwards).
218
+ */
219
+
220
+ function collectRawInlineNodes(rawBlock: Record<string, any>): any[] {
221
+ const out: any[] = [];
222
+ const stack: any[] = [rawBlock];
223
+ let visited = 0;
224
+
225
+ while (stack.length && visited < FILE_CONSTANTS.flattenVisitCap) {
226
+ const node = stack.pop();
227
+ visited += 1;
228
+
229
+ if (!isNodeObj(node) || !Array.isArray(node.content)) {
230
+ continue;
231
+ }
232
+
233
+ // Text-bearing blocks contribute their inline children as one chunk
234
+ const inlineChildren = node.content.filter(
235
+ (child: any) => isNodeObj(child) && (child.type === 'text' || child.type === 'hardBreak'),
236
+ );
237
+ if (inlineChildren.length) {
238
+ if (out.length) {
239
+ out.push({ type: 'hardBreak' });
240
+ }
241
+ out.push(...inlineChildren);
242
+ }
243
+
244
+ // Descend into block children in document order (reverse push)
245
+ for (let i = node.content.length - 1; i >= 0; i--) {
246
+ const child = node.content[i];
247
+ if (isNodeObj(child) && child.type !== 'text' && child.type !== 'hardBreak') {
248
+ stack.push(child);
249
+ }
250
+ }
251
+ }
252
+
253
+ return out;
254
+ }
255
+
256
+ /**
257
+ * Sanitize one raw block node whose type is legal at its position. Returns
258
+ * zero or one blocks: void leaves missing required attrs and lists left
259
+ * with no listItems come back empty. depth is the node's own depth (doc
260
+ * children sit at depth 1); rawDepth counts raw JSON descents.
261
+ */
262
+
263
+ function sanitizeBlockNode(
264
+ raw: Record<string, any>,
265
+ type: RichTextContentType,
266
+ depth: number,
267
+ rawDepth: number,
268
+ budget: SanitizeBudget,
269
+ ): RichTextContent[] {
270
+ if (budget.blocks <= 0) {
271
+ // Block cap reached; truncate the tail
272
+ return [];
273
+ }
274
+ budget.blocks -= 1;
275
+
276
+ if (type === 'paragraph') {
277
+ return [
278
+ {
279
+ type: 'paragraph',
280
+ content: sanitizeInlineContent(raw.content, budget),
281
+ },
282
+ ];
283
+ }
284
+
285
+ if (type === 'heading') {
286
+ // Clamp the heading level into 1-3 (garbage coerces to 1)
287
+ const rawLevel = isNodeObj(raw.attrs) ? Number(raw.attrs.level) : NaN;
288
+ const level = (Number.isFinite(rawLevel) ? Math.min(3, Math.max(1, Math.round(rawLevel))) : 1) as RichTextHeadingLevel;
289
+ return [
290
+ {
291
+ type: 'heading',
292
+ attrs: { level },
293
+ content: sanitizeInlineContent(raw.content, budget),
294
+ },
295
+ ];
296
+ }
297
+
298
+ if (type === 'divider') {
299
+ return [{ type: 'divider' }];
300
+ }
301
+
302
+ if (type === 'image') {
303
+ if (raw._uploading === true) {
304
+ // The signed upload is not authoritative yet. Omitting the block lets
305
+ // unrelated edits persist while a later upload-complete revision adds
306
+ // the validated image.
307
+ budget.blocks += 1;
308
+ return [];
309
+ }
310
+
311
+ // Image blocks must carry a storage id and file uri; everything else
312
+ // (alt, width) is optional and unknown fields are stripped by rebuilding
313
+ // attrs from scratch.
314
+ const rawAttrs = isNodeObj(raw.attrs) ? raw.attrs : {};
315
+ const storageId = typeof rawAttrs.storageId === 'string' ? rawAttrs.storageId : '';
316
+ const fileUri = typeof rawAttrs.fileUri === 'string' ? rawAttrs.fileUri : '';
317
+
318
+ if (!storageId || !fileUri) {
319
+ // Unclaimed/incomplete images (mid-upload) never persist
320
+ budget.blocks += 1;
321
+ return [];
322
+ }
323
+
324
+ const block: RichTextContent = {
325
+ type: 'image',
326
+ attrs: { storageId, fileUri },
327
+ };
328
+ if (typeof rawAttrs.alt === 'string' && rawAttrs.alt) {
329
+ block.attrs!.alt = rawAttrs.alt;
330
+ }
331
+ if (typeof rawAttrs.width === 'number' && Number.isFinite(rawAttrs.width) && rawAttrs.width > 0) {
332
+ block.attrs!.width = rawAttrs.width;
333
+ }
334
+ return [block];
335
+ }
336
+
337
+ if (type === 'bulletList' || type === 'orderedList') {
338
+ const children = sanitizeBlockContent(raw.content, type, depth + 1, rawDepth + 1, budget);
339
+ if (!children.length) {
340
+ // A list with no surviving listItems renders nothing; drop it
341
+ return [];
342
+ }
343
+ return [{ type, content: children }];
344
+ }
345
+
346
+ // listItem/blockquote: containers that must never be left empty
347
+ const children = sanitizeBlockContent(raw.content, type, depth + 1, rawDepth + 1, budget);
348
+ if (!children.length) {
349
+ children.push(createEmptyParagraph());
350
+ }
351
+ return [{ type, content: children }];
352
+ }
353
+
354
+ /**
355
+ * Sanitize one raw child list against a container's nesting rules; depth is
356
+ * the depth the produced children live at (doc children sit at depth 1).
357
+ * Illegal children are never kept as-is: headings become paragraphs where
358
+ * only paragraphs fit, illegal containers are unwrapped (their children
359
+ * re-processed against the same container), text blocks inside lists are
360
+ * wrapped into their own listItem, stray inline nodes are collected into a
361
+ * paragraph, containers past NOTE_MAX_DEPTH are flattened into a paragraph
362
+ * carrying their text, and void leaves with no legal spot are dropped.
363
+ */
364
+
365
+ function sanitizeBlockContent(
366
+ rawContent: unknown,
367
+ containerType: 'doc' | RichTextContentType,
368
+ depth: number,
369
+ rawDepth: number,
370
+ budget: SanitizeBudget,
371
+ ): RichTextContent[] {
372
+ if (!Array.isArray(rawContent) || rawDepth > FILE_CONSTANTS.maxRawNesting) {
373
+ return [];
374
+ }
375
+
376
+ const allowedTypes = NOTE_NESTING_RULES[containerType] || [];
377
+ const blocks: RichTextContent[] = [];
378
+ let strayInline: any[] = [];
379
+
380
+ /*
381
+ * Wrap buffered stray inline nodes (text in block position) into one
382
+ * paragraph, wherever a paragraph — or a listItem to hold it — fits.
383
+ */
384
+ const flushStrayInline = () => {
385
+ if (!strayInline.length) {
386
+ return;
387
+ }
388
+ const rawParagraph = { type: 'paragraph', content: strayInline };
389
+ strayInline = [];
390
+ if (allowedTypes.includes('paragraph')) {
391
+ blocks.push(...sanitizeBlockNode(rawParagraph, 'paragraph', depth, rawDepth, budget));
392
+ } else if (allowedTypes.includes('listItem')) {
393
+ blocks.push(...sanitizeBlockNode({ type: 'listItem', content: [rawParagraph] }, 'listItem', depth, rawDepth, budget));
394
+ }
395
+ };
396
+
397
+ for (const rawChild of rawContent) {
398
+ if (!isNodeObj(rawChild) || typeof rawChild.type !== 'string') {
399
+ continue;
400
+ }
401
+
402
+ // Stray inline nodes in block position buffer up into one paragraph
403
+ if (rawChild.type === 'text' || rawChild.type === 'hardBreak') {
404
+ strayInline.push(rawChild);
405
+ continue;
406
+ }
407
+ flushStrayInline();
408
+
409
+ if (!(NOTE_BLOCK_TYPES as readonly string[]).includes(rawChild.type)) {
410
+ // Unknown block type; drop it
411
+ continue;
412
+ }
413
+
414
+ let raw = rawChild;
415
+ let type = rawChild.type as RichTextContentType;
416
+
417
+ if (isContainerBlockType(type) && depth >= NOTE_MAX_DEPTH) {
418
+ // Container past the depth cap: flatten its subtree into one
419
+ // paragraph carrying the text (hardBreaks between blocks)
420
+ raw = { type: 'paragraph', content: collectRawInlineNodes(raw) };
421
+ type = 'paragraph';
422
+ }
423
+
424
+ if (allowedTypes.includes(type)) {
425
+ blocks.push(...sanitizeBlockNode(raw, type, depth, rawDepth, budget));
426
+ } else if ((type === 'heading' || type === 'paragraph') && allowedTypes.includes('paragraph')) {
427
+ // Text block where only paragraphs fit converts to a paragraph
428
+ blocks.push(...sanitizeBlockNode({ ...raw, type: 'paragraph' }, 'paragraph', depth, rawDepth, budget));
429
+ } else if (isContainerBlockType(type)) {
430
+ // Illegal container: unwrap it and re-process its children
431
+ // against this same container (lists in blockquotes end up as
432
+ // paragraphs, listItems under doc splice their children in, ...)
433
+ blocks.push(...sanitizeBlockContent(raw.content, containerType, depth, rawDepth + 1, budget));
434
+ } else if ((type === 'heading' || type === 'paragraph') && allowedTypes.includes('listItem')) {
435
+ // Text block directly inside a list wraps into its own listItem
436
+ blocks.push(...sanitizeBlockNode({ type: 'listItem', content: [raw] }, 'listItem', depth, rawDepth, budget));
437
+ }
438
+ // Anything left (divider/image with no legal spot here) is dropped
439
+ }
440
+
441
+ flushStrayInline();
442
+ return blocks;
443
+ }
444
+
445
+ /**
446
+ * Sanitize one untrusted note document into the closed noteDoc vocabulary.
447
+ * Guarantees: only whitelisted node/mark types and attrs survive, nesting
448
+ * follows NOTE_NESTING_RULES, heading levels are clamped to 1-3, color and
449
+ * highlight tokens come from the palette, link hrefs are http(s)/mailto
450
+ * only, client-only fields (_key, _uploading) are gone, the doc respects
451
+ * NOTE_MAX_DEPTH / NOTE_MAX_BLOCKS / NOTE_MAX_TEXT_CHARS (tail truncated),
452
+ * adjacent identical-mark text runs are merged, empty runs are dropped, the
453
+ * doc is never empty, and version is stamped with NOTE_DOC_VERSION. The
454
+ * client runs this before save; the server runs it on mutation input.
455
+ */
456
+
457
+ export function sanitizeNoteDoc(input: unknown): RichTextDocument {
458
+ if (!isNodeObj(input) || input.type !== 'doc') {
459
+ // Unknown roots coerce to a fresh empty document
460
+ return createEmptyNoteDoc();
461
+ }
462
+
463
+ const budget: SanitizeBudget = {
464
+ blocks: NOTE_MAX_BLOCKS,
465
+ textChars: NOTE_MAX_TEXT_CHARS,
466
+ };
467
+ const content = sanitizeBlockContent(input.content, 'doc', 1, 0, budget);
468
+
469
+ return {
470
+ type: 'doc',
471
+ version: NOTE_DOC_VERSION,
472
+ content: content.length ? content : [createEmptyParagraph()],
473
+ };
474
+ }
475
+
476
+ /**
477
+ * Extract one plain-text rendition of a note document, for previews and
478
+ * search indexing: text runs concatenate, hardBreaks become newlines, each
479
+ * text-bearing block becomes its own line, and void blocks (divider, image)
480
+ * plus empty blocks contribute nothing.
481
+ */
482
+
483
+ export function noteDocToPlainText(doc: RichTextDocument): string {
484
+ const lines: string[] = [];
485
+
486
+ /*
487
+ * Walk one block list depth-first, pushing one line per text-bearing block.
488
+ */
489
+ const walk = (blocks: Array<RichTextContent | RichTextInlineContent>) => {
490
+ for (const node of blocks) {
491
+ if (!isNodeObj(node)) {
492
+ continue;
493
+ }
494
+ const block = node as RichTextContent;
495
+ if (isContainerBlockType(block.type) && Array.isArray(block.content)) {
496
+ walk(block.content);
497
+ continue;
498
+ }
499
+ if ((block.type === 'paragraph' || block.type === 'heading') && Array.isArray(block.content)) {
500
+ let line = '';
501
+ for (const inline of block.content as RichTextInlineContent[]) {
502
+ if (!isNodeObj(inline)) {
503
+ continue;
504
+ }
505
+ if (inline.type === 'hardBreak') {
506
+ line += '\n';
507
+ } else if (inline.type === 'text' && typeof inline.text === 'string') {
508
+ line += inline.text;
509
+ }
510
+ }
511
+ if (line) {
512
+ lines.push(line);
513
+ }
514
+ }
515
+ }
516
+ };
517
+
518
+ if (isNodeObj(doc) && Array.isArray(doc.content)) {
519
+ walk(doc.content);
520
+ }
521
+ return lines.join('\n');
522
+ }
523
+
524
+ /**
525
+ * Build one text inline node, or an empty content list for a blank line.
526
+ */
527
+
528
+ function createTextContent(text: string): RichTextInlineContent[] {
529
+ return text ? [{ type: 'text', text }] : [];
530
+ }
531
+
532
+ /**
533
+ * Convert markdown-lite plain text into a note document, for agent-written
534
+ * documents: '#'/'##'/'###' lines become headings, '- '/'* ' runs become
535
+ * bulletList items, '1. '-style runs become orderedList items, '---' lines
536
+ * become dividers, and every other non-blank line becomes a paragraph.
537
+ * The result always passes through sanitizeNoteDoc, so caps and nesting
538
+ * rules apply exactly as they do for human-written documents.
539
+ */
540
+
541
+ export function plainTextToNoteDoc(text: string): RichTextDocument {
542
+ const blocks: RichTextContent[] = [];
543
+ let listType: 'bulletList' | 'orderedList' | null = null;
544
+ let listItems: RichTextContent[] = [];
545
+
546
+ /*
547
+ * Close the open list run, if any, into a single list block.
548
+ */
549
+ const flushList = () => {
550
+ if (listType && listItems.length) {
551
+ blocks.push({ type: listType, content: listItems });
552
+ }
553
+ listType = null;
554
+ listItems = [];
555
+ };
556
+
557
+ for (const rawLine of String(text ?? '').split('\n')) {
558
+ const line = rawLine.trim();
559
+
560
+ if (!line) {
561
+ flushList();
562
+ continue;
563
+ }
564
+
565
+ const headingMatch = line.match(/^(#{1,3})\s+(.*)$/);
566
+ if (headingMatch) {
567
+ flushList();
568
+ blocks.push({
569
+ type: 'heading',
570
+ attrs: { level: headingMatch[1].length as RichTextHeadingLevel },
571
+ content: createTextContent(headingMatch[2].trim()),
572
+ });
573
+ continue;
574
+ }
575
+
576
+ if (/^(-{3,}|\*{3,})$/.test(line)) {
577
+ flushList();
578
+ blocks.push({ type: 'divider' });
579
+ continue;
580
+ }
581
+
582
+ const bulletMatch = line.match(/^[-*]\s+(.*)$/);
583
+ const orderedMatch = line.match(/^\d+[.)]\s+(.*)$/);
584
+ const itemText = bulletMatch?.[1] ?? orderedMatch?.[1];
585
+ if (typeof itemText === 'string') {
586
+ const nextListType = bulletMatch ? 'bulletList' : 'orderedList';
587
+ if (listType !== nextListType) {
588
+ flushList();
589
+ listType = nextListType;
590
+ }
591
+ listItems.push({
592
+ type: 'listItem',
593
+ content: [{ type: 'paragraph', content: createTextContent(itemText.trim()) }],
594
+ });
595
+ continue;
596
+ }
597
+
598
+ flushList();
599
+ blocks.push({ type: 'paragraph', content: createTextContent(line) });
600
+ }
601
+
602
+ flushList();
603
+
604
+ return sanitizeNoteDoc({
605
+ type: 'doc',
606
+ version: NOTE_DOC_VERSION,
607
+ content: blocks,
608
+ });
609
+ }