asma-core-helpers 0.26.0 → 0.27.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 (32) hide show
  1. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  2. package/lib/collaboration/applyOperation.js +237 -33
  3. package/lib/collaboration/applyOperation.js.map +1 -1
  4. package/lib/collaboration/index.d.ts +1 -0
  5. package/lib/collaboration/index.d.ts.map +1 -1
  6. package/lib/collaboration/index.js +1 -0
  7. package/lib/collaboration/index.js.map +1 -1
  8. package/lib/collaboration/operations.d.ts +35 -1
  9. package/lib/collaboration/operations.d.ts.map +1 -1
  10. package/lib/collaboration/operations.js +7 -0
  11. package/lib/collaboration/operations.js.map +1 -1
  12. package/lib/collaboration/schemas.d.ts +101 -1
  13. package/lib/collaboration/schemas.d.ts.map +1 -1
  14. package/lib/collaboration/schemas.js +109 -6
  15. package/lib/collaboration/schemas.js.map +1 -1
  16. package/lib/collaboration/templateDocument.d.ts +28 -1
  17. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  18. package/lib/collaboration/templateDocument.js.map +1 -1
  19. package/lib/collaboration/testHelpers/documentGenerator.d.ts +4 -0
  20. package/lib/collaboration/testHelpers/documentGenerator.d.ts.map +1 -1
  21. package/lib/collaboration/testHelpers/documentGenerator.js +100 -4
  22. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  23. package/package.json +1 -1
  24. package/src/collaboration/applyOperation.test.ts +240 -1
  25. package/src/collaboration/applyOperation.ts +280 -36
  26. package/src/collaboration/index.ts +1 -0
  27. package/src/collaboration/operations.ts +35 -0
  28. package/src/collaboration/property.test.ts +20 -0
  29. package/src/collaboration/schemas.test.ts +87 -1
  30. package/src/collaboration/schemas.ts +137 -1
  31. package/src/collaboration/templateDocument.ts +27 -1
  32. package/src/collaboration/testHelpers/documentGenerator.ts +101 -5
@@ -70,6 +70,17 @@ const highlightRuleSchema = type({
70
70
  ...({ '[string]': 'unknown' } as const),
71
71
  })
72
72
 
73
+ const narrativeRuleSchema = type({
74
+ condition: ruleConditionSchema,
75
+ ...({ '[string]': 'unknown' } as const),
76
+ })
77
+
78
+ const qnrRuleSchema = type({
79
+ condition: ruleConditionSchema,
80
+ templateFamilyId: 'string',
81
+ '+': 'reject',
82
+ })
83
+
73
84
  const questionGridConfigSchema = type({
74
85
  columnIds: 'string[]?',
75
86
  minRows: 'number?',
@@ -82,8 +93,20 @@ const questionGridConfigSchema = type({
82
93
  rowTitle: 'string?',
83
94
  })
84
95
 
96
+ const layoutPlacementSchema = type({
97
+ row: 'number',
98
+ cell: 'number',
99
+ keepCellSize: 'boolean?',
100
+ })
101
+
102
+ const questionGridRowEditorSchema = type({
103
+ "layoutByQuestionId?": recordOf(layoutPlacementSchema),
104
+ ...({ '[string]': 'unknown' } as const),
105
+ })
106
+
85
107
  const questionGridPresentationSchema = type({
86
108
  headerTabId: 'string?',
109
+ "rowEditor?": questionGridRowEditorSchema,
87
110
  defaultColumnWidthsByQuestionId: 'Record<string, number>?',
88
111
  ...({ '[string]': 'unknown' } as const),
89
112
  })
@@ -199,6 +222,10 @@ export const qnrTemplateDocumentSchema = type({
199
222
  visibilityRuleOrderByQuestionId: 'Record<string, string[]>?',
200
223
  "highlightRulesById?": recordOf(highlightRuleSchema),
201
224
  highlightRuleOrderByQuestionId: 'Record<string, string[]>?',
225
+ "narrativeRulesById?": recordOf(narrativeRuleSchema),
226
+ narrativeRuleOrderByQuestionId: 'Record<string, string[]>?',
227
+ "qnrRulesById?": recordOf(qnrRuleSchema),
228
+ qnrRuleOrderByQuestionId: 'Record<string, string[]>?',
202
229
  "dataMappingsById?": recordOf(dataMappingSchema),
203
230
  "mappingNodesById?": recordOf(mappingNodeSchema),
204
231
  "mappingBindingsById?": recordOf(mappingBindingSchema),
@@ -236,6 +263,20 @@ export const templateOpSchema = type.or(
236
263
  type({ type: '"question.updateField"', questionId: 'string', field: 'string', value: opValue }),
237
264
  type({ type: '"question.move"', questionId: 'string', toIndex: 'number' }),
238
265
  type({ type: '"question.delete"', questionId: 'string' }),
266
+ type({
267
+ type: '"gridColumn.create"',
268
+ questionId: 'string',
269
+ columnQuestionId: 'string',
270
+ questionType: type.enumerated(...QUESTION_TYPES),
271
+ atIndex: 'number?',
272
+ }),
273
+ type({ type: '"gridColumn.move"', questionId: 'string', columnQuestionId: 'string', toIndex: 'number' }),
274
+ type({
275
+ type: '"gridColumn.setLayout"',
276
+ questionId: 'string',
277
+ columnQuestionId: 'string',
278
+ placement: type.or(layoutPlacementSchema, type('null')),
279
+ }),
239
280
  type({ type: '"gridRow.create"', questionId: 'string', rowId: 'string', label: 'string?', atIndex: 'number?' }),
240
281
  type({ type: '"gridRow.move"', questionId: 'string', rowId: 'string', afterRowId: 'string | null' }),
241
282
  type({ type: '"gridRow.delete"', questionId: 'string', rowId: 'string' }),
@@ -313,6 +354,17 @@ export const templateOpSchema = type.or(
313
354
  type({ type: '"visibilityRule.delete"', ruleId: 'string' }),
314
355
  type({ type: '"highlightRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
315
356
  type({ type: '"highlightRule.delete"', ruleId: 'string' }),
357
+ type({ type: '"narrativeRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
358
+ type({ type: '"narrativeRule.delete"', ruleId: 'string' }),
359
+ type({
360
+ type: '"qnrRule.set"',
361
+ ruleId: 'string',
362
+ questionId: 'string',
363
+ condition: ruleConditionSchema,
364
+ templateFamilyId: 'string',
365
+ '+': 'reject',
366
+ }),
367
+ type({ type: '"qnrRule.delete"', ruleId: 'string' }),
316
368
  )
317
369
 
318
370
  export const answerOpSchema = type.or(
@@ -555,6 +607,85 @@ export const findDuplicateBindingTargets = (
555
607
  return [...byTarget.values()].filter((entry) => entry.bindingIds.length > 1)
556
608
  }
557
609
 
610
+ // ─────────────────────────────── question ownership ───────────────────────────────
611
+
612
+ export type QuestionOwnershipViolation = {
613
+ law: 'QUESTION-OWNERSHIP'
614
+ kind: 'orphan' | 'ordered-and-column' | 'two-grids' | 'dangling-column'
615
+ questionId: string
616
+ gridQuestionIds: string[]
617
+ path: string
618
+ detail: string
619
+ }
620
+
621
+ /**
622
+ * A question has exactly one structural owner: either `questionOrder` or one grid's
623
+ * `columnIds`. This validator covers imported/directly-written documents in addition to
624
+ * the reducer, and reports absent column records as dangling ownership references.
625
+ */
626
+ export const findQuestionOwnershipViolations = (
627
+ document: QnrTemplateDocument,
628
+ ): QuestionOwnershipViolation[] => {
629
+ const ownersByQuestionId = new Map<string, string[]>()
630
+ for (const [gridQuestionId, question] of Object.entries(document.questionsById ?? {})) {
631
+ for (const columnQuestionId of question.grid?.columnIds ?? []) {
632
+ const owners = ownersByQuestionId.get(columnQuestionId) ?? []
633
+ if (!owners.includes(gridQuestionId)) owners.push(gridQuestionId)
634
+ ownersByQuestionId.set(columnQuestionId, owners)
635
+ }
636
+ }
637
+
638
+ const violations: QuestionOwnershipViolation[] = []
639
+ for (const [questionId, gridQuestionIds] of ownersByQuestionId) {
640
+ if (document.questionsById?.[questionId] !== undefined) continue
641
+ violations.push({
642
+ law: 'QUESTION-OWNERSHIP',
643
+ kind: 'dangling-column',
644
+ questionId,
645
+ gridQuestionIds,
646
+ path: `questionsById.${gridQuestionIds[0]}.grid.columnIds`,
647
+ detail: 'column question is absent from questionsById',
648
+ })
649
+ }
650
+
651
+ const topLevel = new Set(document.questionOrder)
652
+ for (const questionId of Object.keys(document.questionsById ?? {})) {
653
+ const gridQuestionIds = ownersByQuestionId.get(questionId) ?? []
654
+ const path = `questionsById.${questionId}`
655
+ if (!topLevel.has(questionId) && gridQuestionIds.length === 0) {
656
+ violations.push({
657
+ law: 'QUESTION-OWNERSHIP',
658
+ kind: 'orphan',
659
+ questionId,
660
+ gridQuestionIds,
661
+ path,
662
+ detail: 'question is neither top-level nor owned by a grid',
663
+ })
664
+ }
665
+ if (topLevel.has(questionId) && gridQuestionIds.length > 0) {
666
+ violations.push({
667
+ law: 'QUESTION-OWNERSHIP',
668
+ kind: 'ordered-and-column',
669
+ questionId,
670
+ gridQuestionIds,
671
+ path,
672
+ detail: 'question is both top-level and owned by a grid',
673
+ })
674
+ }
675
+ if (gridQuestionIds.length > 1) {
676
+ violations.push({
677
+ law: 'QUESTION-OWNERSHIP',
678
+ kind: 'two-grids',
679
+ questionId,
680
+ gridQuestionIds,
681
+ path,
682
+ detail: 'question is owned by more than one grid',
683
+ })
684
+ }
685
+ }
686
+ return violations
687
+ }
688
+
558
689
  // ─────────────────────────────── typed validators ───────────────────────────────
559
690
 
560
691
  export type Validation<T> = { ok: true; value: T } | { ok: false; summary: string }
@@ -573,9 +704,14 @@ export const validateTemplateDocument = validate<QnrTemplateDocument>(qnrTemplat
573
704
  * Full template-document admission check for the contract test: schema + DOC-LAW-1/2 lints +
574
705
  * default lint + binding uniqueness. A document passes only in its canonical minimal form.
575
706
  */
576
- export const findTemplateDocumentContractViolations = (document: QnrTemplateDocument): DocLawViolation[] => [
707
+ export type TemplateDocumentContractViolation = DocLawViolation | QuestionOwnershipViolation
708
+
709
+ export const findTemplateDocumentContractViolations = (
710
+ document: QnrTemplateDocument,
711
+ ): TemplateDocumentContractViolation[] => [
577
712
  ...findDocLawViolations(document),
578
713
  ...findDocLawDefaultViolations(document),
714
+ ...findQuestionOwnershipViolations(document),
579
715
  ]
580
716
 
581
717
  export const findDuplicateBindingTargetsSummary = (document: QnrTemplateDocument): string[] =>
@@ -25,6 +25,8 @@ export type FilterId = string
25
25
  export type MappingId = string
26
26
  export type VisibilityRuleId = string
27
27
  export type HighlightRuleId = string
28
+ export type NarrativeRuleId = string
29
+ export type QnrRuleId = string
28
30
 
29
31
  /** A scalar a document may carry. Deliberately not `any`: DOC-LAW-2 bans `null`. */
30
32
  export type DocScalar = string | number | boolean
@@ -110,10 +112,24 @@ export type QuestionGridConfig = {
110
112
  /**
111
113
  * Grid-owned presentation (OQ-V2-17/25): row-editor layout, filters, grid actions,
112
114
  * highlight rules, the header-tab reference and authored default column widths live
113
- * here — there is no parallel `settings_ui` or `layoutByQuestionId` map.
115
+ * here — there is no parallel top-level layout map; `rowEditor` owns it.
114
116
  */
117
+ /** One atomic row-editor placement for a grid-owned column. */
118
+ export type LayoutPlacement = {
119
+ row: number
120
+ cell: number
121
+ keepCellSize?: boolean
122
+ }
123
+
124
+ /** Row-editor state belongs to the owning grid, keyed by its column question ids. */
125
+ export type QuestionGridRowEditor = {
126
+ layoutByQuestionId?: Record<QuestionId, LayoutPlacement>
127
+ [key: string]: unknown
128
+ }
129
+
115
130
  export type QuestionGridPresentation = {
116
131
  headerTabId?: TabId
132
+ rowEditor?: QuestionGridRowEditor
117
133
  /** OQ-V2-25: authored defaults; per-user widths are preference state outside both documents. */
118
134
  defaultColumnWidthsByQuestionId?: Record<QuestionId, number>
119
135
  [key: string]: unknown
@@ -166,6 +182,12 @@ export type RuleCondition = {
166
182
 
167
183
  export type VisibilityRule = { condition: RuleCondition; [key: string]: unknown }
168
184
  export type HighlightRule = { condition: RuleCondition; [key: string]: unknown }
185
+ export type NarrativeRule = { condition: RuleCondition; [key: string]: unknown }
186
+ export type QnrRule = {
187
+ condition: RuleCondition
188
+ /** A `qnr_templates.id` family reference; pinned versions are intentionally unrepresentable. */
189
+ templateFamilyId: string
190
+ }
169
191
 
170
192
  /** One traversal step. Many questions off one entity share a single node (§2.2a). */
171
193
  export type MappingNode = {
@@ -235,6 +257,10 @@ export type QnrTemplateDocument = {
235
257
  visibilityRuleOrderByQuestionId?: Record<QuestionId, VisibilityRuleId[]>
236
258
  highlightRulesById?: Record<HighlightRuleId, HighlightRule>
237
259
  highlightRuleOrderByQuestionId?: Record<QuestionId, HighlightRuleId[]>
260
+ narrativeRulesById?: Record<NarrativeRuleId, NarrativeRule>
261
+ narrativeRuleOrderByQuestionId?: Record<QuestionId, NarrativeRuleId[]>
262
+ qnrRulesById?: Record<QnrRuleId, QnrRule>
263
+ qnrRuleOrderByQuestionId?: Record<QuestionId, QnrRuleId[]>
238
264
  dataMappingsById?: Record<MappingId, QnrDataMapping>
239
265
  mappingNodesById?: Record<NodeId, MappingNode>
240
266
  mappingBindingsById?: Record<BindingId, MappingBinding>
@@ -27,10 +27,15 @@ const NEW_NODE_ID = (n: number): string => `n-${n}`
27
27
  const NEW_BINDING_ID = (n: number): string => `b-${n}`
28
28
  const NEW_FILTER_ID = (n: number): string => `f-${n}`
29
29
  const NEW_VISIBILITY_RULE_ID = (n: number): string => `vr-${n}`
30
+ const NEW_COLUMN_ID = (n: number): string => `c-${n}`
31
+ const NEW_NARRATIVE_RULE_ID = (n: number): string => `nr-${n}`
32
+ const NEW_QNR_RULE_ID = (n: number): string => `qr-${n}`
30
33
 
31
34
  type IdPools = {
32
35
  questions: string[]
33
36
  grids: string[]
37
+ columns: string[]
38
+ columnOwnerById: Record<string, string>
34
39
  gridRows: string[]
35
40
  alternatives: string[]
36
41
  tabs: string[]
@@ -40,11 +45,15 @@ type IdPools = {
40
45
  filters: string[]
41
46
  visibilityRules: string[]
42
47
  highlightRules: string[]
48
+ narrativeRules: string[]
49
+ qnrRules: string[]
43
50
  }
44
51
 
45
52
  const emptyPools = (): IdPools => ({
46
53
  questions: [],
47
54
  grids: [],
55
+ columns: [],
56
+ columnOwnerById: {},
48
57
  gridRows: [],
49
58
  alternatives: [],
50
59
  tabs: [],
@@ -54,6 +63,8 @@ const emptyPools = (): IdPools => ({
54
63
  filters: [],
55
64
  visibilityRules: [],
56
65
  highlightRules: [],
66
+ narrativeRules: [],
67
+ qnrRules: [],
57
68
  })
58
69
 
59
70
  /** Picks an id from a pool, or mints a new one when the pool is empty. */
@@ -65,7 +76,7 @@ const pickOrFallback = (random: () => number, pool: string[], fallback: string):
65
76
  pool.length === 0 ? fallback : pick(random, pool)
66
77
 
67
78
  /** A schema-valid value for the given question field (op payloads are validated before the reducer). */
68
- const fieldValue = (field: 'label' | 'required' | 'scale.from' | 'grid.singleRow' | 'grid.columnIds', random: () => number) => {
79
+ const fieldValue = (field: 'label' | 'required' | 'scale.from' | 'grid.singleRow', random: () => number) => {
69
80
  switch (field) {
70
81
  case 'label':
71
82
  return pick(random, ['Hei', 'Ha det', 'Tittel'])
@@ -74,8 +85,6 @@ const fieldValue = (field: 'label' | 'required' | 'scale.from' | 'grid.singleRow
74
85
  return pick(random, [true, false] as const)
75
86
  case 'scale.from':
76
87
  return 1
77
- case 'grid.columnIds':
78
- return pick(random, [['c-0'], ['c-1', 'c-2'], []] as Array<string[]>)
79
88
  }
80
89
  }
81
90
 
@@ -114,6 +123,7 @@ export const generateOpSequence = (
114
123
  }
115
124
 
116
125
  const nextOp = (random: () => number, pools: IdPools): TemplateOp => {
126
+ if (maybe(random, 0.22)) return nextAddedContractOp(random, pools)
117
127
  const roll = random()
118
128
 
119
129
  if (roll < 0.1) {
@@ -125,7 +135,7 @@ const nextOp = (random: () => number, pools: IdPools): TemplateOp => {
125
135
  }
126
136
  if (roll < 0.3) {
127
137
  const questionId = idOrNew(random, pools.questions, NEW_QUESTION_ID)
128
- const field = pick(random, ['label', 'required', 'scale.from', 'grid.singleRow', 'grid.columnIds'] as const)
138
+ const field = pick(random, ['label', 'required', 'scale.from', 'grid.singleRow'] as const)
129
139
  // The op schema validates op payloads before the reducer runs, so generated ops must
130
140
  // be schema-valid: each field gets a value of the field's own type.
131
141
  const value = fieldValue(field, random)
@@ -199,14 +209,88 @@ const nextOp = (random: () => number, pools: IdPools): TemplateOp => {
199
209
  }
200
210
  }
201
211
 
212
+ /** Operations added by ASMA-7676, kept in a dedicated mix so every seeded run exercises them. */
213
+ const nextAddedContractOp = (random: () => number, pools: IdPools): TemplateOp => {
214
+ const choice = Math.floor(random() * 9)
215
+ const columnQuestionId = pickOrFallback(random, pools.columns, 'c-ghost')
216
+ const ownerQuestionId = pools.columnOwnerById[columnQuestionId] ?? pickOrFallback(random, pools.grids, 'g-ghost')
217
+ const questionId = idOrNew(random, pools.questions, NEW_QUESTION_ID)
218
+ switch (choice) {
219
+ case 0:
220
+ return {
221
+ type: 'gridColumn.create',
222
+ questionId: pickOrFallback(random, pools.grids, 'g-ghost'),
223
+ columnQuestionId: NEW_COLUMN_ID(pools.columns.length),
224
+ questionType: pick(random, ['TextShort', 'DateField', 'RadioButtons'] as const),
225
+ atIndex: Math.floor(random() * 4),
226
+ }
227
+ case 1:
228
+ return {
229
+ type: 'gridColumn.move',
230
+ questionId: ownerQuestionId,
231
+ columnQuestionId,
232
+ toIndex: Math.floor(random() * 5),
233
+ }
234
+ case 2:
235
+ return {
236
+ type: 'gridColumn.setLayout',
237
+ questionId: ownerQuestionId,
238
+ columnQuestionId,
239
+ placement: maybe(random, 0.25)
240
+ ? null
241
+ : { row: Math.floor(random() * 3), cell: Math.floor(random() * 4), keepCellSize: true },
242
+ }
243
+ case 3:
244
+ return {
245
+ type: 'narrativeRule.set',
246
+ ruleId: NEW_NARRATIVE_RULE_ID(pools.narrativeRules.length),
247
+ questionId,
248
+ condition: { sourceQuestionId: pickOrFallback(random, pools.questions, 'q-ghost') },
249
+ }
250
+ case 4:
251
+ return {
252
+ type: 'narrativeRule.delete',
253
+ ruleId: pickOrFallback(random, pools.narrativeRules, 'nr-ghost'),
254
+ }
255
+ case 5:
256
+ return {
257
+ type: 'qnrRule.set',
258
+ ruleId: NEW_QNR_RULE_ID(pools.qnrRules.length),
259
+ questionId,
260
+ condition: { sourceQuestionId: pickOrFallback(random, pools.questions, 'q-ghost') },
261
+ templateFamilyId: `family-${Math.floor(random() * 5)}`,
262
+ }
263
+ case 6:
264
+ return { type: 'qnrRule.delete', ruleId: pickOrFallback(random, pools.qnrRules, 'qr-ghost') }
265
+ case 7:
266
+ return { type: 'question.move', questionId: columnQuestionId, toIndex: Math.floor(random() * 5) }
267
+ default:
268
+ return {
269
+ type: 'gridColumn.setLayout',
270
+ questionId: ownerQuestionId,
271
+ columnQuestionId,
272
+ placement: null,
273
+ }
274
+ }
275
+ }
276
+
202
277
  const updatePools = (op: TemplateOp, ok: boolean, pools: IdPools): void => {
203
278
  if (!ok) return
204
279
  switch (op.type) {
205
280
  case 'question.create':
206
281
  pools.questions.push(op.questionId)
282
+ if (op.questionType === 'QuestionGrid') pools.grids.push(op.questionId)
207
283
  break
208
284
  case 'question.delete':
209
285
  pools.questions = pools.questions.filter((id) => id !== op.questionId)
286
+ pools.grids = pools.grids.filter((id) => id !== op.questionId)
287
+ pools.columns = pools.columns.filter((id) => id !== op.questionId)
288
+ delete pools.columnOwnerById[op.questionId]
289
+ break
290
+ case 'gridColumn.create':
291
+ pools.questions.push(op.columnQuestionId)
292
+ pools.columns.push(op.columnQuestionId)
293
+ pools.columnOwnerById[op.columnQuestionId] = op.questionId
210
294
  break
211
295
  case 'gridRow.create':
212
296
  pools.gridRows.push(op.rowId)
@@ -229,7 +313,19 @@ const updatePools = (op: TemplateOp, ok: boolean, pools: IdPools): void => {
229
313
  pools.filters.push(op.filterId)
230
314
  break
231
315
  case 'visibilityRule.set':
232
- pools.visibilityRules.push(op.ruleId)
316
+ if (!pools.visibilityRules.includes(op.ruleId)) pools.visibilityRules.push(op.ruleId)
317
+ break
318
+ case 'narrativeRule.set':
319
+ if (!pools.narrativeRules.includes(op.ruleId)) pools.narrativeRules.push(op.ruleId)
320
+ break
321
+ case 'narrativeRule.delete':
322
+ pools.narrativeRules = pools.narrativeRules.filter((id) => id !== op.ruleId)
323
+ break
324
+ case 'qnrRule.set':
325
+ if (!pools.qnrRules.includes(op.ruleId)) pools.qnrRules.push(op.ruleId)
326
+ break
327
+ case 'qnrRule.delete':
328
+ pools.qnrRules = pools.qnrRules.filter((id) => id !== op.ruleId)
233
329
  break
234
330
  case 'mappingBinding.create':
235
331
  pools.bindings.push(op.bindingId)