@airalogy/aimd-recorder 1.22.0 → 1.24.0

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 (95) hide show
  1. package/README.md +80 -0
  2. package/README.zh-CN.md +80 -0
  3. package/dist/{AimdCodeField-BN_0UQMx.js → AimdCodeField-CPjcXY4D.js} +1 -1
  4. package/dist/{AimdDnaSequenceField-Bhj28fP8.js → AimdDnaSequenceField-Dz-IONoA.js} +5 -4
  5. package/dist/{AimdEditor.vue_vue_type_style_index_0_lang-D7c01UqN.js → AimdEditor.vue_vue_type_style_index_0_lang-JAD--qFs.js} +1999 -1900
  6. package/dist/AimdEntityRefField-BE0s2o5T.js +229 -0
  7. package/dist/{AimdMarkdownField-GS15pv4z.js → AimdMarkdownField-BeD2t9JY.js} +5 -5
  8. package/dist/{AimdMarkdownNoteField-H9WP8tR6.js → AimdMarkdownNoteField-DIgGEYpj.js} +16 -16
  9. package/dist/{_commonjsHelpers-B5RozER-.js → _commonjsHelpers-ByX85dGu.js} +12 -19
  10. package/dist/_plugin-vue_export-helper-CHgC5LLL.js +9 -0
  11. package/dist/aimd-recorder.css +1 -1
  12. package/dist/{arc-B50G9-kH.js → arc-CLJJdrm0.js} +1 -1
  13. package/dist/{architectureDiagram-3BPJPVTR-D9mBEbpY.js → architectureDiagram-3BPJPVTR-BizrFPnS.js} +3 -3
  14. package/dist/{blockDiagram-GPEHLZMM-Cs4swgto.js → blockDiagram-GPEHLZMM-IHDih8JW.js} +4 -4
  15. package/dist/{c4Diagram-AAUBKEIU-C12HKS3r.js → c4Diagram-AAUBKEIU-BQtg8m_M.js} +2 -2
  16. package/dist/{channel-D69VnjVz.js → channel-D8q7AX1Z.js} +1 -1
  17. package/dist/{chunk-2J33WTMH-oc-89G5c.js → chunk-2J33WTMH-C24lbKon.js} +1 -1
  18. package/dist/{chunk-4BX2VUAB-BDJS9G3r.js → chunk-4BX2VUAB-1m_lB_xe.js} +1 -1
  19. package/dist/{chunk-55IACEB6-BPl3uHcA.js → chunk-55IACEB6-BE5Nj-sd.js} +1 -1
  20. package/dist/{chunk-727SXJPM-pWe-vDGf.js → chunk-727SXJPM-Cg-Xw_d_.js} +5 -5
  21. package/dist/{chunk-AQP2D5EJ-D-R5sIr1.js → chunk-AQP2D5EJ-BvRpPCiY.js} +3 -3
  22. package/dist/{chunk-FMBD7UC4-bo6Qyom1.js → chunk-FMBD7UC4-D_44MTsg.js} +1 -1
  23. package/dist/{chunk-ND2GUHAM-DQMvtYV7.js → chunk-ND2GUHAM-tVBIo4LA.js} +1 -1
  24. package/dist/{chunk-QZHKN3VN-DlCn3HON.js → chunk-QZHKN3VN-B91HYLks.js} +1 -1
  25. package/dist/{classDiagram-v2-Q7XG4LA2-DzUwWFwr.js → classDiagram-4FO5ZUOK-CkejvTAN.js} +2 -2
  26. package/dist/{classDiagram-4FO5ZUOK-DzUwWFwr.js → classDiagram-v2-Q7XG4LA2-CkejvTAN.js} +2 -2
  27. package/dist/components.js +3869 -3359
  28. package/dist/composables.js +98 -93
  29. package/dist/{cose-bilkent-S5V4N54A-BXLMzfpO.js → cose-bilkent-S5V4N54A-CNcuriOF.js} +2 -2
  30. package/dist/{dagre-BM42HDAG-DHnofIh9.js → dagre-BM42HDAG-DMqFGafq.js} +3 -3
  31. package/dist/{diagram-2AECGRRQ-BqTTVPsm.js → diagram-2AECGRRQ-Cksd3pP3.js} +2 -2
  32. package/dist/{diagram-5GNKFQAL-D5p1UVbw.js → diagram-5GNKFQAL-SVjLnDJG.js} +3 -3
  33. package/dist/{diagram-KO2AKTUF-Uuoz9cFn.js → diagram-KO2AKTUF-DfNIAG6w.js} +2 -2
  34. package/dist/{diagram-LMA3HP47-W001U31X.js → diagram-LMA3HP47-DPOyCMGB.js} +2 -2
  35. package/dist/{diagram-OG6HWLK6-DL516LDr.js → diagram-OG6HWLK6-BDURmT37.js} +3 -3
  36. package/dist/{erDiagram-TEJ5UH35-CCxgMb67.js → erDiagram-TEJ5UH35-N991qII9.js} +4 -4
  37. package/dist/{flowDiagram-I6XJVG4X-nXGdmC0O.js → flowDiagram-I6XJVG4X-BABRFuk-.js} +6 -6
  38. package/dist/{ganttDiagram-6RSMTGT7-Bi9Ro7_Z.js → ganttDiagram-6RSMTGT7-BMDnK96S.js} +3 -3
  39. package/dist/{gitGraphDiagram-PVQCEYII-w1kNAy4E.js → gitGraphDiagram-PVQCEYII-cEvL7Dss.js} +3 -3
  40. package/dist/{graph-CpOkL_eZ.js → graph-BA09aCvZ.js} +1 -1
  41. package/dist/index.js +125 -113
  42. package/dist/{infoDiagram-5YYISTIA-Bde_w9T1.js → infoDiagram-5YYISTIA-DpC1Zthd.js} +1 -1
  43. package/dist/{ishikawaDiagram-YF4QCWOH-x5M1KR0l.js → ishikawaDiagram-YF4QCWOH-CMEt_f-x.js} +1 -1
  44. package/dist/{journeyDiagram-JHISSGLW-CIDQP8Zm.js → journeyDiagram-JHISSGLW-C0Qw169C.js} +4 -4
  45. package/dist/{kanban-definition-UN3LZRKU-CKgO7sG8.js → kanban-definition-UN3LZRKU-caROmSUy.js} +2 -2
  46. package/dist/{layout-BZYprqYR.js → layout-CH65__O4.js} +2 -2
  47. package/dist/{linear-ClSH2F_v.js → linear-B1VXpcsy.js} +1 -1
  48. package/dist/{mermaid.core-CcRV6K2R.js → mermaid.core-Cbmwvfvk.js} +35 -35
  49. package/dist/{mindmap-definition-RKZ34NQL-s3h6uszV.js → mindmap-definition-RKZ34NQL-DpTR5ilS.js} +3 -3
  50. package/dist/{pieDiagram-4H26LBE5-CgiazyWv.js → pieDiagram-4H26LBE5-Cb_KrmWC.js} +3 -3
  51. package/dist/{quadrantDiagram-W4KKPZXB-DCPVgHoW.js → quadrantDiagram-W4KKPZXB-B5_NswmK.js} +2 -2
  52. package/dist/record.js +77 -72
  53. package/dist/{requirementDiagram-4Y6WPE33-DE6F9oSB.js → requirementDiagram-4Y6WPE33-OFwfat5D.js} +3 -3
  54. package/dist/{sankeyDiagram-5OEKKPKP-DZZoFFr-.js → sankeyDiagram-5OEKKPKP-BaawdZEE.js} +1 -1
  55. package/dist/{sequenceDiagram-3UESZ5HK-DaYEOl60.js → sequenceDiagram-3UESZ5HK-DLv8X8ef.js} +3 -3
  56. package/dist/{stateDiagram-AJRCARHV-BmgpHJlH.js → stateDiagram-AJRCARHV-B6F3wrsd.js} +4 -4
  57. package/dist/{stateDiagram-v2-BHNVJYJU-D49CHQD6.js → stateDiagram-v2-BHNVJYJU-BcNEoshv.js} +2 -2
  58. package/dist/{timeline-definition-PNZ67QCA-DdVLoCkC.js → timeline-definition-PNZ67QCA-CvdHJ4eQ.js} +2 -2
  59. package/dist/useCodeBlockRendering-D2viVPtA.js +3158 -0
  60. package/dist/useFieldRendering-Co4DOOvL.js +1120 -0
  61. package/dist/useVarHelpers-Du2obGza.js +3474 -0
  62. package/dist/validation-oyqyD7Jp.js +5601 -0
  63. package/dist/{vennDiagram-CIIHVFJN-CCcMKcd7.js → vennDiagram-CIIHVFJN-U0GlQDjX.js} +1 -1
  64. package/dist/{wardleyDiagram-YWT4CUSO-R4UGgGWY.js → wardleyDiagram-YWT4CUSO-CzF_KMcn.js} +2 -2
  65. package/dist/{xychartDiagram-2RQKCTM6-DyFhCubk.js → xychartDiagram-2RQKCTM6-Cljki2Vk.js} +2 -2
  66. package/package.json +6 -4
  67. package/src/__tests__/collector-field.test.ts +269 -0
  68. package/src/__tests__/record-search-render.test.ts +1 -0
  69. package/src/__tests__/record-validation.test.ts +378 -0
  70. package/src/__tests__/recorder-wysiwyg-field-host.test.ts +26 -0
  71. package/src/__tests__/var-field-render.test.ts +64 -2
  72. package/src/components/AimdCollectorField.vue +233 -0
  73. package/src/components/AimdEntityRefField.vue +314 -0
  74. package/src/components/AimdRecorder.vue +285 -7
  75. package/src/components/AimdRecorderEditor.vue +51 -1
  76. package/src/components/AimdRecorderWysiwygFieldHost.vue +10 -0
  77. package/src/components/AimdRecorderWysiwygSurface.vue +166 -4
  78. package/src/components/AimdVarField.vue +39 -2
  79. package/src/components/AimdVarTableField.vue +38 -21
  80. package/src/components/index.ts +4 -0
  81. package/src/components/recorderMilkdownPlugin.ts +16 -0
  82. package/src/composables/__tests__/useVarHelpers.test.ts +32 -0
  83. package/src/composables/index.ts +12 -0
  84. package/src/composables/useCollectors.ts +399 -0
  85. package/src/composables/useVarHelpers.ts +130 -2
  86. package/src/index.ts +32 -2
  87. package/src/locales.ts +140 -2
  88. package/src/record/index.ts +14 -0
  89. package/src/record/validation.ts +772 -0
  90. package/src/styles/collector-field.css +281 -0
  91. package/src/styles/recorder-surface.css +163 -0
  92. package/src/styles/recorder.css +33 -0
  93. package/src/types.ts +168 -1
  94. package/dist/index-Dkrf2LJl.js +0 -1308
  95. package/dist/useCodeBlockRendering-CCuoP52e.js +0 -6103
@@ -0,0 +1,772 @@
1
+ import type { ExtractedAimdFields } from "@airalogy/aimd-core/types"
2
+ import { getAimdBuiltInTypeMetadata } from "@airalogy/aimd-core/utils"
3
+ import type { ErrorObject } from "ajv"
4
+ import Ajv2020 from "ajv/dist/2020"
5
+ import addFormats from "ajv-formats"
6
+ import type { AimdRecorderMessages } from "../locales"
7
+ import type {
8
+ AimdFieldMeta,
9
+ AimdFieldState,
10
+ AimdProtocolRecordData,
11
+ AimdRecordValidationSchema,
12
+ AimdRecorderFieldType,
13
+ AimdRecorderValidationCode,
14
+ AimdRecorderValidationIssue,
15
+ AimdRecorderValidationResult,
16
+ } from "../types"
17
+ import { getNumericConstraintViolation } from "../composables/useVarHelpers"
18
+
19
+ export interface ValidateAimdRecordOptions {
20
+ fieldMeta?: Record<string, AimdFieldMeta>
21
+ /** Pydantic-compatible JSON Schema returned by protocol parsing. */
22
+ schema?: AimdRecordValidationSchema
23
+ /** Limit validation to one or more canonical field keys. */
24
+ fieldKeys?: string[]
25
+ messages: AimdRecorderMessages["validation"]
26
+ }
27
+
28
+ type SchemaSection = "var" | "step" | "check" | "quiz"
29
+
30
+ interface ResolvedSchemaSection {
31
+ section: SchemaSection
32
+ schema: Record<string, unknown>
33
+ }
34
+
35
+ const SCHEMA_SECTION_ALIASES: Array<{ section: SchemaSection; keys: string[] }> = [
36
+ { section: "var", keys: ["vars", "var", "research_variable"] },
37
+ { section: "step", keys: ["steps", "step", "research_step"] },
38
+ { section: "check", keys: ["checks", "check", "research_check"] },
39
+ { section: "quiz", keys: ["quiz", "quizzes", "research_quiz"] },
40
+ ]
41
+
42
+ const schemaAjv = new Ajv2020({
43
+ allErrors: true,
44
+ allowUnionTypes: true,
45
+ coerceTypes: true,
46
+ strict: false,
47
+ })
48
+ addFormats(schemaAjv)
49
+ const compiledSchemaValidators = new WeakMap<object, ReturnType<typeof schemaAjv.compile>>()
50
+
51
+ function getCompiledSchemaValidator(schema: Record<string, unknown>) {
52
+ const cached = compiledSchemaValidators.get(schema)
53
+ if (cached) return cached
54
+ const validate = schemaAjv.compile(schema)
55
+ compiledSchemaValidators.set(schema, validate)
56
+ return validate
57
+ }
58
+
59
+ function isRecord(value: unknown): value is Record<string, unknown> {
60
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value)
61
+ }
62
+
63
+ function hasOwn(value: object, key: PropertyKey): boolean {
64
+ return Object.prototype.hasOwnProperty.call(value, key)
65
+ }
66
+
67
+ function isEmptyValue(value: unknown): boolean {
68
+ if (value === null || value === undefined) return true
69
+ if (typeof value === "string") return value.trim() === ""
70
+ if (Array.isArray(value)) return value.length === 0
71
+ return false
72
+ }
73
+
74
+ function resolveRequired(
75
+ meta: AimdFieldMeta | undefined,
76
+ kwargs: Record<string, unknown> | undefined,
77
+ inferred: boolean,
78
+ ): boolean {
79
+ if (typeof meta?.required === "boolean") return meta.required
80
+ if (typeof kwargs?.required === "boolean") return kwargs.required
81
+ return inferred
82
+ }
83
+
84
+ function resolvePattern(meta: AimdFieldMeta | undefined, kwargs?: Record<string, unknown>): string | undefined {
85
+ const value = meta?.pattern ?? kwargs?.pattern
86
+ return typeof value === "string" && value ? value : undefined
87
+ }
88
+
89
+ function decodeJsonPointerSegment(value: string): string {
90
+ return value.replace(/~1/g, "/").replace(/~0/g, "~")
91
+ }
92
+
93
+ function getJsonPointerSegments(path: string): string[] {
94
+ return path
95
+ .split("/")
96
+ .slice(1)
97
+ .map(decodeJsonPointerSegment)
98
+ }
99
+
100
+ export function getAimdVarTableCellFieldKey(table: string, rowIndex: number, column: string): string {
101
+ return `var_table:${table}:${rowIndex}:${column}`
102
+ }
103
+
104
+ function getCheckLikeValue(value: unknown): unknown {
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value
106
+ return (value as { checked?: unknown }).checked
107
+ }
108
+
109
+ function normalizeValidationValue(value: unknown): unknown {
110
+ if (Array.isArray(value)) {
111
+ return value.map(normalizeValidationValue)
112
+ }
113
+ if (value instanceof Date) {
114
+ return value.toISOString()
115
+ }
116
+ if (!isRecord(value)) {
117
+ return value
118
+ }
119
+
120
+ const decimalLike = value as { toNumber?: () => unknown; toString?: () => string }
121
+ if (typeof decimalLike.toNumber === "function" && typeof decimalLike.toString === "function") {
122
+ try {
123
+ const numericValue = decimalLike.toNumber()
124
+ if (typeof numericValue === "number" && Number.isFinite(numericValue)) return numericValue
125
+ }
126
+ catch {
127
+ // Fall through to ordinary object normalization.
128
+ }
129
+ }
130
+
131
+ if (typeof value.airalogy_file_id === "string") return value.airalogy_file_id
132
+ if ((value.type === "file" || value.type === "image") && typeof value.id === "string") return value.id
133
+ if (hasOwn(value, "value") && (hasOwn(value, "displayedValue") || hasOwn(value, "formattedValue") || hasOwn(value, "type"))) {
134
+ return normalizeValidationValue(value.value)
135
+ }
136
+ if (!hasOwn(value, "value") && typeof value.formattedValue === "string") return value.formattedValue
137
+
138
+ return Object.fromEntries(
139
+ Object.entries(value).map(([key, nestedValue]) => [key, normalizeValidationValue(nestedValue)]),
140
+ )
141
+ }
142
+
143
+ function getNormalizedSchemaSectionValue(section: SchemaSection, record: AimdProtocolRecordData): Record<string, unknown> {
144
+ const source = record[section] ?? {}
145
+ if (section === "step" || section === "check") {
146
+ return Object.fromEntries(
147
+ Object.entries(source).map(([key, value]) => [key, normalizeValidationValue(getCheckLikeValue(value))]),
148
+ )
149
+ }
150
+ return normalizeValidationValue(source) as Record<string, unknown>
151
+ }
152
+
153
+ function resolveSchemaSections(schema: AimdRecordValidationSchema | undefined): ResolvedSchemaSection[] {
154
+ if (!schema) return []
155
+
156
+ if (schema.type === "object" || isRecord(schema.properties) || Array.isArray(schema.required)) {
157
+ return [{ section: "var", schema }]
158
+ }
159
+
160
+ const resolved: ResolvedSchemaSection[] = []
161
+ for (const entry of SCHEMA_SECTION_ALIASES) {
162
+ const sectionSchema = entry.keys
163
+ .map(key => schema[key])
164
+ .find(isRecord)
165
+ if (sectionSchema) resolved.push({ section: entry.section, schema: sectionSchema })
166
+ }
167
+ return resolved
168
+ }
169
+
170
+ function getSchemaCoveredFieldKeys(schemaSections: ResolvedSchemaSection[]): Set<string> {
171
+ const keys = new Set<string>()
172
+ for (const { section, schema } of schemaSections) {
173
+ if (!isRecord(schema.properties)) continue
174
+ for (const id of Object.keys(schema.properties)) {
175
+ keys.add(`${section}:${id}`)
176
+ if (section === "var") keys.add(`var_table:${id}`)
177
+ }
178
+ }
179
+ return keys
180
+ }
181
+
182
+ function resolveLocalSchemaReference(
183
+ root: Record<string, unknown>,
184
+ schema: Record<string, unknown>,
185
+ ): Record<string, unknown> {
186
+ const ref = schema.$ref
187
+ if (typeof ref !== "string" || !ref.startsWith("#/")) return schema
188
+
189
+ let current: unknown = root
190
+ for (const segment of getJsonPointerSegments(ref.slice(1))) {
191
+ if (!isRecord(current)) return schema
192
+ current = current[segment]
193
+ }
194
+ return isRecord(current) ? current : schema
195
+ }
196
+
197
+ function findArraySchema(
198
+ root: Record<string, unknown>,
199
+ candidate: unknown,
200
+ visited = new Set<object>(),
201
+ ): Record<string, unknown> | undefined {
202
+ if (!isRecord(candidate) || visited.has(candidate)) return undefined
203
+ visited.add(candidate)
204
+ const schema = resolveLocalSchemaReference(root, candidate)
205
+ if (schema !== candidate && !visited.has(schema)) {
206
+ const referenced = findArraySchema(root, schema, visited)
207
+ if (referenced) return referenced
208
+ }
209
+ if (schema.type === "array" || hasOwn(schema, "items")) return schema
210
+
211
+ for (const branchKey of ["anyOf", "oneOf", "allOf"] as const) {
212
+ const branches = schema[branchKey]
213
+ if (!Array.isArray(branches)) continue
214
+ for (const branch of branches) {
215
+ const arraySchema = findArraySchema(root, branch, visited)
216
+ if (arraySchema) return arraySchema
217
+ }
218
+ }
219
+ return undefined
220
+ }
221
+
222
+ function getSchemaRequiredFieldKeys(schemaSections: ResolvedSchemaSection[]): Set<string> {
223
+ const keys = new Set<string>()
224
+ for (const { section, schema } of schemaSections) {
225
+ const required = new Set(
226
+ Array.isArray(schema.required)
227
+ ? schema.required.filter((key): key is string => typeof key === "string")
228
+ : [],
229
+ )
230
+ const properties = isRecord(schema.properties) ? schema.properties : {}
231
+ for (const [id, propertySchema] of Object.entries(properties)) {
232
+ if (required.has(id)) {
233
+ keys.add(`${section}:${id}`)
234
+ if (section === "var") keys.add(`var_table:${id}`)
235
+ }
236
+ if (section !== "var") continue
237
+
238
+ const arraySchema = findArraySchema(schema, propertySchema)
239
+ const itemSchema = isRecord(arraySchema?.items)
240
+ ? resolveLocalSchemaReference(schema, arraySchema.items)
241
+ : undefined
242
+ if (!itemSchema || !Array.isArray(itemSchema.required)) continue
243
+ for (const column of itemSchema.required) {
244
+ if (typeof column === "string") keys.add(`var_table:${id}:${column}`)
245
+ }
246
+ }
247
+ }
248
+ return keys
249
+ }
250
+
251
+ function getFieldLabel(
252
+ fields: ExtractedAimdFields,
253
+ section: AimdRecorderFieldType,
254
+ id: string,
255
+ rowIndex?: number,
256
+ column?: string,
257
+ messages?: AimdRecorderMessages["validation"],
258
+ ): string {
259
+ if (section === "var") {
260
+ const field = fields.var_definitions?.find(candidate => candidate.id === id)
261
+ return field?.title || id
262
+ }
263
+ if (section === "var_table") {
264
+ const table = fields.var_table?.find(candidate => candidate.id === id)
265
+ if (column && rowIndex !== undefined && messages) {
266
+ const columnDefinition = table?.subvars.find(candidate => candidate.id === column)
267
+ return messages.tableCell(rowIndex + 1, columnDefinition?.title || column)
268
+ }
269
+ return table?.title || id
270
+ }
271
+ if (section === "quiz") {
272
+ const quiz = fields.quiz?.find(candidate => candidate.id === id)
273
+ return quiz?.title || quiz?.stem || id
274
+ }
275
+ return id
276
+ }
277
+
278
+ function getIssueValue(
279
+ record: AimdProtocolRecordData,
280
+ section: AimdRecorderFieldType,
281
+ id: string,
282
+ rowIndex?: number,
283
+ column?: string,
284
+ ): unknown {
285
+ if (section === "var") return record.var[id]
286
+ if (section === "var_table") {
287
+ const rows = record.var[id]
288
+ if (rowIndex === undefined || !Array.isArray(rows)) return rows
289
+ const row = rows[rowIndex]
290
+ return column && isRecord(row) ? row[column] : row
291
+ }
292
+ if (section === "step") return getCheckLikeValue(record.step[id])
293
+ if (section === "check") return getCheckLikeValue(record.check[id])
294
+ return record.quiz[id]
295
+ }
296
+
297
+ function mapSchemaErrorToIssue(
298
+ error: ErrorObject,
299
+ section: SchemaSection,
300
+ fields: ExtractedAimdFields,
301
+ record: AimdProtocolRecordData,
302
+ messages: AimdRecorderMessages["validation"],
303
+ ): AimdRecorderValidationIssue | null {
304
+ const segments = getJsonPointerSegments(error.instancePath)
305
+ if (error.keyword === "required" && typeof error.params.missingProperty === "string") {
306
+ segments.push(error.params.missingProperty)
307
+ }
308
+ if (error.keyword === "additionalProperties" && typeof error.params.additionalProperty === "string") {
309
+ segments.push(error.params.additionalProperty)
310
+ }
311
+ if (error.keyword === "unevaluatedProperties" && typeof error.params.unevaluatedProperty === "string") {
312
+ segments.push(error.params.unevaluatedProperty)
313
+ }
314
+ if (error.keyword === "dependentRequired" && typeof error.params.missingProperty === "string") {
315
+ segments.push(error.params.missingProperty)
316
+ }
317
+
318
+ const id = segments[0]
319
+ if (!id) {
320
+ return {
321
+ fieldKey: `${section}:$schema`,
322
+ section,
323
+ code: "schema",
324
+ message: messages.schema("Schema", error.message || error.keyword),
325
+ keyword: error.keyword,
326
+ instancePath: error.instancePath,
327
+ schemaPath: error.schemaPath,
328
+ }
329
+ }
330
+
331
+ const isTable = section === "var" && fields.var_table.some(table => table.id === id)
332
+ const issueSection: AimdRecorderFieldType = isTable ? "var_table" : section
333
+ const rowIndex = isTable && /^\d+$/.test(segments[1] ?? "") ? Number(segments[1]) : undefined
334
+ const column = isTable && rowIndex !== undefined ? segments[2] : undefined
335
+ const fieldKey = isTable && rowIndex !== undefined && column
336
+ ? getAimdVarTableCellFieldKey(id, rowIndex, column)
337
+ : `${issueSection}:${id}`
338
+ const label = getFieldLabel(fields, issueSection, id, rowIndex, column, messages)
339
+ const detail = error.message || error.keyword
340
+
341
+ let code: AimdRecorderValidationCode = "schema"
342
+ let message = messages.schema(label, detail)
343
+ switch (error.keyword) {
344
+ case "required":
345
+ code = "required"
346
+ message = messages.required(label)
347
+ break
348
+ case "pattern":
349
+ code = "pattern"
350
+ message = messages.pattern(label)
351
+ break
352
+ case "enum":
353
+ case "const":
354
+ code = "enum"
355
+ message = messages.enum(label)
356
+ break
357
+ case "type": {
358
+ code = "type"
359
+ const expected = String(error.params.type || "the expected type")
360
+ message = messages.type(label, expected)
361
+ break
362
+ }
363
+ case "format": {
364
+ code = "format"
365
+ const format = String(error.params.format || "the expected")
366
+ message = messages.format(label, format)
367
+ break
368
+ }
369
+ case "minimum":
370
+ code = "numeric"
371
+ message = messages.numeric(label, `Must be >= ${String(error.params.limit)}`)
372
+ break
373
+ case "exclusiveMinimum":
374
+ code = "numeric"
375
+ message = messages.numeric(label, `Must be > ${String(error.params.limit)}`)
376
+ break
377
+ case "maximum":
378
+ code = "numeric"
379
+ message = messages.numeric(label, `Must be <= ${String(error.params.limit)}`)
380
+ break
381
+ case "exclusiveMaximum":
382
+ code = "numeric"
383
+ message = messages.numeric(label, `Must be < ${String(error.params.limit)}`)
384
+ break
385
+ case "multipleOf":
386
+ code = "numeric"
387
+ message = messages.numeric(label, `Must be a multiple of ${String(error.params.multipleOf)}`)
388
+ break
389
+ }
390
+
391
+ return {
392
+ fieldKey,
393
+ section: issueSection,
394
+ code,
395
+ message,
396
+ value: getIssueValue(record, issueSection, id, rowIndex, column),
397
+ rowIndex,
398
+ column,
399
+ keyword: error.keyword,
400
+ instancePath: error.instancePath,
401
+ schemaPath: error.schemaPath,
402
+ }
403
+ }
404
+
405
+ function validateSchema(
406
+ issues: AimdRecorderValidationIssue[],
407
+ fields: ExtractedAimdFields,
408
+ record: AimdProtocolRecordData,
409
+ schemaSections: ResolvedSchemaSection[],
410
+ messages: AimdRecorderMessages["validation"],
411
+ ) {
412
+ if (schemaSections.length === 0) return
413
+
414
+ for (const { section, schema } of schemaSections) {
415
+ let validate: ReturnType<typeof schemaAjv.compile>
416
+ try {
417
+ validate = getCompiledSchemaValidator(schema)
418
+ }
419
+ catch (error) {
420
+ issues.push({
421
+ fieldKey: `${section}:$schema`,
422
+ section,
423
+ code: "schema",
424
+ message: messages.schema("Schema", error instanceof Error ? error.message : String(error)),
425
+ keyword: "compile",
426
+ })
427
+ continue
428
+ }
429
+
430
+ validate(getNormalizedSchemaSectionValue(section, record))
431
+ for (const error of validate.errors ?? []) {
432
+ const issue = mapSchemaErrorToIssue(error, section, fields, record, messages)
433
+ if (issue) issues.push(issue)
434
+ }
435
+ }
436
+ }
437
+
438
+ function addIssue(
439
+ issues: AimdRecorderValidationIssue[],
440
+ fieldKey: string,
441
+ section: AimdRecorderFieldType,
442
+ code: AimdRecorderValidationCode,
443
+ message: string,
444
+ value: unknown,
445
+ details?: Pick<AimdRecorderValidationIssue, "rowIndex" | "column" | "keyword">,
446
+ ) {
447
+ issues.push({ fieldKey, section, code, message, value, ...details })
448
+ }
449
+
450
+ function normalizeTypeName(type: string | undefined): string {
451
+ if (!type) return ""
452
+ return type
453
+ .replace(/\s+/g, "")
454
+ .replace(/^(?:typing\.)?Optional\[(.*)\]$/i, "$1")
455
+ .split("|")
456
+ .find(part => !/^(?:none|null|undefined)$/i.test(part))
457
+ ?.replace(/^(?:builtins\.|airalogy\.types\.)/, "")
458
+ .toLowerCase() ?? ""
459
+ }
460
+
461
+ function getExpectedRuntimeType(type: string | undefined): "string" | "number" | "integer" | "boolean" | "array" | "object" | undefined {
462
+ const normalized = normalizeTypeName(type)
463
+ if (/^(?:str|string|date|datetime|time|uuid|decimal)$/.test(normalized)) return "string"
464
+ if (/^(?:float|number)$/.test(normalized)) return "number"
465
+ if (/^(?:int|integer)$/.test(normalized)) return "integer"
466
+ if (/^(?:bool|boolean)$/.test(normalized)) return "boolean"
467
+ if (/^(?:list|list\[|array|tuple|set)/.test(normalized)) return "array"
468
+ const builtInType = getAimdBuiltInTypeMetadata(type)?.type
469
+ if (builtInType === "string" || builtInType === "number" || builtInType === "integer" || builtInType === "boolean" || builtInType === "array" || builtInType === "object") {
470
+ return builtInType
471
+ }
472
+ return undefined
473
+ }
474
+
475
+ function valueMatchesType(value: unknown, expected: ReturnType<typeof getExpectedRuntimeType>): boolean {
476
+ if (!expected) return true
477
+ if (expected === "array") return Array.isArray(value)
478
+ if (expected === "object") return isRecord(value)
479
+ if (expected === "boolean") return typeof value === "boolean" || value === "true" || value === "false"
480
+ if (expected === "integer") {
481
+ const numeric = typeof value === "number" ? value : Number(value)
482
+ return Number.isInteger(numeric)
483
+ }
484
+ if (expected === "number") {
485
+ const numeric = typeof value === "number" ? value : Number(value)
486
+ return Number.isFinite(numeric)
487
+ }
488
+ return typeof value === "string"
489
+ }
490
+
491
+ function getFallbackFormat(type: string | undefined, kwargs?: Record<string, unknown>): string | undefined {
492
+ if (typeof kwargs?.format === "string" && kwargs.format) return kwargs.format
493
+ const normalized = normalizeTypeName(type)
494
+ if (normalized === "date") return "date"
495
+ if (normalized === "datetime") return "date-time"
496
+ if (normalized === "time") return "time"
497
+ if (normalized === "uuid") return "uuid"
498
+ return undefined
499
+ }
500
+
501
+ function valueMatchesFormat(value: unknown, format: string): boolean {
502
+ if (typeof value !== "string") return false
503
+ if (format === "date") return /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`))
504
+ if (format === "date-time") return !Number.isNaN(Date.parse(value))
505
+ if (format === "time") return /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|[+-][0-2]\d:[0-5]\d)?$/.test(value)
506
+ if (format === "uuid") return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
507
+ if (format === "email") return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
508
+ return true
509
+ }
510
+
511
+ function validateValue(
512
+ issues: AimdRecorderValidationIssue[],
513
+ options: ValidateAimdRecordOptions,
514
+ input: {
515
+ fieldKey: string
516
+ section: AimdRecorderFieldType
517
+ label: string
518
+ value: unknown
519
+ type?: string
520
+ kwargs?: Record<string, unknown>
521
+ meta?: AimdFieldMeta
522
+ enumValues?: unknown[]
523
+ rowIndex?: number
524
+ column?: string
525
+ inferredRequired?: boolean
526
+ schemaCovered?: boolean
527
+ schemaRequired?: boolean
528
+ },
529
+ ) {
530
+ const {
531
+ fieldKey,
532
+ section,
533
+ label,
534
+ value,
535
+ type,
536
+ kwargs,
537
+ meta,
538
+ enumValues,
539
+ rowIndex,
540
+ column,
541
+ inferredRequired = false,
542
+ schemaCovered = false,
543
+ schemaRequired = false,
544
+ } = input
545
+ const details = { rowIndex, column }
546
+ const fallbackKwargs = schemaCovered ? undefined : kwargs
547
+ const fallbackEnumValues = schemaCovered ? undefined : enumValues
548
+ const required = schemaCovered
549
+ ? schemaRequired || meta?.required === true
550
+ : resolveRequired(meta, kwargs, inferredRequired)
551
+
552
+ if (required && isEmptyValue(value)) {
553
+ addIssue(issues, fieldKey, section, "required", options.messages.required(label), value, details)
554
+ return
555
+ }
556
+ if (isEmptyValue(value)) return
557
+
558
+ const pattern = resolvePattern(meta, fallbackKwargs)
559
+ if (pattern) {
560
+ try {
561
+ if (!new RegExp(pattern).test(String(value))) {
562
+ addIssue(issues, fieldKey, section, "pattern", options.messages.pattern(label), value, details)
563
+ }
564
+ }
565
+ catch {
566
+ addIssue(issues, fieldKey, section, "pattern", options.messages.pattern(label), value, details)
567
+ }
568
+ }
569
+
570
+ const allowedValues = meta?.enumOptions?.map(option => option.value) ?? fallbackEnumValues
571
+ if (allowedValues?.length && !allowedValues.some(item => Object.is(item, value))) {
572
+ addIssue(issues, fieldKey, section, "enum", options.messages.enum(label), value, details)
573
+ }
574
+
575
+ if (!schemaCovered) {
576
+ const expectedType = getExpectedRuntimeType(type)
577
+ if (!valueMatchesType(value, expectedType)) {
578
+ addIssue(issues, fieldKey, section, "type", options.messages.type(label, expectedType || type || "valid"), value, details)
579
+ }
580
+
581
+ const format = getFallbackFormat(type, kwargs)
582
+ if (format && !valueMatchesFormat(value, format)) {
583
+ addIssue(issues, fieldKey, section, "format", options.messages.format(label, format), value, details)
584
+ }
585
+ }
586
+
587
+ const numericViolation = getNumericConstraintViolation(value, type, fallbackKwargs)
588
+ if (numericViolation) {
589
+ addIssue(issues, fieldKey, section, "numeric", options.messages.numeric(label, numericViolation), value, details)
590
+ }
591
+ }
592
+
593
+ function matchesFieldSelector(fieldKey: string, selector: string): boolean {
594
+ if (fieldKey === selector) return true
595
+ const selectorParts = selector.split(":")
596
+ if (selectorParts[0] !== "var_table") return false
597
+
598
+ if (selectorParts.length === 2) {
599
+ return fieldKey.startsWith(`${selector}:`)
600
+ }
601
+ if (selectorParts.length === 3) {
602
+ const [section, table, column] = selectorParts
603
+ const fieldParts = fieldKey.split(":")
604
+ return fieldParts[0] === section
605
+ && fieldParts[1] === table
606
+ && fieldParts.length === 4
607
+ && fieldParts[3] === column
608
+ }
609
+ return false
610
+ }
611
+
612
+ export function matchesAimdValidationFieldSelector(fieldKey: string, selector: string): boolean {
613
+ return matchesFieldSelector(fieldKey, selector)
614
+ }
615
+
616
+ function finalizeIssues(
617
+ issues: AimdRecorderValidationIssue[],
618
+ fieldKeys: string[] | undefined,
619
+ ): AimdRecorderValidationIssue[] {
620
+ const selected = fieldKeys?.length
621
+ ? issues.filter(issue => fieldKeys.some(selector => matchesFieldSelector(issue.fieldKey, selector)))
622
+ : issues
623
+ const keysWithSpecificIssues = new Set(
624
+ selected
625
+ .filter(issue => issue.keyword !== "anyOf" && issue.keyword !== "oneOf")
626
+ .map(issue => issue.fieldKey),
627
+ )
628
+ const keysWithRequiredIssues = new Set(
629
+ selected
630
+ .filter(issue => issue.code === "required")
631
+ .map(issue => issue.fieldKey),
632
+ )
633
+ const seen = new Set<string>()
634
+ return selected.filter((issue) => {
635
+ if (issue.code !== "required" && keysWithRequiredIssues.has(issue.fieldKey)) return false
636
+ if ((issue.keyword === "anyOf" || issue.keyword === "oneOf") && keysWithSpecificIssues.has(issue.fieldKey)) {
637
+ return false
638
+ }
639
+ const identity = `${issue.fieldKey}\u0000${issue.code}`
640
+ if (seen.has(identity)) return false
641
+ seen.add(identity)
642
+ return true
643
+ })
644
+ }
645
+
646
+ export function validateAimdRecord(
647
+ fields: ExtractedAimdFields,
648
+ record: AimdProtocolRecordData,
649
+ options: ValidateAimdRecordOptions,
650
+ ): AimdRecorderValidationResult {
651
+ const issues: AimdRecorderValidationIssue[] = []
652
+ const fieldMeta = options.fieldMeta ?? {}
653
+ const schemaSections = resolveSchemaSections(options.schema)
654
+ const schemaCoveredKeys = getSchemaCoveredFieldKeys(schemaSections)
655
+ const schemaRequiredKeys = getSchemaRequiredFieldKeys(schemaSections)
656
+
657
+ validateSchema(issues, fields, record, schemaSections, options.messages)
658
+
659
+ for (const field of fields.var_definitions ?? []) {
660
+ const fieldKey = `var:${field.id}`
661
+ validateValue(issues, options, {
662
+ fieldKey,
663
+ section: "var",
664
+ label: field.title || field.id,
665
+ value: record.var[field.id],
666
+ type: field.type,
667
+ kwargs: field.kwargs,
668
+ meta: fieldMeta[fieldKey],
669
+ enumValues: field.enum,
670
+ inferredRequired: !hasOwn(field, "default"),
671
+ schemaCovered: schemaCoveredKeys.has(fieldKey),
672
+ schemaRequired: schemaRequiredKeys.has(fieldKey),
673
+ })
674
+ }
675
+
676
+ for (const table of fields.var_table ?? []) {
677
+ const tableKey = `var_table:${table.id}`
678
+ const rows = Array.isArray(record.var[table.id]) ? record.var[table.id] as Record<string, unknown>[] : []
679
+ const schemaCovered = schemaCoveredKeys.has(tableKey)
680
+ const required = schemaCovered
681
+ ? schemaRequiredKeys.has(tableKey) || fieldMeta[tableKey]?.required === true
682
+ : resolveRequired(fieldMeta[tableKey], table.kwargs, !hasOwn(table, "default"))
683
+ if (required && rows.length === 0) {
684
+ addIssue(issues, tableKey, "var_table", "required", options.messages.required(table.title || table.id), rows)
685
+ continue
686
+ }
687
+ rows.forEach((row, rowIndex) => {
688
+ for (const column of table.subvars) {
689
+ const columnMetaKey = `${tableKey}:${column.id}`
690
+ const cellKey = getAimdVarTableCellFieldKey(table.id, rowIndex, column.id)
691
+ validateValue(issues, options, {
692
+ fieldKey: cellKey,
693
+ section: "var_table",
694
+ label: options.messages.tableCell(rowIndex + 1, column.title || column.id),
695
+ value: row?.[column.id],
696
+ type: column.type,
697
+ kwargs: column.kwargs,
698
+ meta: fieldMeta[columnMetaKey],
699
+ enumValues: column.enum,
700
+ rowIndex,
701
+ column: column.id,
702
+ inferredRequired: !hasOwn(column, "default"),
703
+ schemaCovered,
704
+ schemaRequired: schemaRequiredKeys.has(columnMetaKey),
705
+ })
706
+ }
707
+ })
708
+ }
709
+
710
+ for (const id of fields.step ?? []) {
711
+ const fieldKey = `step:${id}`
712
+ validateValue(issues, options, {
713
+ fieldKey,
714
+ section: "step",
715
+ label: id,
716
+ value: getCheckLikeValue(record.step[id]),
717
+ meta: fieldMeta[fieldKey],
718
+ schemaCovered: schemaCoveredKeys.has(fieldKey),
719
+ schemaRequired: schemaRequiredKeys.has(fieldKey),
720
+ })
721
+ }
722
+ for (const id of fields.check ?? []) {
723
+ const fieldKey = `check:${id}`
724
+ validateValue(issues, options, {
725
+ fieldKey,
726
+ section: "check",
727
+ label: id,
728
+ value: getCheckLikeValue(record.check[id]),
729
+ meta: fieldMeta[fieldKey],
730
+ schemaCovered: schemaCoveredKeys.has(fieldKey),
731
+ schemaRequired: schemaRequiredKeys.has(fieldKey),
732
+ })
733
+ }
734
+ for (const quiz of fields.quiz ?? []) {
735
+ const fieldKey = `quiz:${quiz.id}`
736
+ const extra = isRecord(quiz.extra) ? quiz.extra : undefined
737
+ validateValue(issues, options, {
738
+ fieldKey,
739
+ section: "quiz",
740
+ label: quiz.title || quiz.stem || quiz.id,
741
+ value: record.quiz[quiz.id],
742
+ kwargs: extra,
743
+ meta: fieldMeta[fieldKey],
744
+ schemaCovered: schemaCoveredKeys.has(fieldKey),
745
+ schemaRequired: schemaRequiredKeys.has(fieldKey),
746
+ })
747
+ }
748
+
749
+ const finalIssues = finalizeIssues(issues, options.fieldKeys)
750
+ const fieldState: Record<string, AimdFieldState> = {}
751
+ for (const issue of finalIssues) {
752
+ fieldState[issue.fieldKey] ??= { validationError: issue.message }
753
+ }
754
+ return {
755
+ valid: finalIssues.length === 0,
756
+ issues: finalIssues,
757
+ fieldState,
758
+ validatedFieldKeys: options.fieldKeys?.length ? [...options.fieldKeys] : undefined,
759
+ }
760
+ }
761
+
762
+ export function validateAimdField(
763
+ fields: ExtractedAimdFields,
764
+ record: AimdProtocolRecordData,
765
+ fieldKey: string,
766
+ options: ValidateAimdRecordOptions,
767
+ ): AimdRecorderValidationResult {
768
+ return validateAimdRecord(fields, record, {
769
+ ...options,
770
+ fieldKeys: [fieldKey],
771
+ })
772
+ }