@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,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
+ }