asma-core-helpers 0.32.0 → 0.34.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 (48) hide show
  1. package/lib/collaboration/applyOperation.d.ts +5 -13
  2. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  3. package/lib/collaboration/applyOperation.js +450 -20
  4. package/lib/collaboration/applyOperation.js.map +1 -1
  5. package/lib/collaboration/operations.d.ts +113 -1
  6. package/lib/collaboration/operations.d.ts.map +1 -1
  7. package/lib/collaboration/operations.js +7 -0
  8. package/lib/collaboration/operations.js.map +1 -1
  9. package/lib/collaboration/schemas.d.ts +54 -0
  10. package/lib/collaboration/schemas.d.ts.map +1 -1
  11. package/lib/collaboration/schemas.js +74 -1
  12. package/lib/collaboration/schemas.js.map +1 -1
  13. package/lib/collaboration/templateDocument.d.ts +194 -0
  14. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  15. package/lib/collaboration/templateDocument.js +104 -0
  16. package/lib/collaboration/templateDocument.js.map +1 -1
  17. package/lib/collaboration/testHelpers/documentGenerator.d.ts +24 -0
  18. package/lib/collaboration/testHelpers/documentGenerator.d.ts.map +1 -1
  19. package/lib/collaboration/testHelpers/documentGenerator.js +180 -2
  20. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  21. package/lib/collaboration/typeContracts.d.ts +73 -1
  22. package/lib/collaboration/typeContracts.d.ts.map +1 -1
  23. package/lib/g-definitions.d.ts +17 -0
  24. package/lib/g-definitions.d.ts.map +1 -1
  25. package/lib/g-definitions.js +13 -0
  26. package/lib/g-definitions.js.map +1 -1
  27. package/lib/helpers/sectionPath.helpers.d.ts +64 -0
  28. package/lib/helpers/sectionPath.helpers.d.ts.map +1 -0
  29. package/lib/helpers/sectionPath.helpers.js +68 -0
  30. package/lib/helpers/sectionPath.helpers.js.map +1 -0
  31. package/lib/index.d.ts +1 -0
  32. package/lib/index.d.ts.map +1 -1
  33. package/lib/index.js +1 -0
  34. package/lib/index.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/collaboration/applyOperation.ts +517 -17
  37. package/src/collaboration/operations.ts +95 -0
  38. package/src/collaboration/property.test.ts +49 -0
  39. package/src/collaboration/schemas.ts +82 -0
  40. package/src/collaboration/templateDocument.ts +238 -1
  41. package/src/collaboration/testHelpers/documentGenerator.ts +201 -2
  42. package/src/collaboration/typeContracts.ts +106 -1
  43. package/src/collaboration/typedAuthoring.test.ts +1091 -0
  44. package/src/collaboration/typedAuthoringHardening.test.ts +344 -1
  45. package/src/g-definitions.ts +29 -0
  46. package/src/helpers/sectionPath.helpers.test.ts +159 -0
  47. package/src/helpers/sectionPath.helpers.ts +129 -0
  48. package/src/index.ts +1 -0
@@ -6,9 +6,14 @@ import { canonicalJson, reduceToMinimalForm } from './canonicalize.js'
6
6
  import { findDocLawViolations } from './docLaws.js'
7
7
  import type { TemplateOp } from './operations.js'
8
8
  import { templateDocumentIsDefault, templateOpSchema, validateTemplateDocument } from './schemas.js'
9
+ import { QUESTION_TYPES, type QuestionType } from './questionTypes.js'
9
10
  import {
10
11
  emptyTemplateDocument,
12
+ isExpressionAlternativeToken,
13
+ isExpressionTargetToken,
11
14
  isKnownActionKind,
15
+ makeExpressionAlternativeToken,
16
+ makeExpressionTargetToken,
12
17
  isKnownMappingFilterOperator,
13
18
  MAPPING_FILTER_OPERATORS,
14
19
  type QnrTemplateDocument,
@@ -639,3 +644,1089 @@ describe('the bundle carries a mapping fragment', () => {
639
644
  assert.deepEqual(Object.keys(bundle.mappingFiltersById['f-1']), ['fieldId', 'operator', 'values'])
640
645
  })
641
646
  })
647
+
648
+ // ───────────────────── tab membership and the counted-grid subset (freeze §3a) ─────────────────────
649
+
650
+ /**
651
+ * Membership is a THIRD tab concern beside layout, not a view of it.
652
+ *
653
+ * Post-release importer scrutiny corrected the field inventory: legacy `dependent_question_ids` is tab
654
+ * membership, and the committed fixture proving it carries a counted composite member with **no**
655
+ * positional placement. So the placement key set is strictly narrower than membership, and any attempt
656
+ * to derive one from the other loses that member — which is why these cases assert the three locations
657
+ * move independently and only cascade in the one direction the freeze specifies.
658
+ */
659
+ describe('tab membership', () => {
660
+ const tab = (doc: QnrTemplateDocument, id = 't-1') => doc.tabsById?.[id]
661
+
662
+ it('appends, does not duplicate, and moves to a clamped index', () => {
663
+ const base = apply(
664
+ [
665
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true },
666
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'g-1', include: true },
667
+ ],
668
+ scaffold(),
669
+ )
670
+ assert.deepEqual(tab(base)?.questionIds, ['q-top', 'g-1'])
671
+
672
+ // Re-including an existing member is idempotent on the list, not a second entry.
673
+ assert.deepEqual(
674
+ tab(apply([{ type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true }], base))?.questionIds,
675
+ ['q-top', 'g-1'],
676
+ )
677
+ // An out-of-range index clamps rather than tearing the list.
678
+ assert.deepEqual(
679
+ tab(apply([{ type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true, atIndex: 99 }], base))
680
+ ?.questionIds,
681
+ ['g-1', 'q-top'],
682
+ )
683
+ assert.deepEqual(
684
+ tab(apply([{ type: 'tab.setQuestion', tabId: 't-1', questionId: 'g-1', include: true, atIndex: 0 }], base))
685
+ ?.questionIds,
686
+ ['g-1', 'q-top'],
687
+ )
688
+ })
689
+
690
+ it('omits the emptied list and keeps the tab', () => {
691
+ const doc = apply(
692
+ [
693
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true },
694
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: false },
695
+ ],
696
+ scaffold(),
697
+ )
698
+ // DOC-LAW-2: an empty list is absent, never stored as `[]`.
699
+ assert.equal('questionIds' in (tab(doc) ?? {}), false)
700
+ assert.deepEqual(tab(doc), { label: 'Første' })
701
+ assert.deepEqual(findDocLawViolations(doc), [])
702
+ })
703
+
704
+ it('refuses including a question the document does not have, but allows excluding one', () => {
705
+ throwsConflict(
706
+ () => apply([{ type: 'tab.setQuestion', tabId: 't-1', questionId: 'ghost', include: true }], scaffold()),
707
+ 'include:true must require a live question',
708
+ )
709
+ // Exclusion stays available with no such question: an imported tab naming a question it never
710
+ // had must be repairable, and refusing would leave the document permanently malformed.
711
+ assert.doesNotThrow(() =>
712
+ apply([{ type: 'tab.setQuestion', tabId: 't-1', questionId: 'ghost', include: false }], scaffold()),
713
+ )
714
+ throwsConflict(
715
+ () => apply([{ type: 'tab.setQuestion', tabId: 'ghost', questionId: 'q-top', include: true }], scaffold()),
716
+ 'an unknown tab is always a conflict',
717
+ )
718
+ })
719
+
720
+ it('two clients adding different members converge in either order', () => {
721
+ const base = scaffold()
722
+ const a: TemplateOp = { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true }
723
+ const b: TemplateOp = { type: 'tab.setQuestion', tabId: 't-1', questionId: 'g-1', include: true }
724
+
725
+ // The lost update a whole-array write would cause: both members must survive both orders.
726
+ assert.deepEqual(tab(apply([a, b], base))?.questionIds, ['q-top', 'g-1'])
727
+ assert.deepEqual(tab(apply([b, a], base))?.questionIds, ['g-1', 'q-top'])
728
+ })
729
+
730
+ it('removing membership atomically drops that question count and placement', () => {
731
+ const base = apply(
732
+ [
733
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'g-1', include: true },
734
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true },
735
+ { type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'g-1', include: true },
736
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'g-1', placement: { row: 0, cell: 0 } },
737
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'q-top', placement: { row: 1, cell: 0 } },
738
+ { type: 'tab.updateField', tabId: 't-1', field: 'count_question_rows_legacy', value: 'kept' },
739
+ ],
740
+ scaffold(),
741
+ )
742
+
743
+ const doc = apply([{ type: 'tab.setQuestion', tabId: 't-1', questionId: 'g-1', include: false }], base)
744
+ assert.deepEqual(tab(doc)?.questionIds, ['q-top'])
745
+ // A count or placement for a non-member is a reference to something the tab no longer shows.
746
+ assert.equal('rowCountQuestionIds' in (tab(doc) ?? {}), false)
747
+ assert.deepEqual(tab(doc)?.layout, { placementsByQuestionId: { 'q-top': { row: 1, cell: 0 } } })
748
+ // Unrelated members, the surviving placement, the label and an open legacy field are untouched.
749
+ assert.equal(tab(doc)?.label, 'Første')
750
+ assert.equal(tab(doc)?.['count_question_rows_legacy'], 'kept')
751
+ })
752
+
753
+ it('one question in two tabs leaves the other tab alone', () => {
754
+ const base = apply(
755
+ [
756
+ { type: 'tab.create', tabId: 't-2', label: 'Andre' },
757
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true },
758
+ { type: 'tab.setQuestion', tabId: 't-2', questionId: 'q-top', include: true },
759
+ ],
760
+ scaffold(),
761
+ )
762
+ // There is deliberately no single-tab ownership invariant, so removing from one is local.
763
+ const doc = apply([{ type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: false }], base)
764
+ assert.equal('questionIds' in (tab(doc, 't-1') ?? {}), false)
765
+ assert.deepEqual(tab(doc, 't-2')?.questionIds, ['q-top'])
766
+ })
767
+ })
768
+
769
+ describe('the counted-grid subset', () => {
770
+ const tab = (doc: QnrTemplateDocument, id = 't-1') => doc.tabsById?.[id]
771
+ const withMembers = () =>
772
+ apply(
773
+ [
774
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'g-1', include: true },
775
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true },
776
+ ],
777
+ scaffold(),
778
+ )
779
+
780
+ it('counts a member grid and leaves membership and layout untouched', () => {
781
+ const doc = apply(
782
+ [
783
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'g-1', placement: { row: 0, cell: 0 } },
784
+ { type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'g-1', include: true },
785
+ ],
786
+ withMembers(),
787
+ )
788
+ assert.deepEqual(tab(doc)?.rowCountQuestionIds, ['g-1'])
789
+ assert.deepEqual(tab(doc)?.questionIds, ['g-1', 'q-top'])
790
+ assert.deepEqual(tab(doc)?.layout, { placementsByQuestionId: { 'g-1': { row: 0, cell: 0 } } })
791
+ })
792
+
793
+ it('refuses a scalar question, a non-member grid, a missing question and a missing tab', () => {
794
+ // Only a grid has rows to count.
795
+ throwsConflict(
796
+ () => apply([{ type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'q-top', include: true }], withMembers()),
797
+ 'a scalar question has no rows',
798
+ )
799
+ // A grid that exists but is not shown by this tab contributes nothing to its count.
800
+ const nonMember = apply([{ type: 'question.create', questionId: 'g-2', questionType: 'QuestionGrid' }], withMembers())
801
+ throwsConflict(
802
+ () => apply([{ type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'g-2', include: true }], nonMember),
803
+ 'a non-member grid must be refused',
804
+ )
805
+ throwsConflict(
806
+ () => apply([{ type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'ghost', include: true }], withMembers()),
807
+ 'a missing question must be refused',
808
+ )
809
+ throwsConflict(
810
+ () => apply([{ type: 'tab.setRowCountQuestion', tabId: 'ghost', questionId: 'g-1', include: true }], withMembers()),
811
+ 'a missing tab must be refused',
812
+ )
813
+ })
814
+
815
+ it('refuses a DANGLING member id, so the existence check is what does the work', () => {
816
+ // The `'ghost'` case above is *also* a nonmember, so the membership check refuses it and the
817
+ // existence check is never exercised — the same "passes for the wrong reason" shape as the
818
+ // A11/A12/A39 gaps. Here the id IS a member, so membership passes and only the existence guard
819
+ // can refuse.
820
+ //
821
+ // The document is built by hand on purpose: no legal sequence of ops can put a dangling id in
822
+ // `questionIds` (`tab.setQuestion include:true` requires a live question). This is the imported
823
+ // malformed state the freeze says must stay repairable, so it is reachable in production.
824
+ const imported: QnrTemplateDocument = {
825
+ ...withMembers(),
826
+ tabsById: { 't-1': { label: 'Første', questionIds: ['ghost-grid'] } },
827
+ }
828
+
829
+ throwsConflict(
830
+ () => apply([{ type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'ghost-grid', include: true }], imported),
831
+ 'a dangling member id must still be refused as a missing question',
832
+ )
833
+ // And the repair path stays open on that same document, which is why the state is worth having.
834
+ assert.doesNotThrow(() =>
835
+ apply([{ type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'ghost-grid', include: false }], imported),
836
+ )
837
+ })
838
+
839
+ it('repairs every one of those malformed cases by excluding', () => {
840
+ // Exclusion requires neither a live question nor valid membership: an imported document whose
841
+ // count names a scalar, a non-member or a deleted question must be fixable in place.
842
+ const imported = apply(
843
+ [{ type: 'tab.updateField', tabId: 't-1', field: 'label', value: 'Fane' }],
844
+ withMembers(),
845
+ )
846
+ for (const questionId of ['q-top', 'ghost', 'g-1']) {
847
+ assert.doesNotThrow(
848
+ () => apply([{ type: 'tab.setRowCountQuestion', tabId: 't-1', questionId, include: false }], imported),
849
+ `excluding "${questionId}" must stay available`,
850
+ )
851
+ }
852
+ })
853
+
854
+ it('does not add or remove membership', () => {
855
+ const doc = apply(
856
+ [
857
+ { type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'g-1', include: true },
858
+ { type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'g-1', include: false },
859
+ ],
860
+ withMembers(),
861
+ )
862
+ assert.deepEqual(tab(doc)?.questionIds, ['g-1', 'q-top'])
863
+ assert.equal('rowCountQuestionIds' in (tab(doc) ?? {}), false)
864
+ })
865
+ })
866
+
867
+ describe('tab.updateField reserves all three tab-owned collections', () => {
868
+ it('refuses the exact path, an ancestor and a descendant for each', () => {
869
+ for (const field of [
870
+ 'questionIds',
871
+ 'questionIds.0',
872
+ 'rowCountQuestionIds',
873
+ 'rowCountQuestionIds.1',
874
+ 'layout',
875
+ 'layout.placementsByQuestionId',
876
+ 'layout.placementsByQuestionId.q-top',
877
+ ]) {
878
+ assert.notEqual(tabFieldPathRefusal(field), undefined, `"${field}" must be reserved`)
879
+ }
880
+ })
881
+
882
+ it('still accepts the label and an unrelated legacy field', () => {
883
+ // Narrowing the open bag would make an imported tab unwritable — DEC-006's whole point.
884
+ assert.equal(tabFieldPathRefusal('label'), undefined)
885
+ assert.equal(tabFieldPathRefusal('count_question_rows'), undefined)
886
+ const doc = apply(
887
+ [
888
+ { type: 'tab.updateField', tabId: 't-1', field: 'label', value: 'Ny' },
889
+ { type: 'tab.updateField', tabId: 't-1', field: 'dependent_question_ids_legacy', value: 'x' },
890
+ ],
891
+ scaffold(),
892
+ )
893
+ assert.equal(doc.tabsById?.['t-1']?.label, 'Ny')
894
+ assert.equal(doc.tabsById?.['t-1']?.['dependent_question_ids_legacy'], 'x')
895
+ })
896
+
897
+ it('refuses a whole-snapshot write through every reserved spelling at the reducer', () => {
898
+ for (const field of ['questionIds', 'rowCountQuestionIds', 'layout']) {
899
+ throwsConflict(
900
+ () => apply([{ type: 'tab.updateField', tabId: 't-1', field, value: 'anything' }], scaffold()),
901
+ `"${field}" must be refused by the reducer, not only by the helper`,
902
+ )
903
+ }
904
+ })
905
+ })
906
+
907
+ describe('question deletion scrubs all three tab locations', () => {
908
+ it('removes the id from membership, count and layout across multiple tabs', () => {
909
+ const base = apply(
910
+ [
911
+ { type: 'tab.create', tabId: 't-2', label: 'Andre' },
912
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'g-1', include: true },
913
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'q-top', include: true },
914
+ { type: 'tab.setRowCountQuestion', tabId: 't-1', questionId: 'g-1', include: true },
915
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'g-1', placement: { row: 0, cell: 0 } },
916
+ { type: 'tab.setQuestion', tabId: 't-2', questionId: 'g-1', include: true },
917
+ { type: 'tab.setRowCountQuestion', tabId: 't-2', questionId: 'g-1', include: true },
918
+ { type: 'tab.setLayout', tabId: 't-2', questionId: 'g-1', placement: { row: 2, cell: 1 } },
919
+ ],
920
+ scaffold(),
921
+ )
922
+
923
+ const doc = apply([{ type: 'question.delete', questionId: 'g-1' }], base)
924
+ // Left behind, each of the three would name a question the document no longer has —
925
+ // unreachable state that still changes `document_hash`.
926
+ assert.deepEqual(doc.tabsById?.['t-1']?.questionIds, ['q-top'])
927
+ assert.equal('rowCountQuestionIds' in (doc.tabsById?.['t-1'] ?? {}), false)
928
+ assert.equal('layout' in (doc.tabsById?.['t-1'] ?? {}), false)
929
+ // The second tab is scrubbed too, and survives with nothing but its label.
930
+ assert.deepEqual(doc.tabsById?.['t-2'], { label: 'Andre' })
931
+ assert.deepEqual(findDocLawViolations(doc), [])
932
+ })
933
+
934
+ it('scrubs a recursively deleted grid column from every tab location', () => {
935
+ const base = apply(
936
+ [
937
+ { type: 'tab.setQuestion', tabId: 't-1', questionId: 'c-1', include: true },
938
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'c-1', placement: { row: 0, cell: 3 } },
939
+ ],
940
+ scaffold(),
941
+ )
942
+ // `c-1` is deleted only as a consequence of its owning grid going, so the cascade has to run
943
+ // for every id in the ownership subtree rather than just the one named in the op.
944
+ const doc = apply([{ type: 'question.delete', questionId: 'g-1' }], base)
945
+ assert.deepEqual(doc.tabsById?.['t-1'], { label: 'Første' })
946
+ })
947
+ })
948
+
949
+ describe('tab.setLayout is not narrowed by the membership repair', () => {
950
+ it('still places a question that is not a member, so v0.31 logs replay', () => {
951
+ // A v0.31 log has no membership ops in it at all. Requiring membership here would make every
952
+ // stored layout-only log unreplayable — the exact break DEC-006 forbids.
953
+ const doc = apply(
954
+ [{ type: 'tab.setLayout', tabId: 't-1', questionId: 'q-top', placement: { row: 1, cell: 2 } }],
955
+ scaffold(),
956
+ )
957
+ assert.deepEqual(doc.tabsById?.['t-1']?.layout, {
958
+ placementsByQuestionId: { 'q-top': { row: 1, cell: 2 } },
959
+ })
960
+ assert.equal('questionIds' in (doc.tabsById?.['t-1'] ?? {}), false)
961
+ })
962
+
963
+ it('produces a byte-identical tab to the one a v0.31 reducer produced', () => {
964
+ // The v0.31 result for this log, recorded as literal bytes rather than recomputed: a canonical
965
+ // form that moved would otherwise agree with itself and prove nothing.
966
+ const doc = apply(
967
+ [
968
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'q-top', placement: { row: 0, cell: 0 } },
969
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'g-1', placement: { row: 1, cell: 1, keepCellSize: true } },
970
+ { type: 'tab.setLayout', tabId: 't-1', questionId: 'q-top', placement: null },
971
+ ],
972
+ scaffold(),
973
+ )
974
+ assert.equal(
975
+ canonicalJson(doc.tabsById?.['t-1']),
976
+ '{"label":"Første","layout":{"placementsByQuestionId":{"g-1":{"cell":1,"keepCellSize":true,"row":1}}}}',
977
+ )
978
+ })
979
+ })
980
+
981
+ // ───────────────────────── AC-9: Expression formulas and Chart legends ─────────────────────────
982
+
983
+ /**
984
+ * The AC-9 closed producers over two still-open released bags.
985
+ *
986
+ * `QnrQuestion.chart` and `QnrAlternative` stay open, so `question.updateField` and
987
+ * `alternative.updateField` keep writing every one of these paths byte-for-byte — imported `pie`
988
+ * content, truncated legacy tokens and malformed legend bags all remain readable and replayable. What
989
+ * the four new operations add is a path that can only produce canonical state: publication, not replay,
990
+ * is where the old shapes become findings.
991
+ *
992
+ * @see the AC-9 shared repair matrix — reducer laws and append-only split
993
+ */
994
+
995
+ /** A radar Chart, an ExpressionQuestion, and two flagged targets legal to cite from either. */
996
+ const ac9 = (): QnrTemplateDocument =>
997
+ apply([
998
+ { type: 'question.create', questionId: 'ch-1', questionType: 'Chart' },
999
+ { type: 'question.updateField', questionId: 'ch-1', field: 'chart.type', value: 'radar' },
1000
+ { type: 'alternative.create', questionId: 'ch-1', alternativeId: 'ca-1', label: 'Akse' },
1001
+ { type: 'question.create', questionId: 'ex-1', questionType: 'ExpressionQuestion' },
1002
+ { type: 'alternative.create', questionId: 'ex-1', alternativeId: 'ea-1', label: 'Formel' },
1003
+ { type: 'question.create', questionId: 'tg-1', questionType: 'RadioButtons' },
1004
+ { type: 'question.updateField', questionId: 'tg-1', field: 'flags.is_expression', value: true },
1005
+ { type: 'question.create', questionId: 'tg-2', questionType: 'LinearScale' },
1006
+ { type: 'question.updateField', questionId: 'tg-2', field: 'flags.is_expression', value: true },
1007
+ // Deliberately unflagged, and a Chart, so both refusal reasons are reachable.
1008
+ { type: 'question.create', questionId: 'tg-off', questionType: 'RadioButtons' },
1009
+ { type: 'question.create', questionId: 'ch-2', questionType: 'Chart' },
1010
+ ])
1011
+
1012
+ const alternative = (doc: QnrTemplateDocument, id: string) => doc.alternativesById?.[id]
1013
+ const chart = (doc: QnrTemplateDocument, id = 'ch-1') =>
1014
+ doc.questionsById?.[id]?.['chart'] as Record<string, unknown> | undefined
1015
+
1016
+ describe('the canonical expression tokens', () => {
1017
+ it('is injective where legacy was not', () => {
1018
+ // Legacy tokenized the LAST EIGHT characters of an id, so these two ids collided and a formula
1019
+ // silently scored the wrong question. Guaranteed rather than unlucky after a bundle pick, where
1020
+ // every fresh id comes from one map.
1021
+ const a = 'q-1111111111-deadbeef'
1022
+ const b = 'q-2222222222-deadbeef'
1023
+ assert.equal(a.slice(-8), b.slice(-8))
1024
+ assert.notEqual(makeExpressionTargetToken(a), makeExpressionTargetToken(b))
1025
+ })
1026
+
1027
+ it('encodes the complete id as lowercase UTF-8 hex and round-trips non-ASCII', () => {
1028
+ assert.equal(makeExpressionTargetToken('q1'), '<target_7131>')
1029
+ assert.equal(makeExpressionAlternativeToken('a1'), '<exp_6131>')
1030
+ // Two bytes per non-ASCII character, so a Unicode id is not lossy or ambiguous.
1031
+ assert.equal(makeExpressionTargetToken('æ'), '<target_c3a6>')
1032
+ assert.equal(makeExpressionTargetToken('æ'), makeExpressionTargetToken('æ'))
1033
+ })
1034
+
1035
+ it('keeps the two token spaces disjoint', () => {
1036
+ assert.equal(isExpressionTargetToken(makeExpressionTargetToken('x')), true)
1037
+ assert.equal(isExpressionAlternativeToken(makeExpressionAlternativeToken('x')), true)
1038
+ // A target token is not an alternative token even for the same id.
1039
+ assert.equal(isExpressionAlternativeToken(makeExpressionTargetToken('x')), false)
1040
+ assert.equal(isExpressionTargetToken(makeExpressionAlternativeToken('x')), false)
1041
+ })
1042
+
1043
+ it('refuses every non-canonical spelling, including the legacy one', () => {
1044
+ for (const value of [
1045
+ '<target_>', // empty body
1046
+ '<target_713>', // odd length: half a byte
1047
+ '<target_71G1>', // non-hex
1048
+ '<target_71A1>', // uppercase
1049
+ '<target_7131', // unterminated
1050
+ 'target_7131>', // no opening delimiter
1051
+ '<target_7131>x', // suffix claimant
1052
+ 'x<target_7131>', // prefix claimant
1053
+ '<target_deadbeef>_old',
1054
+ '<exp_7131>',
1055
+ '',
1056
+ ]) {
1057
+ assert.equal(isExpressionTargetToken(value), false, value)
1058
+ }
1059
+ })
1060
+ })
1061
+
1062
+ describe('alternative.setExpressionFormula', () => {
1063
+ it('writes the formula and its ordered targets as one value', () => {
1064
+ const doc = apply(
1065
+ [
1066
+ {
1067
+ type: 'alternative.setExpressionFormula',
1068
+ questionId: 'ex-1',
1069
+ alternativeId: 'ea-1',
1070
+ value: `${makeExpressionTargetToken('tg-2')} + ${makeExpressionTargetToken('tg-1')}`,
1071
+ expressionTargets: ['tg-2', 'tg-1'],
1072
+ },
1073
+ ],
1074
+ ac9(),
1075
+ )
1076
+ assert.equal(alternative(doc, 'ea-1')?.['value'], '<target_74672d32> + <target_74672d31>')
1077
+ // Authored order is preserved, not sorted: it is the order the author listed.
1078
+ assert.deepEqual(alternative(doc, 'ea-1')?.['expressionTargets'], ['tg-2', 'tg-1'])
1079
+ })
1080
+
1081
+ it('omits an empty target list rather than storing []', () => {
1082
+ const doc = apply(
1083
+ [{ type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: '1 + 2', expressionTargets: [] }],
1084
+ ac9(),
1085
+ )
1086
+ assert.equal(alternative(doc, 'ea-1')?.['value'], '1 + 2')
1087
+ assert.equal('expressionTargets' in (alternative(doc, 'ea-1') ?? {}), false)
1088
+ assert.deepEqual(findDocLawViolations(doc), [])
1089
+ })
1090
+
1091
+ it('is draft-permissive: text and targets need not agree', () => {
1092
+ // A half-typed formula must save. Publication owns the mismatch finding; erasing or repairing it
1093
+ // here would delete what the author is in the middle of writing.
1094
+ assert.doesNotThrow(() =>
1095
+ apply(
1096
+ [{ type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: `${makeExpressionTargetToken('tg-1')} +`, expressionTargets: [] }],
1097
+ ac9(),
1098
+ ),
1099
+ )
1100
+ assert.doesNotThrow(() =>
1101
+ apply(
1102
+ [{ type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: '0', expressionTargets: ['tg-1'] }],
1103
+ ac9(),
1104
+ ),
1105
+ )
1106
+ })
1107
+
1108
+ it('refuses a duplicate, missing, wrong-type, Chart or flag-off target', () => {
1109
+ const bad: Array<[string, string[]]> = [
1110
+ ['a duplicate target', ['tg-1', 'tg-1']],
1111
+ ['a missing target', ['ghost']],
1112
+ ['an unflagged target', ['tg-off']],
1113
+ ['a Chart target', ['ch-2']],
1114
+ ['a grid target', ['ex-1']],
1115
+ ]
1116
+ for (const [hint, expressionTargets] of bad) {
1117
+ throwsConflict(
1118
+ () => apply([{ type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: '0', expressionTargets }], ac9()),
1119
+ hint,
1120
+ )
1121
+ }
1122
+ })
1123
+
1124
+ it('refuses a wrong owner type and an alternative of another question', () => {
1125
+ throwsConflict(
1126
+ () => apply([{ type: 'alternative.setExpressionFormula', questionId: 'ch-1', alternativeId: 'ca-1', value: '0', expressionTargets: [] }], ac9()),
1127
+ 'only an ExpressionQuestion has a formula',
1128
+ )
1129
+ throwsConflict(
1130
+ () => apply([{ type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ca-1', value: '0', expressionTargets: [] }], ac9()),
1131
+ 'the alternative must be owned by that exact question',
1132
+ )
1133
+ })
1134
+
1135
+ it('is last-writer-wins on the whole value, and different alternatives converge', () => {
1136
+ const two = apply(
1137
+ [
1138
+ { type: 'alternative.create', questionId: 'ex-1', alternativeId: 'ea-2', label: 'Formel 2' },
1139
+ { type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: 'A', expressionTargets: ['tg-1'] },
1140
+ { type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-2', value: 'B', expressionTargets: ['tg-2'] },
1141
+ // The second write on ea-1 replaces the whole value: no stale target survives under it.
1142
+ { type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: 'C', expressionTargets: [] },
1143
+ ],
1144
+ ac9(),
1145
+ )
1146
+ assert.equal(alternative(two, 'ea-1')?.['value'], 'C')
1147
+ assert.equal('expressionTargets' in (alternative(two, 'ea-1') ?? {}), false)
1148
+ assert.equal(alternative(two, 'ea-2')?.['value'], 'B')
1149
+ assert.deepEqual(alternative(two, 'ea-2')?.['expressionTargets'], ['tg-2'])
1150
+ })
1151
+ })
1152
+
1153
+ describe('chartLegend.create', () => {
1154
+ it('inserts the record and the order entry atomically, appending by default', () => {
1155
+ const doc = apply(
1156
+ [
1157
+ { type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' },
1158
+ { type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-2', label: 'Psykisk' },
1159
+ ],
1160
+ ac9(),
1161
+ )
1162
+ assert.deepEqual(chart(doc)?.['legendsById'], {
1163
+ 'lg-1': { id: 'lg-1', label: 'Fysisk' },
1164
+ 'lg-2': { id: 'lg-2', label: 'Psykisk' },
1165
+ })
1166
+ // A record with no order entry is unreachable state that still moves the hash; the reverse dangles.
1167
+ assert.deepEqual(chart(doc)?.['legendsOrder'], ['lg-1', 'lg-2'])
1168
+ })
1169
+
1170
+ it('clamps atIndex, which is what makes a bundle pick lossless', () => {
1171
+ const base = apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'A' }], ac9())
1172
+ const first = apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-2', label: 'B', atIndex: 0 }], base)
1173
+ assert.deepEqual(chart(first)?.['legendsOrder'], ['lg-2', 'lg-1'])
1174
+ const clamped = apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-3', label: 'C', atIndex: 99 }], first)
1175
+ assert.deepEqual(chart(clamped)?.['legendsOrder'], ['lg-2', 'lg-1', 'lg-3'])
1176
+ })
1177
+
1178
+ it('refuses an empty id or label, a duplicate id, and a duplicate label', () => {
1179
+ const base = apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' }], ac9())
1180
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: '', label: 'X' }], base), 'empty id')
1181
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-9', label: '' }], base), 'empty label')
1182
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Annet' }], base), 'duplicate id')
1183
+ // Legacy compares labels by exact equality, and two same-labelled legends are
1184
+ // indistinguishable in the radar the author is looking at.
1185
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-2', label: 'Fysisk' }], base), 'duplicate label')
1186
+ })
1187
+
1188
+ it('refuses a non-Chart owner and a non-radar Chart', () => {
1189
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ex-1', legendId: 'lg-1', label: 'A' }], ac9()), 'not a Chart')
1190
+ // `pie` is preserved on read but never authored: legacy's designer exposes no working Pie editor.
1191
+ const pie = apply([{ type: 'question.updateField', questionId: 'ch-2', field: 'chart.type', value: 'pie' }], ac9())
1192
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ch-2', legendId: 'lg-1', label: 'A' }], pie), 'pie is not authorable')
1193
+ // An uppercase spelling is not a second authored vocabulary either.
1194
+ const upper = apply([{ type: 'question.updateField', questionId: 'ch-2', field: 'chart.type', value: 'RADAR' }], ac9())
1195
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ch-2', legendId: 'lg-1', label: 'A' }], upper), 'RADAR is not radar')
1196
+ })
1197
+ })
1198
+
1199
+ describe('chartLegend.delete', () => {
1200
+ const withLegends = () =>
1201
+ apply(
1202
+ [
1203
+ { type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' },
1204
+ { type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-2', label: 'Psykisk' },
1205
+ { type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-1', questionIdMap: 'tg-1' } },
1206
+ ],
1207
+ ac9(),
1208
+ )
1209
+
1210
+ it('removes the record and every order occurrence, and clears its owned assignments', () => {
1211
+ const doc = apply([{ type: 'chartLegend.delete', questionId: 'ch-1', legendId: 'lg-1' }], withLegends())
1212
+ assert.deepEqual(chart(doc)?.['legendsById'], { 'lg-2': { id: 'lg-2', label: 'Psykisk' } })
1213
+ assert.deepEqual(chart(doc)?.['legendsOrder'], ['lg-2'])
1214
+ // The legacy effect: a legend that disappears stops appearing on alternatives.
1215
+ assert.equal('chartLegend' in (alternative(doc, 'ca-1') ?? {}), false)
1216
+ assert.deepEqual(findDocLawViolations(doc), [])
1217
+ })
1218
+
1219
+ it('prunes the emptied containers without deleting the Chart', () => {
1220
+ const doc = apply(
1221
+ [
1222
+ { type: 'chartLegend.delete', questionId: 'ch-1', legendId: 'lg-1' },
1223
+ { type: 'chartLegend.delete', questionId: 'ch-1', legendId: 'lg-2' },
1224
+ ],
1225
+ withLegends(),
1226
+ )
1227
+ assert.equal('legendsById' in (chart(doc) ?? {}), false)
1228
+ assert.equal('legendsOrder' in (chart(doc) ?? {}), false)
1229
+ // The Chart itself, and its authored type, survive an emptied legend collection.
1230
+ assert.deepEqual(chart(doc), { type: 'radar' })
1231
+ assert.equal(doc.questionsById?.['ch-1']?.type, 'Chart')
1232
+ })
1233
+
1234
+ it('leaves an identically-named legend on another Chart alone', () => {
1235
+ // Imported ids do collide across questions, so the cascade is scoped by ownership rather than
1236
+ // by id — clearing another Chart's assignment would be data loss.
1237
+ const base = apply(
1238
+ [
1239
+ { type: 'question.updateField', questionId: 'ch-2', field: 'chart.type', value: 'radar' },
1240
+ { type: 'chartLegend.create', questionId: 'ch-2', legendId: 'lg-1', label: 'Fysisk' },
1241
+ { type: 'alternative.create', questionId: 'ch-2', alternativeId: 'ca-2', label: 'Akse' },
1242
+ { type: 'alternative.setChartLegend', questionId: 'ch-2', alternativeId: 'ca-2', chartLegend: { id: 'lg-1', questionIdMap: 'tg-2' } },
1243
+ ],
1244
+ withLegends(),
1245
+ )
1246
+ const before = canonicalJson({ chart: chart(base, 'ch-2'), assignment: alternative(base, 'ca-2') })
1247
+
1248
+ const doc = apply([{ type: 'chartLegend.delete', questionId: 'ch-1', legendId: 'lg-1' }], base)
1249
+ assert.equal(canonicalJson({ chart: chart(doc, 'ch-2'), assignment: alternative(doc, 'ca-2') }), before)
1250
+ assert.equal('chartLegend' in (alternative(doc, 'ca-1') ?? {}), false)
1251
+ })
1252
+
1253
+ it('repairs imported non-radar state and refuses an unknown legend', () => {
1254
+ // Deletion deliberately does NOT require radar: a `pie` document carrying legends must be fixable.
1255
+ const pie = apply(
1256
+ [
1257
+ { type: 'question.updateField', questionId: 'ch-1', field: 'chart.type', value: 'pie' },
1258
+ ],
1259
+ withLegends(),
1260
+ )
1261
+ assert.doesNotThrow(() => apply([{ type: 'chartLegend.delete', questionId: 'ch-1', legendId: 'lg-1' }], pie))
1262
+ throwsConflict(() => apply([{ type: 'chartLegend.delete', questionId: 'ch-1', legendId: 'ghost' }], withLegends()), 'unknown legend')
1263
+ throwsConflict(() => apply([{ type: 'chartLegend.delete', questionId: 'ex-1', legendId: 'lg-1' }], withLegends()), 'not a Chart')
1264
+ })
1265
+ })
1266
+
1267
+ describe('alternative.setChartLegend', () => {
1268
+ const withLegend = () =>
1269
+ apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' }], ac9())
1270
+
1271
+ it('derives the label from the owning legend and writes the whole value at once', () => {
1272
+ const doc = apply(
1273
+ [{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-1', questionIdMap: 'tg-1' } }],
1274
+ withLegend(),
1275
+ )
1276
+ // The label is copied here, never taken from the client: one legend id must not carry two labels.
1277
+ assert.deepEqual(alternative(doc, 'ca-1')?.['chartLegend'], {
1278
+ id: 'lg-1',
1279
+ questionIdMap: 'tg-1',
1280
+ label: 'Fysisk',
1281
+ })
1282
+ })
1283
+
1284
+ it('replaces the whole value and clears it entirely', () => {
1285
+ const base = apply(
1286
+ [
1287
+ { type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-2', label: 'Psykisk' },
1288
+ { type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-1', questionIdMap: 'tg-1' } },
1289
+ ],
1290
+ withLegend(),
1291
+ )
1292
+ const replaced = apply(
1293
+ [{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-2', questionIdMap: 'tg-2' } }],
1294
+ base,
1295
+ )
1296
+ // Three separate field writes could interleave into an id/target/label hybrid no author selected.
1297
+ assert.deepEqual(alternative(replaced, 'ca-1')?.['chartLegend'], {
1298
+ id: 'lg-2',
1299
+ questionIdMap: 'tg-2',
1300
+ label: 'Psykisk',
1301
+ })
1302
+ const cleared = apply([{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: null }], replaced)
1303
+ assert.equal('chartLegend' in (alternative(cleared, 'ca-1') ?? {}), false)
1304
+ assert.deepEqual(findDocLawViolations(cleared), [])
1305
+ })
1306
+
1307
+ it('refuses a missing legend, a missing target, a Chart target and an unflagged target', () => {
1308
+ for (const [hint, chartLegend] of [
1309
+ ['missing legend', { id: 'ghost', questionIdMap: 'tg-1' }],
1310
+ ['missing target', { id: 'lg-1', questionIdMap: 'ghost' }],
1311
+ ['Chart target', { id: 'lg-1', questionIdMap: 'ch-2' }],
1312
+ ['unflagged target', { id: 'lg-1', questionIdMap: 'tg-off' }],
1313
+ ] as const) {
1314
+ throwsConflict(
1315
+ () => apply([{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend }], withLegend()),
1316
+ hint,
1317
+ )
1318
+ }
1319
+ })
1320
+
1321
+ it('refuses a wrong owner and a non-radar Chart, but still clears them', () => {
1322
+ throwsConflict(
1323
+ () => apply([{ type: 'alternative.setChartLegend', questionId: 'ex-1', alternativeId: 'ea-1', chartLegend: { id: 'lg-1', questionIdMap: 'tg-1' } }], withLegend()),
1324
+ 'only a Chart carries an assignment',
1325
+ )
1326
+ throwsConflict(
1327
+ () => apply([{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ea-1', chartLegend: { id: 'lg-1', questionIdMap: 'tg-1' } }], withLegend()),
1328
+ 'the alternative must belong to that Chart',
1329
+ )
1330
+ // Clearing must survive a non-radar owner so an imported dangling assignment is repairable.
1331
+ const pie = apply([{ type: 'question.updateField', questionId: 'ch-1', field: 'chart.type', value: 'pie' }], withLegend())
1332
+ assert.doesNotThrow(() =>
1333
+ apply([{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: null }], pie),
1334
+ )
1335
+ throwsConflict(
1336
+ () => apply([{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-1', questionIdMap: 'tg-1' } }], pie),
1337
+ 'a non-null assignment requires radar',
1338
+ )
1339
+ })
1340
+
1341
+ it('refuses a client-supplied label at the schema', () => {
1342
+ // The compile-time half is in `typeContracts.ts`; this is the wire half.
1343
+ const validated = templateOpSchema({
1344
+ type: 'alternative.setChartLegend',
1345
+ questionId: 'ch-1',
1346
+ alternativeId: 'ca-1',
1347
+ chartLegend: { id: 'lg-1', questionIdMap: 'tg-1', label: 'Noe annet' },
1348
+ })
1349
+ assert.ok(validated instanceof type.errors, 'a client label must not validate')
1350
+ })
1351
+ })
1352
+
1353
+ describe('AC-9 deletion cascades', () => {
1354
+ const bound = () =>
1355
+ apply(
1356
+ [
1357
+ { type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' },
1358
+ { type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-1', questionIdMap: 'tg-1' } },
1359
+ {
1360
+ type: 'alternative.setExpressionFormula',
1361
+ questionId: 'ex-1',
1362
+ alternativeId: 'ea-1',
1363
+ value: `${makeExpressionTargetToken('tg-1')} + ${makeExpressionTargetToken('tg-2')} + ${makeExpressionTargetToken('tg-1')}`,
1364
+ expressionTargets: ['tg-1', 'tg-2'],
1365
+ },
1366
+ ],
1367
+ ac9(),
1368
+ )
1369
+
1370
+ it('deleting a target scrubs the list, every token occurrence, and the Chart assignment', () => {
1371
+ const doc = apply([{ type: 'question.delete', questionId: 'tg-1' }], bound())
1372
+ assert.deepEqual(alternative(doc, 'ea-1')?.['expressionTargets'], ['tg-2'])
1373
+ // Replaced with `0` so the formula still reads as arithmetic; both occurrences go.
1374
+ assert.equal(alternative(doc, 'ea-1')?.['value'], '0 + <target_74672d32> + 0')
1375
+ assert.equal('chartLegend' in (alternative(doc, 'ca-1') ?? {}), false)
1376
+ assert.deepEqual(findDocLawViolations(doc), [])
1377
+ })
1378
+
1379
+ it('never substring-matches, so legacy text and other tokens are untouched', () => {
1380
+ // A legacy truncated token and arbitrary author prose are not this reducer's to rewrite.
1381
+ const legacy = apply(
1382
+ [{ type: 'alternative.updateField', questionId: 'ex-1', alternativeId: 'ea-1', field: 'value', value: '<target_74672d31 + tg-1 + <target_74672d3> + tg-1-total' }],
1383
+ bound(),
1384
+ )
1385
+ const doc = apply([{ type: 'question.delete', questionId: 'tg-1' }], legacy)
1386
+ assert.equal(alternative(doc, 'ea-1')?.['value'], '<target_74672d31 + tg-1 + <target_74672d3> + tg-1-total')
1387
+ })
1388
+
1389
+ it('scrubs a recursively deleted grid column from a formula and an assignment', () => {
1390
+ const base = apply(
1391
+ [
1392
+ { type: 'question.create', questionId: 'g-x', questionType: 'QuestionGrid' },
1393
+ { type: 'gridColumn.create', questionId: 'g-x', columnQuestionId: 'gc-1', questionType: 'RadioButtons' },
1394
+ { type: 'question.updateField', questionId: 'gc-1', field: 'flags.is_expression', value: true },
1395
+ { type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: makeExpressionTargetToken('gc-1'), expressionTargets: ['gc-1'] },
1396
+ { type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' },
1397
+ { type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-1', questionIdMap: 'gc-1' } },
1398
+ ],
1399
+ ac9(),
1400
+ )
1401
+ // The column dies only as a consequence of its grid going, so the cascade must run for the whole
1402
+ // ownership subtree rather than the one id the operation names.
1403
+ const doc = apply([{ type: 'question.delete', questionId: 'g-x' }], base)
1404
+ assert.equal('expressionTargets' in (alternative(doc, 'ea-1') ?? {}), false)
1405
+ assert.equal(alternative(doc, 'ea-1')?.['value'], '0')
1406
+ assert.equal('chartLegend' in (alternative(doc, 'ca-1') ?? {}), false)
1407
+ })
1408
+
1409
+ it('deleting an alternative scrubs only its own canonical token from its own question', () => {
1410
+ const base = apply(
1411
+ [
1412
+ { type: 'question.updateField', questionId: 'ex-1', field: 'expression.base', value: `${makeExpressionAlternativeToken('ea-1')} + ${makeExpressionAlternativeToken('ea-2')}` },
1413
+ { type: 'alternative.create', questionId: 'ex-1', alternativeId: 'ea-2', label: 'To' },
1414
+ // Another question's formula mentioning the same alternative is not ours to rewrite.
1415
+ { type: 'question.create', questionId: 'ex-2', questionType: 'ExpressionQuestion' },
1416
+ { type: 'question.updateField', questionId: 'ex-2', field: 'expression.base', value: makeExpressionAlternativeToken('ea-1') },
1417
+ ],
1418
+ ac9(),
1419
+ )
1420
+ const doc = apply([{ type: 'alternative.delete', questionId: 'ex-1', alternativeId: 'ea-1' }], base)
1421
+ assert.equal((doc.questionsById?.['ex-1']?.['expression'] as Record<string, unknown>)['base'], ' + <exp_65612d32>')
1422
+ assert.equal((doc.questionsById?.['ex-2']?.['expression'] as Record<string, unknown>)['base'], '<exp_65612d31>')
1423
+ })
1424
+
1425
+ it('prunes the emptied expression bag rather than leaving an empty string', () => {
1426
+ const base = apply(
1427
+ [{ type: 'question.updateField', questionId: 'ex-1', field: 'expression.base', value: makeExpressionAlternativeToken('ea-1') }],
1428
+ ac9(),
1429
+ )
1430
+ const doc = apply([{ type: 'alternative.delete', questionId: 'ex-1', alternativeId: 'ea-1' }], base)
1431
+ assert.equal('expression' in (doc.questionsById?.['ex-1'] ?? {}), false)
1432
+ assert.deepEqual(findDocLawViolations(doc), [])
1433
+ })
1434
+
1435
+ it('leaves a legacy noncanonical token alone when its alternative goes', () => {
1436
+ const base = apply(
1437
+ [{ type: 'question.updateField', questionId: 'ex-1', field: 'expression.base', value: '<exp_65612d31 + <exp_deadbeef>' }],
1438
+ ac9(),
1439
+ )
1440
+ const doc = apply([{ type: 'alternative.delete', questionId: 'ex-1', alternativeId: 'ea-1' }], base)
1441
+ // Publication reports it; the reducer does not guess which legacy token meant this alternative.
1442
+ assert.equal((doc.questionsById?.['ex-1']?.['expression'] as Record<string, unknown>)['base'], '<exp_65612d31 + <exp_deadbeef>')
1443
+ })
1444
+ })
1445
+
1446
+ describe('the AC-9 released bags are not narrowed', () => {
1447
+ it('still writes every new path through the old updateField ops', () => {
1448
+ // The append-only pattern: `question.updateField`/`alternative.updateField` keep working on
1449
+ // exactly the paths the typed ops now own, so v0.31 logs replay unchanged.
1450
+ const doc = apply(
1451
+ [
1452
+ { type: 'question.updateField', questionId: 'ch-1', field: 'chart.legendRange.min', value: 0 },
1453
+ { type: 'question.updateField', questionId: 'ch-1', field: 'chart.newIndicator', value: 'buffer' },
1454
+ { type: 'alternative.updateField', questionId: 'ex-1', alternativeId: 'ea-1', field: 'value', value: 'legacy formula' },
1455
+ { type: 'alternative.updateField', questionId: 'ch-1', alternativeId: 'ca-1', field: 'chartLegend', value: 'not even an object' },
1456
+ ],
1457
+ ac9(),
1458
+ )
1459
+ assert.equal(alternative(doc, 'ea-1')?.['value'], 'legacy formula')
1460
+ assert.equal(alternative(doc, 'ca-1')?.['chartLegend'], 'not even an object')
1461
+ assert.equal(chart(doc)?.['newIndicator'], 'buffer')
1462
+ // Readable and valid: a stored UI buffer is refused by publication, not by the reducer.
1463
+ const validated = validateTemplateDocument(doc)
1464
+ assert.ok(validated.ok, validated.ok ? '' : validated.summary)
1465
+ })
1466
+
1467
+ it('keeps an imported pie/unknown chart and a malformed legend bag readable', () => {
1468
+ const doc = apply(
1469
+ [
1470
+ { type: 'question.updateField', questionId: 'ch-2', field: 'chart.type', value: 'pie' },
1471
+ { type: 'question.updateField', questionId: 'ch-2', field: 'chart.legendsById', value: 'malformed' },
1472
+ ],
1473
+ ac9(),
1474
+ )
1475
+ const validated = validateTemplateDocument(doc)
1476
+ assert.ok(validated.ok, validated.ok ? '' : validated.summary)
1477
+ // …and none of it becomes writable through the typed path.
1478
+ throwsConflict(() => apply([{ type: 'chartLegend.create', questionId: 'ch-2', legendId: 'lg-1', label: 'A' }], doc), 'pie stays read-only')
1479
+ })
1480
+
1481
+ it('replays a v0.31 alternative.updateField log to byte-identical bytes', () => {
1482
+ const doc = apply(
1483
+ [
1484
+ { type: 'alternative.updateField', questionId: 'ex-1', alternativeId: 'ea-1', field: 'value', value: '<target_deadbeef>' },
1485
+ { type: 'alternative.updateField', questionId: 'ex-1', alternativeId: 'ea-1', field: 'expressionTargets', value: ['tg-1'] },
1486
+ ],
1487
+ ac9(),
1488
+ )
1489
+ assert.equal(canonicalJson(alternative(doc, 'ea-1')), '{"expressionTargets":["tg-1"],"label":"Formel","value":"<target_deadbeef>"}')
1490
+ })
1491
+ })
1492
+
1493
+ // ───────── survivor closure: cases the first mutation pass reached for the wrong reason ─────────
1494
+
1495
+ /**
1496
+ * Eight seeded mutants survived the first pass, and every one exposed a fixture that passed for a
1497
+ * reason other than the one it claimed. They are collected here because each needs a *specific* input
1498
+ * the happy-path fixtures do not produce — a flags bag that exists but is off, a Chart that is a legal
1499
+ * target except for its type, a payload that reaches the reducer without passing the schema.
1500
+ */
1501
+ describe('the target gate refuses for the stated reason, not an incidental one', () => {
1502
+ /** The `ac9` fixture's unflagged target has no `flags` bag at all, so the bag guard caught it and
1503
+ * the `is_expression === true` check was never the thing doing the work. */
1504
+ const withFlagBags = () =>
1505
+ apply(
1506
+ [
1507
+ { type: 'question.create', questionId: 'tg-false', questionType: 'RadioButtons' },
1508
+ { type: 'question.updateField', questionId: 'tg-false', field: 'flags.is_expression', value: false },
1509
+ { type: 'question.create', questionId: 'tg-other', questionType: 'RadioButtons' },
1510
+ { type: 'question.updateField', questionId: 'tg-other', field: 'flags.small_size', value: true },
1511
+ // A Chart that would otherwise qualify: the flag IS on, so only the type excludes it.
1512
+ { type: 'question.updateField', questionId: 'ch-2', field: 'flags.is_expression', value: true },
1513
+ ],
1514
+ ac9(),
1515
+ )
1516
+
1517
+ it('refuses a target whose flag is present but not true', () => {
1518
+ // `flags.is_expression: false` and a flags bag with unrelated members are both "flag off" —
1519
+ // and both must be refused by the value check rather than by the bag being absent.
1520
+ for (const questionId of ['tg-false', 'tg-other']) {
1521
+ throwsConflict(
1522
+ () => apply([{ type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: '0', expressionTargets: [questionId] }], withFlagBags()),
1523
+ `"${questionId}" has a flags bag but no true is_expression`,
1524
+ )
1525
+ }
1526
+ })
1527
+
1528
+ it('refuses a Chart target even when its is_expression flag is on', () => {
1529
+ // A chart scoring a chart is the cycle legacy never allowed, so the TYPE must exclude it
1530
+ // independently of the flag.
1531
+ throwsConflict(
1532
+ () => apply([{ type: 'alternative.setExpressionFormula', questionId: 'ex-1', alternativeId: 'ea-1', value: '0', expressionTargets: ['ch-2'] }], withFlagBags()),
1533
+ 'a flagged Chart is still not a target',
1534
+ )
1535
+ const legend = apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' }], withFlagBags())
1536
+ throwsConflict(
1537
+ () => apply([{ type: 'alternative.setChartLegend', questionId: 'ch-1', alternativeId: 'ca-1', chartLegend: { id: 'lg-1', questionIdMap: 'ch-2' } }], legend),
1538
+ 'a flagged Chart is still not an assignment target',
1539
+ )
1540
+ })
1541
+ })
1542
+
1543
+ describe('the Chart assignment label is derived even on a replayed op', () => {
1544
+ it('ignores a label that reached the reducer without passing the schema', () => {
1545
+ // The reducer is reachable without the validator: bunjs replays a stored `collab_ops` log
1546
+ // directly. So the schema refusing a client label is not sufficient — the reducer must derive it
1547
+ // regardless, or one legend id ends up carrying two labels and therefore two document hashes.
1548
+ const base = apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' }], ac9())
1549
+ const replayed = {
1550
+ type: 'alternative.setChartLegend',
1551
+ questionId: 'ch-1',
1552
+ alternativeId: 'ca-1',
1553
+ chartLegend: { id: 'lg-1', questionIdMap: 'tg-1', label: 'Noe klienten fant på' },
1554
+ } as unknown as TemplateOp
1555
+
1556
+ const doc = apply([replayed], base)
1557
+ assert.deepEqual(alternative(doc, 'ca-1')?.['chartLegend'], {
1558
+ id: 'lg-1',
1559
+ questionIdMap: 'tg-1',
1560
+ label: 'Fysisk',
1561
+ })
1562
+ })
1563
+ })
1564
+
1565
+ describe('alternative.delete rewrites only its own owner formula', () => {
1566
+ it('does nothing when the owning question has no base formula, even if another question does', () => {
1567
+ // The owner is looked up by id. Scanning for "the first question with a base" would rewrite a
1568
+ // formula belonging to someone else — invisible while the owner happens to be found first.
1569
+ const base = apply(
1570
+ [
1571
+ // A distinguishing member on the owner. Without it the two ExpressionQuestions are
1572
+ // structurally identical once the base is stripped — and because the helper writes its
1573
+ // result back to the OWNER's key, reading the wrong question produced a document equal
1574
+ // to the right one. That is exactly how this mutant survived the first pass.
1575
+ { type: 'question.updateField', questionId: 'ex-1', field: 'label', value: 'Eier' },
1576
+ { type: 'question.create', questionId: 'ex-2', questionType: 'ExpressionQuestion' },
1577
+ { type: 'question.updateField', questionId: 'ex-2', field: 'label', value: 'Annen' },
1578
+ { type: 'question.updateField', questionId: 'ex-2', field: 'expression.base', value: makeExpressionAlternativeToken('ea-1') },
1579
+ { type: 'alternative.create', questionId: 'ex-2', alternativeId: 'ea-2', label: 'To' },
1580
+ ],
1581
+ ac9(),
1582
+ )
1583
+ // `ex-1` owns `ea-1` and carries NO base; `ex-2` carries a base citing `ea-1`.
1584
+ assert.equal('expression' in (base.questionsById?.['ex-1'] ?? {}), false)
1585
+
1586
+ const doc = apply([{ type: 'alternative.delete', questionId: 'ex-1', alternativeId: 'ea-1' }], base)
1587
+ assert.equal(
1588
+ (doc.questionsById?.['ex-2']?.['expression'] as Record<string, unknown>)['base'],
1589
+ '<exp_65612d31>',
1590
+ )
1591
+ // The owner is untouched ENTIRELY — not merely still base-less.
1592
+ assert.deepEqual(doc.questionsById?.['ex-1'], { type: 'ExpressionQuestion', label: 'Eier' })
1593
+ assert.equal(doc.questionsById?.['ex-2']?.label, 'Annen')
1594
+ })
1595
+ })
1596
+
1597
+ describe('the alternative token recognizer enforces the same exact grammar as the target one', () => {
1598
+ it('refuses uppercase, odd-length, empty and claimant spellings', () => {
1599
+ for (const value of [
1600
+ '<exp_65612D31>', // uppercase
1601
+ '<exp_6561231>', // odd length
1602
+ '<exp_>', // empty body
1603
+ '<exp_65G1>', // non-hex
1604
+ '<exp_6561', // unterminated
1605
+ 'x<exp_6561>', // prefix claimant
1606
+ '<exp_6561>x', // suffix claimant
1607
+ '<target_6561>', // the other token space
1608
+ ]) {
1609
+ assert.equal(isExpressionAlternativeToken(value), false, value)
1610
+ }
1611
+ assert.equal(isExpressionAlternativeToken(makeExpressionAlternativeToken('ea-1')), true)
1612
+ })
1613
+ })
1614
+
1615
+ describe('the tab document members are typed, not admitted by the open index', () => {
1616
+ it('refuses an array of objects and a non-string member for both lists', () => {
1617
+ // The tab bag keeps its open `[string]: unknown` index, so leaving these members untyped would
1618
+ // silently admit exactly the array-of-objects shape DOC-LAW-1 exists to prevent.
1619
+ for (const [member, value] of [
1620
+ ['questionIds', [{ questionId: 'q-1' }]],
1621
+ ['questionIds', [1, 2]],
1622
+ ['rowCountQuestionIds', [{ questionId: 'g-1' }]],
1623
+ ['rowCountQuestionIds', 'g-1'],
1624
+ ] as const) {
1625
+ const doc = {
1626
+ documentId: 'tpl-schema',
1627
+ revision: 0,
1628
+ questionOrder: [],
1629
+ tabsById: { 't-1': { label: 'Fane', [member]: value } },
1630
+ }
1631
+ const validated = validateTemplateDocument(doc as never)
1632
+ assert.equal(validated.ok, false, `${member} = ${JSON.stringify(value)} must not validate`)
1633
+ }
1634
+ })
1635
+
1636
+ it('still validates the legal primitive-id arrays and an unrelated open member', () => {
1637
+ const validated = validateTemplateDocument({
1638
+ documentId: 'tpl-schema',
1639
+ revision: 0,
1640
+ questionOrder: [],
1641
+ tabsById: { 't-1': { label: 'Fane', questionIds: ['q-1'], rowCountQuestionIds: ['g-1'], legacyBag: { a: 1 } } },
1642
+ } as never)
1643
+ assert.ok(validated.ok, validated.ok ? '' : validated.summary)
1644
+ })
1645
+ })
1646
+
1647
+ // ───────── the admissible target vocabulary, pinned exhaustively in both directions ─────────
1648
+
1649
+ /**
1650
+ * `EXPRESSION_TARGET_TYPES` is a hand-maintained opt-in literal, and the type system can only check
1651
+ * that its members *are* question types — never that they are the *right* ones.
1652
+ *
1653
+ * That gap was measured: dropping four of the six admissible types, widening the list with a scalar
1654
+ * `TextShort`, or widening it with `ExpressionQuestion` all left the suite green. Dropping a type
1655
+ * silently refuses a legitimate authored target forever; widening makes a non-selectable question a
1656
+ * legal score target, which is the "non-selectable target" the frozen matrix names.
1657
+ *
1658
+ * So the vocabulary is pinned here, exhaustively over the whole shared register: every admissible type
1659
+ * must be ACCEPTED and every other type in `QUESTION_TYPES` must be REFUSED. Enumerating the
1660
+ * complement rather than a hand-picked sample is deliberate — adding a question type to the shared
1661
+ * register then forces a decision here instead of silently defaulting either way.
1662
+ */
1663
+ describe('the Expression/Chart target vocabulary', () => {
1664
+ const ADMISSIBLE: readonly QuestionType[] = [
1665
+ 'BooleanQuestion',
1666
+ 'CheckBoxes',
1667
+ 'Dropdown',
1668
+ 'Emoticons',
1669
+ 'LinearScale',
1670
+ 'RadioButtons',
1671
+ ]
1672
+ const REFUSED = QUESTION_TYPES.filter((type) => !ADMISSIBLE.includes(type))
1673
+
1674
+ /** One flagged question of `type`, so `flags.is_expression` can never be the reason for a refusal. */
1675
+ const withTarget = (type: QuestionType) =>
1676
+ apply(
1677
+ [
1678
+ { type: 'question.create', questionId: 'target', questionType: type },
1679
+ { type: 'question.updateField', questionId: 'target', field: 'flags.is_expression', value: true },
1680
+ ],
1681
+ ac9(),
1682
+ )
1683
+
1684
+ const setFormula: TemplateOp = {
1685
+ type: 'alternative.setExpressionFormula',
1686
+ questionId: 'ex-1',
1687
+ alternativeId: 'ea-1',
1688
+ value: '0',
1689
+ expressionTargets: ['target'],
1690
+ }
1691
+
1692
+ it('admits exactly the six selectable-or-LinearScale types', () => {
1693
+ // This direction catches a DROPPED member: the refusal-only tests cannot.
1694
+ for (const type of ADMISSIBLE) {
1695
+ assert.doesNotThrow(() => apply([setFormula], withTarget(type)), `${type} must be admitted as a target`)
1696
+ }
1697
+ })
1698
+
1699
+ it('refuses every other type in the shared register', () => {
1700
+ // Each is created WITH the flag on, so only the type list can be doing the refusing.
1701
+ assert.ok(REFUSED.length > 0, 'the complement must be non-empty or this test is vacuous')
1702
+ for (const type of REFUSED) {
1703
+ throwsConflict(() => apply([setFormula], withTarget(type)), `${type} must be refused as a target`)
1704
+ }
1705
+ })
1706
+
1707
+ it('applies the same vocabulary to a Chart assignment target', () => {
1708
+ // One gate, two operations: a type legal for a formula must be legal for an assignment and
1709
+ // vice-versa, or the two paths would drift into two different vocabularies.
1710
+ const assignment = (): TemplateOp => ({
1711
+ type: 'alternative.setChartLegend',
1712
+ questionId: 'ch-1',
1713
+ alternativeId: 'ca-1',
1714
+ chartLegend: { id: 'lg-1', questionIdMap: 'target' },
1715
+ })
1716
+ const withLegend = (type: QuestionType) =>
1717
+ apply([{ type: 'chartLegend.create', questionId: 'ch-1', legendId: 'lg-1', label: 'Fysisk' }], withTarget(type))
1718
+
1719
+ for (const type of ADMISSIBLE) {
1720
+ assert.doesNotThrow(() => apply([assignment()], withLegend(type)), `${type} must be an assignment target`)
1721
+ }
1722
+ for (const type of REFUSED) {
1723
+ throwsConflict(() => apply([assignment()], withLegend(type)), `${type} must not be an assignment target`)
1724
+ }
1725
+ })
1726
+
1727
+ it('covers the whole register, so a new question type cannot slip past undecided', () => {
1728
+ assert.equal(ADMISSIBLE.length + REFUSED.length, QUESTION_TYPES.length)
1729
+ // Every admissible type is a real member of the shared register, not a typo.
1730
+ for (const type of ADMISSIBLE) assert.ok(QUESTION_TYPES.includes(type), `${type} is not a QuestionType`)
1731
+ })
1732
+ })