@jsb188/mday 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -0,0 +1,273 @@
1
+ import {
2
+ QR_CODE_APP_FIELD_REFERENCE_TYPES,
3
+ QR_CODE_LIMITS,
4
+ QR_CODE_REFERENCE_ID_PREFIXES,
5
+ QR_CODE_REFERENCE_TYPES,
6
+ } from '../constants/qrCode.ts';
7
+ import type { QrCodeField, QrCodePayload, QrCodeReferenceField, QrCodeReferenceType } from '../types/qrCode.d.ts';
8
+ import {
9
+ assertQrCodeRecordKeys,
10
+ assertQrCodeTextSize,
11
+ readQrCodeValue,
12
+ QrCodeCodecError,
13
+ readQrCodeRecord,
14
+ readQrCodeString,
15
+ readQrCodeOrganizationId,
16
+ readQrCodeCreatedAt,
17
+ } from './qrCode.helpers.ts';
18
+
19
+ export { assertQrCodeStringEncoding, QrCodeCodecError, readQrCodeValue } from './qrCode.helpers.ts';
20
+
21
+ /*
22
+ * Permit letters, numbers, combining marks, regular spaces, dashes and underscores while editing field keys.
23
+ */
24
+ export function hasValidQrCodeFieldKeyCharacters(value: string): boolean {
25
+ return /^[\p{L}\p{N}\p{M}_ -]*$/u.test(value);
26
+ }
27
+
28
+ /*
29
+ * Canonicalize field keys before issuance, converting Unicode dashes and space-like characters and removing other symbols.
30
+ */
31
+ export function normalizeQrCodeFieldKey(value: string): string {
32
+ return value
33
+ .normalize('NFC')
34
+ .replace(/[\p{Dash_Punctuation}\u2212\u2043\u00ad\u207b\u208b\u2796]/gu, '-')
35
+ .replace(/[\p{White_Space}\p{Cf}\u2800\u3164\uffa0\u115f\u1160]/gu, ' ')
36
+ .replace(/[^\p{L}\p{N}\p{M}_ -]/gu, '')
37
+ .trim();
38
+ }
39
+
40
+ /*
41
+ * Recognize a canonical unpadded base64url token containing 128 random bits.
42
+ */
43
+ export function isQrCodePublicId(value: unknown): value is string {
44
+ return typeof value === 'string' && value.length === 22 && /^[A-Za-z0-9_-]{21}[AQgw]$/.test(value);
45
+ }
46
+
47
+ /*
48
+ * Validate one stored or public reference and its frozen display name without resolving the identity.
49
+ */
50
+ function readQrCodeReferenceField(
51
+ field: Record<string, unknown>,
52
+ key: string,
53
+ description: string | undefined,
54
+ referenceIdFormat: 'numeric' | 'readable',
55
+ ): QrCodeReferenceField {
56
+ assertQrCodeRecordKeys(field, ['key', 'description', 'kind', 'reference', 'displayNameSnapshot']);
57
+ const reference = readQrCodeRecord(field.reference);
58
+ assertQrCodeRecordKeys(reference, ['type', 'id']);
59
+ if (
60
+ !QR_CODE_REFERENCE_TYPES.includes(reference.type as QrCodeReferenceType) ||
61
+ typeof reference.id !== 'string' ||
62
+ !reference.id.length ||
63
+ reference.id.length > QR_CODE_LIMITS.referenceIdLength
64
+ ) {
65
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code reference.');
66
+ }
67
+ const type = reference.type as QrCodeReferenceType;
68
+ const validId =
69
+ referenceIdFormat === 'numeric'
70
+ ? /^[0-9]+$/.test(reference.id)
71
+ : new RegExp(`^${QR_CODE_REFERENCE_ID_PREFIXES[type]}-[0-9]+(?:-[0-9]+)?$`).test(reference.id.replace(/[‐‑‒–—―−]/g, '-'));
72
+ if (!validId) throw new QrCodeCodecError('INVALID', 'Invalid QR code reference ID.');
73
+
74
+ return {
75
+ key,
76
+ ...(description === undefined ? {} : { description }),
77
+ kind: 'REFERENCE',
78
+ reference: { type, id: reference.id },
79
+ displayNameSnapshot: readQrCodeString(field.displayNameSnapshot, QR_CODE_LIMITS.displayNameLength),
80
+ };
81
+ }
82
+
83
+ /*
84
+ * Validate and clone ordered fields using the ID representation required by their boundary.
85
+ */
86
+ function readQrCodeFields(fields: unknown, referenceIdFormat: 'numeric' | 'readable'): QrCodeField[] {
87
+ if (!Array.isArray(fields) || !fields.length) {
88
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code fields.');
89
+ }
90
+ if (fields.length > QR_CODE_LIMITS.maxFields) {
91
+ throw new QrCodeCodecError('TOO_LARGE', 'QR code exceeds the maximum field count.');
92
+ }
93
+
94
+ const keys = new Set<string>();
95
+ const result: QrCodeField[] = [];
96
+ for (const value of fields) {
97
+ const field = readQrCodeRecord(value);
98
+ const key = readQrCodeString(field.key, QR_CODE_LIMITS.fieldKeyLength);
99
+ const rawDescription = field.description;
100
+ const description =
101
+ rawDescription === undefined ? undefined : readQrCodeString(rawDescription, QR_CODE_LIMITS.fieldDescriptionLength);
102
+ if (keys.has(key)) {
103
+ throw new QrCodeCodecError('INVALID', 'Duplicate QR code field key.');
104
+ }
105
+ keys.add(key);
106
+ const requiredReferenceType = Object.hasOwn(QR_CODE_APP_FIELD_REFERENCE_TYPES, key)
107
+ ? QR_CODE_APP_FIELD_REFERENCE_TYPES[key as keyof typeof QR_CODE_APP_FIELD_REFERENCE_TYPES]
108
+ : undefined;
109
+ if (requiredReferenceType && field.kind !== 'REFERENCE') {
110
+ throw new QrCodeCodecError('INVALID', 'App-specific QR code fields require a reference ID.');
111
+ }
112
+
113
+ if (field.kind === 'REFERENCE') {
114
+ const referenceField = readQrCodeReferenceField(field, key, description, referenceIdFormat);
115
+ if (requiredReferenceType && referenceField.reference.type !== requiredReferenceType) {
116
+ throw new QrCodeCodecError('INVALID', 'Invalid reference type for an app-specific QR code field.');
117
+ }
118
+ result.push(referenceField);
119
+ } else if (field.kind === 'VALUE') {
120
+ assertQrCodeRecordKeys(field, ['key', 'description', 'kind', 'value']);
121
+ result.push({
122
+ key,
123
+ ...(description === undefined ? {} : { description }),
124
+ kind: 'VALUE',
125
+ value: readQrCodeValue(field.value),
126
+ });
127
+ } else {
128
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code field kind.');
129
+ }
130
+ }
131
+
132
+ assertQrCodeTextSize(JSON.stringify(result));
133
+ return result;
134
+ }
135
+
136
+ /*
137
+ * Validate stored domain fields and GraphQL-shaped snapshots whose reference IDs remain numeric strings.
138
+ */
139
+ export function validateQrCodeFields(fields: unknown): QrCodeField[] {
140
+ return readQrCodeFields(fields, 'numeric');
141
+ }
142
+
143
+ /*
144
+ * Validate versioned public payloads without decoding identities or changing the issued snapshot.
145
+ */
146
+ export function validateQrCodePayload(value: unknown): QrCodePayload {
147
+ const payload = readQrCodeRecord(value);
148
+ if (typeof payload.v !== 'number' || !Number.isInteger(payload.v) || payload.v < 1) {
149
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code version.');
150
+ }
151
+ if (payload.v !== 1 && payload.v !== 2 && payload.v !== 3) {
152
+ throw new QrCodeCodecError('UNSUPPORTED_VERSION', 'Unsupported QR code version.');
153
+ }
154
+ assertQrCodeRecordKeys(
155
+ payload,
156
+ payload.v === 3 ? ['v', 'publicId', 'organizationId', 'createdAt', 'fields'] : ['v', 'publicId', 'fields'],
157
+ );
158
+ if (!isQrCodePublicId(payload.publicId)) {
159
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code public ID.');
160
+ }
161
+ if (payload.v === 3) {
162
+ return {
163
+ v: payload.v,
164
+ publicId: payload.publicId,
165
+ organizationId: readQrCodeOrganizationId(payload.organizationId),
166
+ createdAt: readQrCodeCreatedAt(payload.createdAt),
167
+ fields: readQrCodeFields(payload.fields, 'readable'),
168
+ };
169
+ }
170
+
171
+ return {
172
+ v: payload.v,
173
+ publicId: payload.publicId,
174
+ fields: readQrCodeFields(payload.fields, payload.v === 1 ? 'numeric' : 'readable'),
175
+ };
176
+ }
177
+
178
+ /*
179
+ * Encode UTF-8 bytes with the URL-safe alphabet and no padding.
180
+ */
181
+ function encodeQrCodeBase64(bytes: Uint8Array): string {
182
+ return btoa(String.fromCharCode(...bytes))
183
+ .replace(/\+/g, '-')
184
+ .replace(/\//g, '_')
185
+ .replace(/=+$/, '');
186
+ }
187
+
188
+ /*
189
+ * Decode canonical base64url into UTF-8 text, rejecting invalid byte sequences.
190
+ */
191
+ function decodeQrCodeBase64(value: string): string {
192
+ if (!value || !/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1) {
193
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code payload encoding.');
194
+ }
195
+ const decoded = atob(value.replace(/-/g, '+').replace(/_/g, '/'));
196
+ const bytes = Uint8Array.from(decoded, (character) => character.charCodeAt(0));
197
+ if (encodeQrCodeBase64(bytes) !== value) {
198
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code payload encoding.');
199
+ }
200
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
201
+ }
202
+
203
+ /*
204
+ * Parse a bounded URL, allowing plain HTTP only for loopback development hosts.
205
+ */
206
+ function readQrCodeURL(value: string): URL {
207
+ if (typeof value !== 'string') {
208
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code URL.');
209
+ }
210
+ assertQrCodeTextSize(value);
211
+ if (/\s/.test(value)) {
212
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code URL.');
213
+ }
214
+ let url: URL;
215
+ try {
216
+ url = new URL(value);
217
+ } catch {
218
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code URL.');
219
+ }
220
+ const loopbackHTTP = url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
221
+ if ((!loopbackHTTP && url.protocol !== 'https:') || url.username || url.password || value.includes('?') || value.includes('\\')) {
222
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code URL.');
223
+ }
224
+ return url;
225
+ }
226
+
227
+ /*
228
+ * Create a link whose fragment contains every value needed for a standalone offline scan.
229
+ */
230
+ export function encodeQrCodeText(origin: string, payload: QrCodePayload): string {
231
+ const url = readQrCodeURL(origin);
232
+ if (url.pathname !== '/' || url.hash) {
233
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code origin.');
234
+ }
235
+ const snapshot = validateQrCodePayload(payload);
236
+ const json = JSON.stringify(snapshot);
237
+ assertQrCodeTextSize(json);
238
+ const encoded = encodeQrCodeBase64(new TextEncoder().encode(json));
239
+ const text = `${url.origin}/q/${snapshot.publicId}#v${snapshot.v}.${encoded}`;
240
+ assertQrCodeTextSize(text);
241
+ return text;
242
+ }
243
+
244
+ /*
245
+ * Decode a scanned link locally; this validates the snapshot but grants no authorization.
246
+ */
247
+ export function decodeQrCodeText(text: string): QrCodePayload {
248
+ const url = readQrCodeURL(text);
249
+ const publicId = url.pathname.startsWith('/q/') ? url.pathname.slice(3) : '';
250
+ if (!isQrCodePublicId(publicId)) {
251
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code path.');
252
+ }
253
+ const versionMarker = /^#v([123])\./.exec(url.hash);
254
+ if (!versionMarker) {
255
+ throw new QrCodeCodecError('UNSUPPORTED_VERSION', 'Unsupported QR code version.');
256
+ }
257
+ let snapshot: QrCodePayload;
258
+ try {
259
+ snapshot = validateQrCodePayload(JSON.parse(decodeQrCodeBase64(url.hash.slice(versionMarker[0].length))));
260
+ } catch (error) {
261
+ if (error instanceof QrCodeCodecError) {
262
+ throw error;
263
+ }
264
+ throw new QrCodeCodecError('INVALID', 'Invalid QR code payload encoding.');
265
+ }
266
+ if (snapshot.v !== Number(versionMarker[1])) {
267
+ throw new QrCodeCodecError('INVALID', 'QR code fragment version does not match its payload.');
268
+ }
269
+ if (snapshot.publicId !== publicId) {
270
+ throw new QrCodeCodecError('INVALID', 'QR code path does not match its payload.');
271
+ }
272
+ return snapshot;
273
+ }
@@ -0,0 +1,385 @@
1
+ import { type DefaultTreeAdapterTypes, parseFragment } from 'parse5';
2
+ import { NOTE_DOC_VERSION, NOTE_LINK_HREF_REGEX, NOTE_MAX_TEXT_CHARS } from '../constants/noteDoc.ts';
3
+ import type {
4
+ RichTextContent,
5
+ RichTextDocument,
6
+ RichTextHeadingLevel,
7
+ RichTextInlineContent,
8
+ RichTextMark,
9
+ RichTextMarkType,
10
+ } from '@jsb188/mday/types/richText.d.ts';
11
+ import { plainTextToNoteDoc, sanitizeNoteDoc } from './noteDoc.ts';
12
+
13
+ const FILE_CONSTANTS = {
14
+ blockContainerTags: new Set([
15
+ 'address',
16
+ 'article',
17
+ 'aside',
18
+ 'div',
19
+ 'figcaption',
20
+ 'figure',
21
+ 'footer',
22
+ 'header',
23
+ 'main',
24
+ 'nav',
25
+ 'section',
26
+ ]),
27
+ maxTraversalDepth: 64,
28
+ markTags: {
29
+ b: 'bold',
30
+ code: 'code',
31
+ del: 'strike',
32
+ em: 'italic',
33
+ i: 'italic',
34
+ s: 'strike',
35
+ strike: 'strike',
36
+ strong: 'bold',
37
+ u: 'underline',
38
+ } as Partial<Record<string, RichTextMarkType>>,
39
+ skippedTags: new Set([
40
+ 'applet',
41
+ 'embed',
42
+ 'frame',
43
+ 'frameset',
44
+ 'head',
45
+ 'iframe',
46
+ 'math',
47
+ 'noembed',
48
+ 'noframes',
49
+ 'noscript',
50
+ 'object',
51
+ 'script',
52
+ 'style',
53
+ 'svg',
54
+ 'table',
55
+ 'template',
56
+ ]),
57
+ htmlMarkupPattern: /<(?:!--|!doctype\b|\/?\s*[a-z][^>]*>)/i,
58
+ supportedHTMLPattern: /<\s*\/?\s*(?:a|b|blockquote|br|code|del|div|em|h[1-6]|hr|i|li|ol|p|pre|s|strike|strong|u|ul)\b/i,
59
+ };
60
+
61
+ type RichTextHTMLChildNode = DefaultTreeAdapterTypes.ChildNode;
62
+ type RichTextHTMLElement = DefaultTreeAdapterTypes.Element;
63
+ type RichTextHTMLTextNode = DefaultTreeAdapterTypes.TextNode;
64
+
65
+ /*
66
+ * Return whether one parsed HTML child is a text node.
67
+ */
68
+ function isRichTextHTMLTextNode(node: RichTextHTMLChildNode): node is RichTextHTMLTextNode {
69
+ return node.nodeName === '#text' && 'value' in node;
70
+ }
71
+
72
+ /*
73
+ * Return whether one parsed HTML child is an element node.
74
+ */
75
+ function isRichTextHTMLElement(node: RichTextHTMLChildNode): node is RichTextHTMLElement {
76
+ return 'tagName' in node;
77
+ }
78
+
79
+ /*
80
+ * Read one case-insensitive HTML attribute from a parsed element.
81
+ */
82
+ function getRichTextHTMLAttribute(element: RichTextHTMLElement, name: string): string | null {
83
+ return element.attrs.find((attribute) => attribute.name.toLowerCase() === name.toLowerCase())?.value || null;
84
+ }
85
+
86
+ /*
87
+ * Build one stable identity for an order-insensitive rich-text mark set.
88
+ */
89
+ function getRichTextHTMLMarkSetKey(marks?: RichTextMark[]): string {
90
+ return (marks || [])
91
+ .map((mark) => `${mark.type}:${mark.attrs?.href || mark.attrs?.token || ''}`)
92
+ .sort()
93
+ .join('|');
94
+ }
95
+
96
+ /*
97
+ * Add or replace one mark without retaining duplicate mark types.
98
+ */
99
+ function addRichTextHTMLMark(marks: RichTextMark[], mark: RichTextMark): RichTextMark[] {
100
+ return [...marks.filter((current) => current.type !== mark.type), mark];
101
+ }
102
+
103
+ /*
104
+ * Append normalized text and merge it with an adjacent equivalent run.
105
+ */
106
+ function appendRichTextHTMLText(content: RichTextInlineContent[], value: string, marks: RichTextMark[]): void {
107
+ const text = value.replace(/\s+/g, ' ');
108
+ if (!text) {
109
+ return;
110
+ }
111
+
112
+ const previous = content[content.length - 1];
113
+ if (previous?.type === 'text' && getRichTextHTMLMarkSetKey(previous.marks) === getRichTextHTMLMarkSetKey(marks)) {
114
+ previous.text = `${previous.text || ''}${text}`;
115
+ return;
116
+ }
117
+
118
+ content.push(marks.length ? { marks: marks.slice(), text, type: 'text' } : { text, type: 'text' });
119
+ }
120
+
121
+ /*
122
+ * Remove HTML-layout whitespace from the beginning and end of one block.
123
+ */
124
+ function trimRichTextHTMLInlineContent(content: RichTextInlineContent[]): RichTextInlineContent[] {
125
+ const trimmed = content.slice();
126
+ const first = trimmed[0];
127
+ if (first?.type === 'text') {
128
+ first.text = first.text?.replace(/^\s+/, '');
129
+ if (!first.text) {
130
+ trimmed.shift();
131
+ }
132
+ }
133
+
134
+ const last = trimmed[trimmed.length - 1];
135
+ if (last?.type === 'text') {
136
+ last.text = last.text?.replace(/\s+$/, '');
137
+ if (!last.text) {
138
+ trimmed.pop();
139
+ }
140
+ }
141
+ return trimmed;
142
+ }
143
+
144
+ /*
145
+ * Collect safe inline content while translating semantic HTML into marks.
146
+ */
147
+ function getRichTextHTMLInlineContent(
148
+ nodes: RichTextHTMLChildNode[],
149
+ parentMarks: RichTextMark[] = [],
150
+ depth = 0,
151
+ ): RichTextInlineContent[] {
152
+ if (depth >= FILE_CONSTANTS.maxTraversalDepth) {
153
+ return [];
154
+ }
155
+
156
+ const content: RichTextInlineContent[] = [];
157
+ for (const node of nodes) {
158
+ if (isRichTextHTMLTextNode(node)) {
159
+ appendRichTextHTMLText(content, node.value, parentMarks);
160
+ continue;
161
+ }
162
+ if (!isRichTextHTMLElement(node)) {
163
+ continue;
164
+ }
165
+
166
+ const tagName = node.tagName.toLowerCase();
167
+ if (FILE_CONSTANTS.skippedTags.has(tagName)) {
168
+ continue;
169
+ }
170
+ if (tagName === 'br') {
171
+ content.push({ type: 'hardBreak' });
172
+ continue;
173
+ }
174
+
175
+ let marks = parentMarks;
176
+ const markType = FILE_CONSTANTS.markTags[tagName];
177
+ if (markType) {
178
+ marks = addRichTextHTMLMark(marks, { type: markType });
179
+ }
180
+ if (tagName === 'a') {
181
+ const href = getRichTextHTMLAttribute(node, 'href')?.trim() || '';
182
+ if (NOTE_LINK_HREF_REGEX.test(href)) {
183
+ marks = addRichTextHTMLMark(marks, {
184
+ attrs: { href },
185
+ type: 'link',
186
+ });
187
+ }
188
+ }
189
+
190
+ const childContent = getRichTextHTMLInlineContent(node.childNodes, marks, depth + 1);
191
+ for (const child of childContent) {
192
+ if (child.type === 'hardBreak') {
193
+ content.push(child);
194
+ } else {
195
+ appendRichTextHTMLText(content, child.text || '', child.marks || []);
196
+ }
197
+ }
198
+ }
199
+ return content;
200
+ }
201
+
202
+ /*
203
+ * Collect safe raw text from a preformatted subtree without collapsing line
204
+ * endings or repeated spaces.
205
+ */
206
+ function getRichTextHTMLPreformattedText(nodes: RichTextHTMLChildNode[], depth = 0): string {
207
+ if (depth >= FILE_CONSTANTS.maxTraversalDepth) {
208
+ return '';
209
+ }
210
+
211
+ return nodes
212
+ .map((node) => {
213
+ if (isRichTextHTMLTextNode(node)) {
214
+ return node.value;
215
+ }
216
+ if (!isRichTextHTMLElement(node) || FILE_CONSTANTS.skippedTags.has(node.tagName.toLowerCase())) {
217
+ return '';
218
+ }
219
+ if (node.tagName.toLowerCase() === 'br') {
220
+ return '\n';
221
+ }
222
+ return getRichTextHTMLPreformattedText(node.childNodes, depth + 1);
223
+ })
224
+ .join('');
225
+ }
226
+
227
+ /*
228
+ * Convert preformatted text into code-marked runs and explicit hard breaks.
229
+ */
230
+ function getRichTextHTMLPreformattedContent(element: RichTextHTMLElement): RichTextInlineContent[] {
231
+ const content: RichTextInlineContent[] = [];
232
+ getRichTextHTMLPreformattedText(element.childNodes)
233
+ .replace(/\r\n?/g, '\n')
234
+ .split('\n')
235
+ .forEach((line, index) => {
236
+ if (index) {
237
+ content.push({ type: 'hardBreak' });
238
+ }
239
+ if (line) {
240
+ content.push({ marks: [{ type: 'code' }], text: line, type: 'text' });
241
+ }
242
+ });
243
+ return content;
244
+ }
245
+
246
+ /*
247
+ * Convert one parsed text-bearing element into a canonical content block.
248
+ */
249
+ function getRichTextHTMLTextBlock(
250
+ element: RichTextHTMLElement,
251
+ type: 'heading' | 'paragraph',
252
+ level?: RichTextHeadingLevel,
253
+ parentMarks: RichTextMark[] = [],
254
+ ): RichTextContent {
255
+ return {
256
+ ...(level ? { attrs: { level } } : {}),
257
+ content: trimRichTextHTMLInlineContent(getRichTextHTMLInlineContent(element.childNodes, parentMarks)),
258
+ type,
259
+ };
260
+ }
261
+
262
+ /*
263
+ * Convert one parsed list item while retaining supported nested lists.
264
+ */
265
+ function getRichTextHTMLListItem(element: RichTextHTMLElement, depth: number): RichTextContent {
266
+ const content = getRichTextHTMLBlocks(element.childNodes, depth + 1);
267
+ return {
268
+ content: content.length ? content : [{ content: [], type: 'paragraph' }],
269
+ type: 'listItem',
270
+ };
271
+ }
272
+
273
+ /*
274
+ * Convert one parsed list into ordered canonical list-item children.
275
+ */
276
+ function getRichTextHTMLList(element: RichTextHTMLElement, type: 'bulletList' | 'orderedList', depth: number): RichTextContent {
277
+ return {
278
+ content: element.childNodes.flatMap((node) =>
279
+ isRichTextHTMLElement(node) && node.tagName.toLowerCase() === 'li' ? [getRichTextHTMLListItem(node, depth)] : [],
280
+ ),
281
+ type,
282
+ };
283
+ }
284
+
285
+ /*
286
+ * Convert one recognized block element or return null for inline wrappers.
287
+ */
288
+ function getRichTextHTMLElementBlocks(element: RichTextHTMLElement, depth: number): RichTextContent[] | null {
289
+ const tagName = element.tagName.toLowerCase();
290
+ if (FILE_CONSTANTS.skippedTags.has(tagName)) {
291
+ return null;
292
+ }
293
+ if (tagName === 'p') {
294
+ return [getRichTextHTMLTextBlock(element, 'paragraph')];
295
+ }
296
+ if (/^h[1-6]$/.test(tagName)) {
297
+ return [getRichTextHTMLTextBlock(element, 'heading', Math.min(3, Number(tagName.slice(1))) as RichTextHeadingLevel)];
298
+ }
299
+ if (tagName === 'ul' || tagName === 'ol') {
300
+ return [getRichTextHTMLList(element, tagName === 'ul' ? 'bulletList' : 'orderedList', depth)];
301
+ }
302
+ if (tagName === 'blockquote') {
303
+ return [
304
+ {
305
+ content: getRichTextHTMLBlocks(element.childNodes, depth + 1),
306
+ type: 'blockquote',
307
+ },
308
+ ];
309
+ }
310
+ if (tagName === 'hr') {
311
+ return [{ type: 'divider' }];
312
+ }
313
+ if (tagName === 'pre') {
314
+ return [
315
+ {
316
+ content: getRichTextHTMLPreformattedContent(element),
317
+ type: 'paragraph',
318
+ },
319
+ ];
320
+ }
321
+ if (FILE_CONSTANTS.blockContainerTags.has(tagName)) {
322
+ return getRichTextHTMLBlocks(element.childNodes, depth + 1);
323
+ }
324
+ return null;
325
+ }
326
+
327
+ /*
328
+ * Convert parsed HTML children into canonical top-level rich-text blocks.
329
+ */
330
+ function getRichTextHTMLBlocks(nodes: RichTextHTMLChildNode[], depth = 0): RichTextContent[] {
331
+ if (depth >= FILE_CONSTANTS.maxTraversalDepth) {
332
+ return [];
333
+ }
334
+
335
+ const blocks: RichTextContent[] = [];
336
+ let inlineNodes: RichTextHTMLChildNode[] = [];
337
+
338
+ /*
339
+ * Flush adjacent top-level inline nodes into one paragraph.
340
+ */
341
+ const flushInlineNodes = () => {
342
+ const content = trimRichTextHTMLInlineContent(getRichTextHTMLInlineContent(inlineNodes, [], depth + 1));
343
+ if (content.length) {
344
+ blocks.push({ content, type: 'paragraph' });
345
+ }
346
+ inlineNodes = [];
347
+ };
348
+
349
+ for (const node of nodes) {
350
+ const elementBlocks = isRichTextHTMLElement(node) ? getRichTextHTMLElementBlocks(node, depth) : null;
351
+ if (elementBlocks === null) {
352
+ inlineNodes.push(node);
353
+ continue;
354
+ }
355
+
356
+ flushInlineNodes();
357
+ blocks.push(...elementBlocks);
358
+ }
359
+ flushInlineNodes();
360
+ return blocks;
361
+ }
362
+
363
+ /*
364
+ * Return whether a string contains supported semantic rich-text HTML markup.
365
+ */
366
+ export function containsRichTextHTMLMarkup(value: unknown): boolean {
367
+ return typeof value === 'string' && FILE_CONSTANTS.supportedHTMLPattern.test(value);
368
+ }
369
+
370
+ /*
371
+ * Parse untrusted HTML or plain text into one sanitized rich-text document.
372
+ */
373
+ export function richTextHTMLToDocument(value: unknown): RichTextDocument {
374
+ const source = typeof value === 'string' ? value.slice(0, NOTE_MAX_TEXT_CHARS) : '';
375
+ if (!FILE_CONSTANTS.htmlMarkupPattern.test(source)) {
376
+ return plainTextToNoteDoc(source);
377
+ }
378
+
379
+ const fragment = parseFragment(source);
380
+ return sanitizeNoteDoc({
381
+ content: getRichTextHTMLBlocks(fragment.childNodes),
382
+ type: 'doc',
383
+ version: NOTE_DOC_VERSION,
384
+ });
385
+ }