@intellectif/lk-core 1.1.0 → 1.3.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 (99) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +4 -3
  3. package/dist/ai-B222dtHH.d.cts +2154 -0
  4. package/dist/ai-B222dtHH.d.cts.map +1 -0
  5. package/dist/ai-B222dtHH.d.ts +2154 -0
  6. package/dist/ai-B222dtHH.d.ts.map +1 -0
  7. package/dist/ai-check.cjs +758 -464
  8. package/dist/ai-check.cjs.map +1 -1
  9. package/dist/ai-check.d.cts +82 -68
  10. package/dist/ai-check.d.cts.map +1 -0
  11. package/dist/ai-check.d.ts +82 -68
  12. package/dist/ai-check.d.ts.map +1 -0
  13. package/dist/ai-check.js +756 -465
  14. package/dist/ai-check.js.map +1 -1
  15. package/dist/ai-writing-CCBjTOM3.js +2496 -0
  16. package/dist/ai-writing-CCBjTOM3.js.map +1 -0
  17. package/dist/ai-writing-DCVkv4Zj.cjs +2735 -0
  18. package/dist/ai-writing-DCVkv4Zj.cjs.map +1 -0
  19. package/dist/{index-DlcqkM_L.d.ts → index-BWPRPIXL.d.ts} +263 -258
  20. package/dist/index-BWPRPIXL.d.ts.map +1 -0
  21. package/dist/index-CXyOV8sm.d.cts +153 -0
  22. package/dist/index-CXyOV8sm.d.cts.map +1 -0
  23. package/dist/index-CegM8o15.d.ts +153 -0
  24. package/dist/index-CegM8o15.d.ts.map +1 -0
  25. package/dist/index-Dyu66R4-.d.cts +1071 -0
  26. package/dist/index-Dyu66R4-.d.cts.map +1 -0
  27. package/dist/{index-DlCW0XaQ.d.cts → index-O4_ExlAD.d.cts} +263 -258
  28. package/dist/index-O4_ExlAD.d.cts.map +1 -0
  29. package/dist/index-UGxRSopE.d.ts +1071 -0
  30. package/dist/index-UGxRSopE.d.ts.map +1 -0
  31. package/dist/index.cjs +1210 -1671
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +1090 -853
  34. package/dist/index.d.cts.map +1 -0
  35. package/dist/index.d.ts +1090 -853
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +1063 -1672
  38. package/dist/index.js.map +1 -1
  39. package/dist/item-group-DXiR8nOr.js +445 -0
  40. package/dist/item-group-DXiR8nOr.js.map +1 -0
  41. package/dist/item-group-DroFXgLb.cjs +505 -0
  42. package/dist/item-group-DroFXgLb.cjs.map +1 -0
  43. package/dist/registry-DVi0LR_i.cjs +5915 -0
  44. package/dist/registry-DVi0LR_i.cjs.map +1 -0
  45. package/dist/registry-Dsx9mNsS.js +5449 -0
  46. package/dist/registry-Dsx9mNsS.js.map +1 -0
  47. package/dist/schemas-Bdw0nGPo.js +152 -0
  48. package/dist/schemas-Bdw0nGPo.js.map +1 -0
  49. package/dist/schemas-DVbAOrtd.cjs +224 -0
  50. package/dist/schemas-DVbAOrtd.cjs.map +1 -0
  51. package/dist/schemas.cjs +16 -32
  52. package/dist/schemas.d.cts +2 -2
  53. package/dist/schemas.d.ts +2 -2
  54. package/dist/schemas.js +3 -32
  55. package/dist/scoring-B2_HEhMT.cjs +1748 -0
  56. package/dist/scoring-B2_HEhMT.cjs.map +1 -0
  57. package/dist/scoring-BZqUkuDF.js +1604 -0
  58. package/dist/scoring-BZqUkuDF.js.map +1 -0
  59. package/dist/scoring.cjs +37 -75
  60. package/dist/scoring.d.cts +3 -1103
  61. package/dist/scoring.d.ts +3 -1103
  62. package/dist/scoring.js +3 -75
  63. package/dist/xapi-CMTph7wG.js +332 -0
  64. package/dist/xapi-CMTph7wG.js.map +1 -0
  65. package/dist/xapi-DNzkSJ0S.cjs +362 -0
  66. package/dist/xapi-DNzkSJ0S.cjs.map +1 -0
  67. package/dist/xapi.cjs +7 -16
  68. package/dist/xapi.d.cts +2 -150
  69. package/dist/xapi.d.ts +2 -150
  70. package/dist/xapi.js +2 -16
  71. package/package.json +4 -4
  72. package/dist/activity-MBOYLBjR.d.cts +0 -1840
  73. package/dist/activity-MBOYLBjR.d.ts +0 -1840
  74. package/dist/chunk-2JT2WUQ2.cjs +0 -458
  75. package/dist/chunk-2JT2WUQ2.cjs.map +0 -1
  76. package/dist/chunk-DSDXL3JO.cjs +0 -4597
  77. package/dist/chunk-DSDXL3JO.cjs.map +0 -1
  78. package/dist/chunk-FBKTION6.js +0 -4597
  79. package/dist/chunk-FBKTION6.js.map +0 -1
  80. package/dist/chunk-IARLJ5MW.js +0 -1256
  81. package/dist/chunk-IARLJ5MW.js.map +0 -1
  82. package/dist/chunk-LDFQUZII.cjs +0 -950
  83. package/dist/chunk-LDFQUZII.cjs.map +0 -1
  84. package/dist/chunk-NQHETFDA.js +0 -950
  85. package/dist/chunk-NQHETFDA.js.map +0 -1
  86. package/dist/chunk-SJVRUPJT.js +0 -272
  87. package/dist/chunk-SJVRUPJT.js.map +0 -1
  88. package/dist/chunk-TJJFKKH2.cjs +0 -272
  89. package/dist/chunk-TJJFKKH2.cjs.map +0 -1
  90. package/dist/chunk-VSH7ECQL.cjs +0 -1256
  91. package/dist/chunk-VSH7ECQL.cjs.map +0 -1
  92. package/dist/chunk-XS6U2ARZ.js +0 -458
  93. package/dist/chunk-XS6U2ARZ.js.map +0 -1
  94. package/dist/schemas.cjs.map +0 -1
  95. package/dist/schemas.js.map +0 -1
  96. package/dist/scoring.cjs.map +0 -1
  97. package/dist/scoring.js.map +0 -1
  98. package/dist/xapi.cjs.map +0 -1
  99. package/dist/xapi.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,1771 +1,1162 @@
1
- import {
2
- XAPIVerb,
3
- XAPI_VERB_DISPLAY,
4
- validateXAPIStatement,
5
- xAPIBuilder,
6
- xapiDefinitionFor
7
- } from "./chunk-SJVRUPJT.js";
8
- import {
9
- INTERACTIVE_VIDEO_ITEM_TYPES,
10
- ItemGroupSchema,
11
- RedactedItemGroupSchema,
12
- TIMELINE_MAX_CHAPTERS,
13
- TIMELINE_MAX_ITEMS,
14
- TIMELINE_MAX_QUIZZES,
15
- TIMELINE_MAX_TITLE_LENGTH,
16
- dictationJsonSchema,
17
- fillInTheBlanksJsonSchema,
18
- gapSelectJsonSchema,
19
- isInteractiveVideoItemType,
20
- itemGroupJsonSchema,
21
- jsonSchemaFor,
22
- multipleChoiceJsonSchema,
23
- readAloudJsonSchema,
24
- stimulusJsonSchema,
25
- validateActivity,
26
- validateItemGroup,
27
- validateMedia,
28
- validateOptionMedia,
29
- writtenResponseJsonSchema
30
- } from "./chunk-XS6U2ARZ.js";
31
- import {
32
- AI_COACHING_MAX_TIP_LENGTH,
33
- AI_COACHING_MAX_WORDS,
34
- AI_EXPLANATION_TYPES,
35
- AI_HINT_TYPES,
36
- AI_TEXT_MAX_LENGTH,
37
- AI_WRITING_MAX_CORRECTIONS,
38
- AI_WRITING_MAX_FIELD_LENGTH,
39
- aiAllowedByContent,
40
- aiCoachingRequest,
41
- aiExplanationRequest,
42
- aiGradeOf,
43
- aiHintRequest,
44
- aiSupports,
45
- aiWritingFeedbackRequest,
46
- buildAiFacts,
47
- checkAiCoaching,
48
- checkAiExplanation,
49
- checkAiHint,
50
- checkAiWritingFeedback,
51
- hintRevealsAnswer,
52
- readAiTextResult
53
- } from "./chunk-NQHETFDA.js";
54
- import {
55
- DEFAULT_ITEM_SCORING_POLICY,
56
- DEFAULT_PASS_THRESHOLD,
57
- ITEM_SCORING_MAX_RETRIES,
58
- alignReadAloud,
59
- classifyBand,
60
- composeAssessmentScore,
61
- computePassThreshold,
62
- diffDictationChars,
63
- evaluate,
64
- evaluateTries,
65
- gradeFromRubric,
66
- gradeReadAloud,
67
- gte,
68
- hasGrade,
69
- inspectWav,
70
- outcomeFromGrade,
71
- outcomeFromUnscorable,
72
- resolveItemScoringPolicy,
73
- roundGrade,
74
- score,
75
- scoreTries,
76
- validateItemScoringPolicy,
77
- validateSpeechAssessment
78
- } from "./chunk-IARLJ5MW.js";
79
- import {
80
- ActivitySchemaError,
81
- DICTATION_MAX_ACCEPTED_TRANSCRIPTS,
82
- DICTATION_MAX_EQUIVALENCES,
83
- DICTATION_MAX_EQUIVALENCE_LENGTH,
84
- DICTATION_MAX_TEXT_LENGTH,
85
- DICTATION_MAX_TRANSCRIPT_LENGTH,
86
- DRAFT_ISSUE_SEVERITY,
87
- DeferredScoringError,
88
- GROUP_CAPTIONS_REVEAL_DICTATION,
89
- MEDIA_FIELD_POLICY,
90
- READ_ALOUD_MAX_DIMENSION_WEIGHT,
91
- READ_ALOUD_MAX_REFERENCE_LENGTH,
92
- READ_ALOUD_MAX_SECONDS,
93
- READ_ALOUD_MAX_TAKES,
94
- RedactedScoringError,
95
- SPEECH_ASSESSMENT_MAX_WORDS,
96
- UnknownActivityTypeError,
97
- alignDictation,
98
- checkMedia,
99
- countWords,
100
- coveredPathsOf,
101
- covers,
102
- defineActivityType,
103
- dictationReferenceWords,
104
- dictationType,
105
- fillInTheBlanksType,
106
- gapSelectType,
107
- getActivityTypeDescriptor,
108
- groupCaptionsField,
109
- isMissingId,
110
- isRecord,
111
- isUnset,
112
- isUnwritten,
113
- issue,
114
- levenshteinDistance,
115
- matchText,
116
- multipleChoiceType,
117
- pathKey,
118
- readAloudType,
119
- readSchema,
120
- refusesEmpty,
121
- registerActivityType,
122
- registeredActivityTypes,
123
- withValidationScope,
124
- writtenResponseType
125
- } from "./chunk-FBKTION6.js";
126
-
127
- // src/content-hash.ts
1
+ import { A as AI_TEXT_MAX_LENGTH, B as readAiTextResult, C as validateItemGroupDraft, D as checkAiCoaching, E as aiCoachingRequest, F as aiSupports, I as buildAiFacts, L as checkAiExplanation, M as aiExplanationRequest, N as aiGradeOf, O as AI_EXPLANATION_TYPES, P as aiHintRequest, R as checkAiHint, S as critiqueItemGroupDraft, T as AI_COACHING_MAX_WORDS, _ as critiqueDraft, a as AI_DRAFTS_MAX_COUNT, b as createItemGroupDraft, c as aiDraftsRequest, d as interactiveVideoFromDrafts, f as AI_CRITIQUE_MAX_FIELD_LENGTH, g as createDraft, h as checkAiCritique, i as checkAiWritingFeedback, j as aiAllowedByContent, k as AI_HINT_TYPES, l as checkAiDrafts, m as aiCritiqueRequest, n as AI_WRITING_MAX_FIELD_LENGTH, o as AI_DRAFTS_MAX_REPAIRS, p as AI_CRITIQUE_MAX_FINDINGS, r as aiWritingFeedbackRequest, s as aiDraftsRepairRequest, t as AI_WRITING_MAX_CORRECTIONS, u as generateDrafts, v as validateDraft, w as AI_COACHING_MAX_TIP_LENGTH, x as critiqueDrafts, y as createInteractiveVideoDraft, z as hintRevealsAnswer } from "./ai-writing-CCBjTOM3.js";
2
+ import { $ as dictationReferenceWords, A as matchText, J as RedactedScoringError, K as ActivitySchemaError, S as READ_ALOUD_MAX_TAKES, Y as UnknownActivityTypeError, Z as alignDictation, a as readSchema, b as READ_ALOUD_MAX_REFERENCE_LENGTH, c as dictationType, ct as BUILT_IN_ACTIVITY_TYPES, d as multipleChoiceType, et as DICTATION_MAX_ACCEPTED_TRANSCRIPTS, f as readAloudType, it as DICTATION_MAX_TRANSCRIPT_LENGTH, j as countWords, k as levenshteinDistance, l as fillInTheBlanksType, m as defineActivityType, n as registerActivityType, nt as DICTATION_MAX_EQUIVALENCE_LENGTH, p as writtenResponseType, q as DeferredScoringError, r as registeredActivityTypes, rt as DICTATION_MAX_TEXT_LENGTH, s as MEDIA_FIELD_POLICY, t as getActivityTypeDescriptor, tt as DICTATION_MAX_EQUIVALENCES, u as gapSelectType, ut as isBuiltInActivityType, w as SPEECH_ASSESSMENT_MAX_WORDS, x as READ_ALOUD_MAX_SECONDS, y as READ_ALOUD_MAX_DIMENSION_WEIGHT } from "./registry-Dsx9mNsS.js";
3
+ import { C as validateItemScoringPolicy, S as scoreTries, _ as gte, a as inspectWav, b as ITEM_SCORING_MAX_RETRIES, c as validateSpeechAssessment, d as gradeFromRubric, f as hasGrade, g as classifyBand, h as computePassThreshold, i as outcomeFromUnscorable, l as diffDictationChars, m as DEFAULT_PASS_THRESHOLD, n as evaluateTries, o as gradeReadAloud, p as outcomeFromGrade, r as score, s as alignReadAloud, t as evaluate, u as composeAssessmentScore, v as roundGrade, x as resolveItemScoringPolicy, y as DEFAULT_ITEM_SCORING_POLICY } from "./scoring-BZqUkuDF.js";
4
+ import { a as INTERACTIVE_VIDEO_ITEM_TYPES, c as TIMELINE_MAX_QUIZZES, i as validateItemGroup, l as TIMELINE_MAX_TITLE_LENGTH, n as RedactedItemGroupSchema, o as TIMELINE_MAX_CHAPTERS, s as TIMELINE_MAX_ITEMS, u as isInteractiveVideoItemType } from "./item-group-DXiR8nOr.js";
5
+ import { a as fillInTheBlanksJsonSchema, c as jsonSchemaFor, d as stimulusJsonSchema, f as writtenResponseJsonSchema, i as dictationJsonSchema, l as multipleChoiceJsonSchema, n as validateMedia, o as gapSelectJsonSchema, r as validateOptionMedia, s as itemGroupJsonSchema, t as validateActivity, u as readAloudJsonSchema } from "./schemas-Bdw0nGPo.js";
6
+ import { a as validateXAPIStatement, i as XAPI_VERB_DISPLAY, n as xapiDefinitionFor, r as XAPIVerb, t as xAPIBuilder } from "./xapi-CMTph7wG.js";
7
+ //#region src/content-hash.ts
8
+ /**
9
+ * Content fingerprinting — "is this the same content the learner was served?"
10
+ *
11
+ * A recorded attempt outlives the content it was taken against. Papers get
12
+ * corrected, a typo is fixed, an option is reworded — and six months later a
13
+ * remark, an appeal, or a per-item analysis is run against content that is no
14
+ * longer what the learner saw. Nothing warns anybody, because the ids all still
15
+ * match. A fingerprint stored with the attempt turns that silent drift into a
16
+ * question somebody can answer.
17
+ */
18
+ /**
19
+ * Deterministic JSON: object keys sorted, arrays left in order, `undefined`
20
+ * omitted from objects (matching `JSON.stringify`) and rendered as `null`
21
+ * inside arrays.
22
+ *
23
+ * Key order is the whole point. Two objects that differ only in the order
24
+ * their keys happened to be written are the SAME content, and a fingerprint
25
+ * that disagreed would raise a false alarm every time a payload made a
26
+ * round-trip through a different serializer.
27
+ */
128
28
  function canonicalJson(value, seen = /* @__PURE__ */ new Set()) {
129
- if (value === null) {
130
- return "null";
131
- }
132
- if (typeof value === "number") {
133
- return Number.isFinite(value) ? JSON.stringify(value === 0 ? 0 : value) : `"#${String(value)}"`;
134
- }
135
- if (typeof value === "string" || typeof value === "boolean") {
136
- return JSON.stringify(value);
137
- }
138
- if (typeof value === "bigint") {
139
- return `"#${value.toString()}n"`;
140
- }
141
- if (typeof value === "object") {
142
- if (seen.has(value)) {
143
- throw new Error(
144
- "canonicalJson: the value contains a circular reference and cannot be fingerprinted."
145
- );
146
- }
147
- seen.add(value);
148
- try {
149
- if (Array.isArray(value)) {
150
- return `[${value.map((element) => element === void 0 ? "null" : canonicalJson(element, seen)).join(",")}]`;
151
- }
152
- const source = value;
153
- const parts = [];
154
- for (const key of Object.keys(source).sort()) {
155
- const entry = source[key];
156
- if (entry === void 0) {
157
- continue;
158
- }
159
- parts.push(`${JSON.stringify(key)}:${canonicalJson(entry, seen)}`);
160
- }
161
- return `{${parts.join(",")}}`;
162
- } finally {
163
- seen.delete(value);
164
- }
165
- }
166
- return "null";
29
+ if (value === null) return "null";
30
+ if (typeof value === "number") return Number.isFinite(value) ? JSON.stringify(value === 0 ? 0 : value) : `"#${String(value)}"`;
31
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
32
+ if (typeof value === "bigint") return `"#${value.toString()}n"`;
33
+ if (typeof value === "object") {
34
+ if (seen.has(value)) throw new Error("canonicalJson: the value contains a circular reference and cannot be fingerprinted.");
35
+ seen.add(value);
36
+ try {
37
+ if (Array.isArray(value)) return `[${value.map((element) => element === void 0 ? "null" : canonicalJson(element, seen)).join(",")}]`;
38
+ const source = value;
39
+ const parts = [];
40
+ for (const key of Object.keys(source).sort()) {
41
+ const entry = source[key];
42
+ if (entry === void 0) continue;
43
+ parts.push(`${JSON.stringify(key)}:${canonicalJson(entry, seen)}`);
44
+ }
45
+ return `{${parts.join(",")}}`;
46
+ } finally {
47
+ seen.delete(value);
48
+ }
49
+ }
50
+ return "null";
167
51
  }
168
- var FNV_OFFSET = 14695981039346656037n;
169
- var FNV_PRIME = 1099511628211n;
170
- var MASK64 = (1n << 64n) - 1n;
52
+ const FNV_OFFSET = 14695981039346656037n;
53
+ const FNV_PRIME = 1099511628211n;
54
+ const MASK64 = (1n << 64n) - 1n;
55
+ /**
56
+ * FNV-1a over the UTF-8 bytes of `input`, as 16 lowercase hex digits.
57
+ *
58
+ * **This is a change-detection fingerprint, not a tamper-evident signature.**
59
+ * It is deterministic across runtimes and dependency-free, which is what makes
60
+ * it usable in a stored grade record — but an adversary who can edit content
61
+ * can also, with effort, preserve the fingerprint. If you need the stronger
62
+ * property, sign the plan with a key the content author does not hold; this
63
+ * exists to catch honest edits, which is what actually happens.
64
+ */
171
65
  function fingerprint(input) {
172
- const bytes = new TextEncoder().encode(input);
173
- let hash = FNV_OFFSET;
174
- for (const byte of bytes) {
175
- hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK64;
176
- }
177
- return hash.toString(16).padStart(16, "0");
66
+ const bytes = new TextEncoder().encode(input);
67
+ let hash = FNV_OFFSET;
68
+ for (const byte of bytes) hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK64;
69
+ return hash.toString(16).padStart(16, "0");
178
70
  }
71
+ /**
72
+ * Fingerprints any JSON-serialisable value through {@link canonicalJson}, so
73
+ * the result depends on the content and not on how it was written.
74
+ */
179
75
  function contentHash(value) {
180
- return fingerprint(canonicalJson(value));
76
+ return fingerprint(canonicalJson(value));
181
77
  }
182
-
183
- // src/delivery.ts
184
- var OPEN_DELIVERY_POLICY = Object.freeze({
185
- feedback: true,
186
- solutions: true,
187
- hints: true,
188
- ai: Object.freeze({ hints: true, explanations: true })
78
+ //#endregion
79
+ //#region src/delivery.ts
80
+ /**
81
+ * The policy that restricts nothing: every setting `true`. It is what an absent
82
+ * policy resolves to, and it is exactly the behaviour the SDK had before
83
+ * delivery policies existed.
84
+ */
85
+ const OPEN_DELIVERY_POLICY = Object.freeze({
86
+ feedback: true,
87
+ solutions: true,
88
+ hints: true,
89
+ ai: Object.freeze({
90
+ hints: true,
91
+ explanations: true
92
+ })
189
93
  });
190
- var SETTINGS = ["feedback", "solutions", "hints"];
191
- var AI_SETTINGS = ["hints", "explanations"];
94
+ const SETTINGS = [
95
+ "feedback",
96
+ "solutions",
97
+ "hints"
98
+ ];
99
+ const AI_SETTINGS = ["hints", "explanations"];
100
+ /**
101
+ * One setting as a render reads it. Absent or `null` is unset, and unset is
102
+ * `true`: JSON has no `undefined`, so a setting nobody chose arrives from a
103
+ * database as `null`.
104
+ *
105
+ * Anything else that is not exactly `true` reads as `false`. Every setting is a
106
+ * restriction, so a value that cannot be read is read as the restriction — a
107
+ * `"false"` string from a form, say, whose author meant exactly that. Reading
108
+ * it as `true` would put hints on a paper whose school had switched them off.
109
+ */
192
110
  function allows(value) {
193
- return value === void 0 || value === null || value === true;
111
+ return value === void 0 || value === null || value === true;
194
112
  }
113
+ /**
114
+ * A policy with every setting spelled out — see {@link DeliveryPolicy}.
115
+ *
116
+ * Tolerant, because it runs where a learner is waiting: nothing here throws.
117
+ * A value it cannot read restricts rather than allows (see above), and a
118
+ * policy that is not an object at all restricts everything. Check a policy
119
+ * before you store it with {@link validateDeliveryPolicy}; `planAttempt` does.
120
+ */
195
121
  function resolveDeliveryPolicy(policy) {
196
- if (policy === void 0 || policy === null) {
197
- return OPEN_DELIVERY_POLICY;
198
- }
199
- if (typeof policy !== "object" || Array.isArray(policy)) {
200
- return {
201
- feedback: false,
202
- solutions: false,
203
- hints: false,
204
- ai: { hints: false, explanations: false }
205
- };
206
- }
207
- const given = policy;
208
- const ai = given.ai;
209
- const aiGiven = ai === void 0 || ai === null || ai === true ? {} : typeof ai === "object" && !Array.isArray(ai) ? ai : { hints: false, explanations: false };
210
- return {
211
- feedback: allows(given.feedback),
212
- solutions: allows(given.solutions),
213
- hints: allows(given.hints),
214
- ai: { hints: allows(aiGiven.hints), explanations: allows(aiGiven.explanations) }
215
- };
122
+ if (policy === void 0 || policy === null) return OPEN_DELIVERY_POLICY;
123
+ if (typeof policy !== "object" || Array.isArray(policy)) return {
124
+ feedback: false,
125
+ solutions: false,
126
+ hints: false,
127
+ ai: {
128
+ hints: false,
129
+ explanations: false
130
+ }
131
+ };
132
+ const given = policy;
133
+ const ai = given.ai;
134
+ const aiGiven = ai === void 0 || ai === null || ai === true ? {} : typeof ai === "object" && !Array.isArray(ai) ? ai : {
135
+ hints: false,
136
+ explanations: false
137
+ };
138
+ return {
139
+ feedback: allows(given.feedback),
140
+ solutions: allows(given.solutions),
141
+ hints: allows(given.hints),
142
+ ai: {
143
+ hints: allows(aiGiven.hints),
144
+ explanations: allows(aiGiven.explanations)
145
+ }
146
+ };
216
147
  }
148
+ /**
149
+ * The strictest of several policies: a setting is on only where every one of
150
+ * them leaves it on. How a course's policy and an assessment's combine, and
151
+ * how a pager's policy wins over whatever a question it draws was handed.
152
+ */
217
153
  function combineDeliveryPolicies(...policies) {
218
- const resolved = policies.map(resolveDeliveryPolicy);
219
- const every = (read) => resolved.every(read);
220
- return {
221
- feedback: every((one) => one.feedback),
222
- solutions: every((one) => one.solutions),
223
- hints: every((one) => one.hints),
224
- ai: {
225
- hints: every((one) => one.ai.hints),
226
- explanations: every((one) => one.ai.explanations)
227
- }
228
- };
154
+ const resolved = policies.map(resolveDeliveryPolicy);
155
+ const every = (read) => resolved.every(read);
156
+ return {
157
+ feedback: every((one) => one.feedback),
158
+ solutions: every((one) => one.solutions),
159
+ hints: every((one) => one.hints),
160
+ ai: {
161
+ hints: every((one) => one.ai.hints),
162
+ explanations: every((one) => one.ai.explanations)
163
+ }
164
+ };
229
165
  }
166
+ /**
167
+ * Checks a policy before it is stored: each setting `true`, `false`, `null`
168
+ * or absent, and nothing else — no misspelled setting, no string standing in
169
+ * for a boolean.
170
+ *
171
+ * Stricter than {@link resolveDeliveryPolicy} on purpose. A misspelled
172
+ * restriction (`hint: false`) is silently no restriction at all, and a
173
+ * policy is a record of the conditions a paper was sat under: it is worth
174
+ * refusing before it is written down, rather than read charitably after.
175
+ */
230
176
  function validateDeliveryPolicy(policy) {
231
- const issues = [];
232
- if (policy === void 0 || policy === null) {
233
- return { success: true, data: {} };
234
- }
235
- if (typeof policy !== "object" || Array.isArray(policy)) {
236
- return {
237
- success: false,
238
- issues: [{ path: "", message: "A delivery policy is an object of settings." }]
239
- };
240
- }
241
- const given = policy;
242
- for (const key of Object.keys(given)) {
243
- if (key === "ai") {
244
- continue;
245
- }
246
- if (!SETTINGS.includes(key)) {
247
- issues.push({
248
- path: key,
249
- message: `"${key}" is not a delivery setting. The settings are feedback, solutions, hints and ai.`
250
- });
251
- continue;
252
- }
253
- const value = given[key];
254
- if (value !== true && value !== false && value !== null && value !== void 0) {
255
- issues.push({ path: key, message: `"${key}" must be true, false or null.` });
256
- }
257
- }
258
- const ai = given.ai;
259
- if (ai !== void 0 && ai !== null && ai !== true && ai !== false) {
260
- if (typeof ai !== "object" || Array.isArray(ai)) {
261
- issues.push({
262
- path: "ai",
263
- message: '"ai" must be true, false, or an object of hints and explanations.'
264
- });
265
- } else {
266
- for (const [key, value] of Object.entries(ai)) {
267
- if (!AI_SETTINGS.includes(key)) {
268
- issues.push({
269
- path: `ai.${key}`,
270
- message: `"ai.${key}" is not an AI setting. The settings are hints and explanations.`
271
- });
272
- continue;
273
- }
274
- if (value !== true && value !== false && value !== null && value !== void 0) {
275
- issues.push({ path: `ai.${key}`, message: `"ai.${key}" must be true, false or null.` });
276
- }
277
- }
278
- }
279
- }
280
- return issues.length > 0 ? { success: false, issues } : { success: true, data: given };
177
+ const issues = [];
178
+ if (policy === void 0 || policy === null) return {
179
+ success: true,
180
+ data: {}
181
+ };
182
+ if (typeof policy !== "object" || Array.isArray(policy)) return {
183
+ success: false,
184
+ issues: [{
185
+ path: "",
186
+ message: "A delivery policy is an object of settings."
187
+ }]
188
+ };
189
+ const given = policy;
190
+ for (const key of Object.keys(given)) {
191
+ if (key === "ai") continue;
192
+ if (!SETTINGS.includes(key)) {
193
+ issues.push({
194
+ path: key,
195
+ message: `"${key}" is not a delivery setting. The settings are feedback, solutions, hints and ai.`
196
+ });
197
+ continue;
198
+ }
199
+ const value = given[key];
200
+ if (value !== true && value !== false && value !== null && value !== void 0) issues.push({
201
+ path: key,
202
+ message: `"${key}" must be true, false or null.`
203
+ });
204
+ }
205
+ const ai = given.ai;
206
+ if (ai !== void 0 && ai !== null && ai !== true && ai !== false) {
207
+ if (typeof ai !== "object" || Array.isArray(ai)) issues.push({
208
+ path: "ai",
209
+ message: "\"ai\" must be true, false, or an object of hints and explanations."
210
+ });
211
+ else for (const [key, value] of Object.entries(ai)) {
212
+ if (!AI_SETTINGS.includes(key)) {
213
+ issues.push({
214
+ path: `ai.${key}`,
215
+ message: `"ai.${key}" is not an AI setting. The settings are hints and explanations.`
216
+ });
217
+ continue;
218
+ }
219
+ if (value !== true && value !== false && value !== null && value !== void 0) issues.push({
220
+ path: `ai.${key}`,
221
+ message: `"ai.${key}" must be true, false or null.`
222
+ });
223
+ }
224
+ }
225
+ return issues.length > 0 ? {
226
+ success: false,
227
+ issues
228
+ } : {
229
+ success: true,
230
+ data: given
231
+ };
281
232
  }
282
-
283
- // src/shuffle.ts
233
+ //#endregion
234
+ //#region src/shuffle.ts
235
+ /**
236
+ * Seeded, deterministic shuffling — the ONE algorithm every presentation-order
237
+ * decision in the SDK goes through: option order in a multiple-choice item,
238
+ * item order inside an item group, entry order in a sequence. A server and a
239
+ * client holding the same seed derive the same order, and an order recorded
240
+ * against an attempt can be rebuilt later from nothing but its seed.
241
+ *
242
+ * STABILITY: the hash and the generator are part of the wire contract. A
243
+ * stored attempt may hold only a seed and rely on this function to reproduce
244
+ * the order it presented; changing either would silently re-order every
245
+ * recorded attempt. Any change here is a package major, and the pinned
246
+ * permutation test exists so an accidental one fails loudly.
247
+ */
248
+ /** FNV-1a hash of a string → unsigned 32-bit integer. */
284
249
  function hashSeed(input) {
285
- let h = 2166136261 >>> 0;
286
- for (let i = 0; i < input.length; i += 1) {
287
- h ^= input.charCodeAt(i);
288
- h = Math.imul(h, 16777619) >>> 0;
289
- }
290
- return h;
250
+ let h = 2166136261;
251
+ for (let i = 0; i < input.length; i += 1) {
252
+ h ^= input.charCodeAt(i);
253
+ h = Math.imul(h, 16777619) >>> 0;
254
+ }
255
+ return h;
291
256
  }
257
+ /** LCG-driven Fisher–Yates over a 32-bit seed; returns a permutation (no loss, no duplicate). */
292
258
  function shuffleWithSeed(items, seed, version) {
293
- const out = [...items];
294
- let s = seed >>> 0 || 1;
295
- for (let i = out.length - 1; i > 0; i -= 1) {
296
- s = Math.imul(s, 1664525) + 1013904223 >>> 0;
297
- const j = version === 2 ? Math.floor(s / 4294967296 * (i + 1)) : s % (i + 1);
298
- [out[i], out[j]] = [out[j], out[i]];
299
- }
300
- return out;
259
+ const out = [...items];
260
+ let s = seed >>> 0 || 1;
261
+ for (let i = out.length - 1; i > 0; i -= 1) {
262
+ s = Math.imul(s, 1664525) + 1013904223 >>> 0;
263
+ const j = version === 2 ? Math.floor(s / 4294967296 * (i + 1)) : s % (i + 1);
264
+ [out[i], out[j]] = [out[j], out[i]];
265
+ }
266
+ return out;
301
267
  }
302
268
  function seededShuffle(items, seed, options = {}) {
303
- return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);
269
+ return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);
304
270
  }
305
-
306
- // src/item-group.ts
271
+ //#endregion
272
+ //#region src/item-group.ts
273
+ /** Narrows a sequence entry to an item group. */
307
274
  function isItemGroup(entry) {
308
- return entry.type === "item-group";
275
+ return entry.type === "item-group";
309
276
  }
277
+ /**
278
+ * An entry's declared `slotKey`, if it has one. Read structurally rather than
279
+ * from the type, because a plain activity may carry one too — `slotKey` is a
280
+ * property of an item's PLACE in a paper, so any entry can declare it without
281
+ * every activity schema having to know about assessment assembly.
282
+ *
283
+ * A key containing `.` is rejected: `.` separates a group from its item in a
284
+ * slot id, so `"a.b"` as a group key would be indistinguishable from item `b`
285
+ * of group `a`.
286
+ */
310
287
  function keyOf(entry) {
311
- const key = entry.slotKey;
312
- if (key === void 0) {
313
- return void 0;
314
- }
315
- if (typeof key !== "string" || key.length === 0) {
316
- throw new Error(
317
- `flattenSequence: slotKey must be a non-empty string, received ${String(key)}.`
318
- );
319
- }
320
- if (key.includes(".")) {
321
- throw new Error(
322
- `flattenSequence: slotKey "${key}" contains a "." , which separates a group from its item in a slot id. Choose a key without it, or the two become indistinguishable.`
323
- );
324
- }
325
- return key;
288
+ const key = entry.slotKey;
289
+ if (key === void 0) return;
290
+ if (typeof key !== "string" || key.length === 0) throw new Error(`flattenSequence: slotKey must be a non-empty string, received ${String(key)}.`);
291
+ if (key.includes(".")) throw new Error(`flattenSequence: slotKey "${key}" contains a "." , which separates a group from its item in a slot id. Choose a key without it, or the two become indistinguishable.`);
292
+ return key;
326
293
  }
294
+ /**
295
+ * An interactive video's items in the order its quizzes open: by the quiz's
296
+ * time — stably, so quizzes at one moment keep their authored order — then by
297
+ * position within the quiz. An item no quiz places (content the schema would
298
+ * refuse) keeps its authored place after every placed one, rather than
299
+ * vanishing from the paper.
300
+ */
327
301
  function inQuizOrder(items, timeline) {
328
- const placement = /* @__PURE__ */ new Map();
329
- timeline.cues.forEach((cue, cueIndex) => {
330
- cue.itemIds.forEach((itemId, position) => {
331
- if (!placement.has(itemId)) {
332
- placement.set(itemId, { at: cue.at, cue: cueIndex, position });
333
- }
334
- });
335
- });
336
- const unplaced = { at: Number.POSITIVE_INFINITY, cue: Number.POSITIVE_INFINITY, position: 0 };
337
- return items.map((entry) => ({ entry, place: placement.get(entry.item.id) ?? unplaced })).sort(
338
- (a, b) => a.place.at - b.place.at || a.place.cue - b.place.cue || a.place.position - b.place.position || a.entry.itemIndex - b.entry.itemIndex
339
- ).map(({ entry }) => entry);
302
+ const placement = /* @__PURE__ */ new Map();
303
+ timeline.cues.forEach((cue, cueIndex) => {
304
+ cue.itemIds.forEach((itemId, position) => {
305
+ if (!placement.has(itemId)) placement.set(itemId, {
306
+ at: cue.at,
307
+ cue: cueIndex,
308
+ position
309
+ });
310
+ });
311
+ });
312
+ const unplaced = {
313
+ at: Number.POSITIVE_INFINITY,
314
+ cue: Number.POSITIVE_INFINITY,
315
+ position: 0
316
+ };
317
+ return items.map((entry) => ({
318
+ entry,
319
+ place: placement.get(entry.item.id) ?? unplaced
320
+ })).sort((a, b) => a.place.at - b.place.at || a.place.cue - b.place.cue || a.place.position - b.place.position || a.entry.itemIndex - b.entry.itemIndex).map(({ entry }) => entry);
340
321
  }
322
+ /**
323
+ * Turns a sequence definition — loose activities and item groups, in authored
324
+ * order — into the ordered list of slots to present. Pure and deterministic:
325
+ * call it on the server to record an attempt's order, and on the client to
326
+ * render it, and the two agree.
327
+ *
328
+ * Shuffling is opt-in and seeded. Groups are shuffle-atomic: with
329
+ * `shuffleEntries` a group changes position but stays one contiguous block,
330
+ * and only a group that declares `shuffle: 'within-group'` has its items
331
+ * reordered. Every slot carries a `slotId` derived from the authored
332
+ * position, so identities survive shuffling.
333
+ *
334
+ * @throws Error when a shuffle is requested without a `seed`.
335
+ */
341
336
  function flattenSequence(entries, options = {}) {
342
- const shuffleEntries = options.shuffleEntries === true;
343
- const needsSeed = shuffleEntries || entries.some((entry) => isItemGroup(entry) && entry.shuffle === "within-group");
344
- if (needsSeed && options.seed === void 0) {
345
- throw new Error(
346
- 'flattenSequence: a seed is required when shuffling (shuffleEntries, or a group with shuffle: "within-group"). Pass the attempt id so the server and the client derive the same order.'
347
- );
348
- }
349
- const seed = options.seed ?? "";
350
- const authored = entries.map((entry, entryIndex) => ({ entry, entryIndex }));
351
- const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`) : authored;
352
- const slots = [];
353
- for (const { entry, entryIndex } of ordered) {
354
- const entryKey = keyOf(entry) ?? String(entryIndex);
355
- if (!isItemGroup(entry)) {
356
- slots.push({ slotId: entryKey, index: slots.length, activity: entry });
357
- continue;
358
- }
359
- if (entry.items.length === 0) {
360
- throw new Error(
361
- `flattenSequence: item group "${entry.id}" has no items. An empty group would silently remove its stimulus and its questions from the presented sequence.`
362
- );
363
- }
364
- const timeline = entry.timeline;
365
- if (timeline !== void 0 && entry.shuffle === "within-group") {
366
- throw new Error(
367
- `flattenSequence: item group "${entry.id}" has a timeline and shuffle: "within-group". An interactive video presents its questions in the order its quizzes open.`
368
- );
369
- }
370
- const items = entry.items.map((item, itemIndex) => ({ item, itemIndex }));
371
- const presented = timeline !== void 0 ? inQuizOrder(items, timeline) : entry.shuffle === "within-group" ? seededShuffle(items, `${seed}:group:${entry.id}`) : items;
372
- const size = presented.length;
373
- presented.forEach(({ item, itemIndex }, position) => {
374
- const cue = timeline?.cues.find((candidate) => candidate.itemIds.includes(item.id));
375
- slots.push({
376
- // Slot ids stay AUTHORED — the item's index or its key — whatever the
377
- // presented order: moving a quiz must never re-map a stored answer.
378
- slotId: `${entryKey}.${keyOf(item) ?? String(itemIndex)}`,
379
- index: slots.length,
380
- activity: item,
381
- group: {
382
- id: entry.id,
383
- ...entry.title !== void 0 ? { title: entry.title } : {},
384
- stimulus: entry.stimulus,
385
- position,
386
- size,
387
- ...timeline !== void 0 ? { timeline } : {},
388
- ...cue !== void 0 ? { cue } : {}
389
- }
390
- });
391
- });
392
- }
393
- const seenSlotIds = /* @__PURE__ */ new Set();
394
- const seenEntryKeys = /* @__PURE__ */ new Set();
395
- for (const slot of slots) {
396
- if (seenSlotIds.has(slot.slotId)) {
397
- throw new Error(
398
- `flattenSequence: duplicate slot id "${slot.slotId}". Two entries declare the same slotKey, so responses stored against them could not be told apart.`
399
- );
400
- }
401
- seenSlotIds.add(slot.slotId);
402
- }
403
- for (const { entry, entryIndex } of ordered) {
404
- const entryKey = keyOf(entry) ?? String(entryIndex);
405
- if (seenEntryKeys.has(entryKey)) {
406
- throw new Error(
407
- `flattenSequence: duplicate entry key "${entryKey}". A loose activity and an item group cannot share a slotKey \u2014 their slot ids would not collide, but everything that reads the entry they belong to would treat them as one entry.`
408
- );
409
- }
410
- seenEntryKeys.add(entryKey);
411
- }
412
- return slots;
337
+ const shuffleEntries = options.shuffleEntries === true;
338
+ if ((shuffleEntries || entries.some((entry) => isItemGroup(entry) && entry.shuffle === "within-group")) && options.seed === void 0) throw new Error("flattenSequence: a seed is required when shuffling (shuffleEntries, or a group with shuffle: \"within-group\"). Pass the attempt id so the server and the client derive the same order.");
339
+ const seed = options.seed ?? "";
340
+ const authored = entries.map((entry, entryIndex) => ({
341
+ entry,
342
+ entryIndex
343
+ }));
344
+ const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`, { version: 1 }) : authored;
345
+ const slots = [];
346
+ for (const { entry, entryIndex } of ordered) {
347
+ const entryKey = keyOf(entry) ?? String(entryIndex);
348
+ if (!isItemGroup(entry)) {
349
+ slots.push({
350
+ slotId: entryKey,
351
+ index: slots.length,
352
+ activity: entry
353
+ });
354
+ continue;
355
+ }
356
+ if (entry.items.length === 0) throw new Error(`flattenSequence: item group "${entry.id}" has no items. An empty group would silently remove its stimulus and its questions from the presented sequence.`);
357
+ const timeline = entry.timeline;
358
+ if (timeline !== void 0 && entry.shuffle === "within-group") throw new Error(`flattenSequence: item group "${entry.id}" has a timeline and shuffle: "within-group". An interactive video presents its questions in the order its quizzes open.`);
359
+ const items = entry.items.map((item, itemIndex) => ({
360
+ item,
361
+ itemIndex
362
+ }));
363
+ const presented = timeline !== void 0 ? inQuizOrder(items, timeline) : entry.shuffle === "within-group" ? seededShuffle(items, `${seed}:group:${entry.id}`, { version: 1 }) : items;
364
+ const size = presented.length;
365
+ presented.forEach(({ item, itemIndex }, position) => {
366
+ const cue = timeline?.cues.find((candidate) => candidate.itemIds.includes(item.id));
367
+ slots.push({
368
+ slotId: `${entryKey}.${keyOf(item) ?? String(itemIndex)}`,
369
+ index: slots.length,
370
+ activity: item,
371
+ group: {
372
+ id: entry.id,
373
+ ...entry.title !== void 0 ? { title: entry.title } : {},
374
+ stimulus: entry.stimulus,
375
+ position,
376
+ size,
377
+ ...timeline !== void 0 ? { timeline } : {},
378
+ ...cue !== void 0 ? { cue } : {}
379
+ }
380
+ });
381
+ });
382
+ }
383
+ const seenSlotIds = /* @__PURE__ */ new Set();
384
+ const seenEntryKeys = /* @__PURE__ */ new Set();
385
+ for (const slot of slots) {
386
+ if (seenSlotIds.has(slot.slotId)) throw new Error(`flattenSequence: duplicate slot id "${slot.slotId}". Two entries declare the same slotKey, so responses stored against them could not be told apart.`);
387
+ seenSlotIds.add(slot.slotId);
388
+ }
389
+ for (const { entry, entryIndex } of ordered) {
390
+ const entryKey = keyOf(entry) ?? String(entryIndex);
391
+ if (seenEntryKeys.has(entryKey)) throw new Error(`flattenSequence: duplicate entry key "${entryKey}". A loose activity and an item group cannot share a slotKey — their slot ids would not collide, but everything that reads the entry they belong to would treat them as one entry.`);
392
+ seenEntryKeys.add(entryKey);
393
+ }
394
+ return slots;
413
395
  }
414
-
415
- // src/media-budget.ts
396
+ //#endregion
397
+ //#region src/media-budget.ts
398
+ /**
399
+ * The authored-entry prefix of a slot id: `"3"` for both `"3"` and `"3.1"`.
400
+ *
401
+ * Safe because every slot id in a plan is produced by `flattenSequence`, and
402
+ * `keyOf` rejects a `.` in both an entry key and an item key — so the first
403
+ * `.` is always the group/item separator.
404
+ */
416
405
  function entryKeyOf(slotId) {
417
- const dot = slotId.indexOf(".");
418
- return dot === -1 ? slotId : slotId.slice(0, dot);
406
+ const dot = slotId.indexOf(".");
407
+ return dot === -1 ? slotId : slotId.slice(0, dot);
419
408
  }
409
+ /** Budget key for an activity's OWN `data.media`. One budget per slot. */
420
410
  function slotMediaKey(slotId) {
421
- return `slot:${slotId}`;
411
+ return `slot:${slotId}`;
422
412
  }
413
+ /**
414
+ * Budget key for an item group's `stimulus.media`.
415
+ *
416
+ * Keyed by the ENTRY, not the slot: one recording serves every question in the
417
+ * group, so `"3.0"`…`"3.5"` share one budget. Keying by `slotId` would hand a
418
+ * six-question `maxPlays: 2` listening group twelve plays; keying by
419
+ * `stimulus.id` would collide across papers, which is the thing slot keys and
420
+ * `planHash` exist to prevent.
421
+ */
423
422
  function stimulusMediaKey(slotId) {
424
- return `stimulus:${entryKeyOf(slotId)}`;
423
+ return `stimulus:${entryKeyOf(slotId)}`;
425
424
  }
425
+ /**
426
+ * Resolves the defaults once, so the schema refinements, the plan and the
427
+ * renderer cannot drift apart about what a policy means.
428
+ *
429
+ * Absent `playback` resolves to exactly the SDK's pre-0.8.0 behaviour:
430
+ * `controls: 'native'`, no budget, free seeking, free speed, no hints.
431
+ */
426
432
  function resolvePlaybackPolicy(media) {
427
- const p = media.playback;
428
- const budgeted = typeof p?.maxPlays === "number";
429
- const seek = p?.seek ?? (budgeted ? "none" : "allow");
430
- const rate = p?.rate ?? "allow";
431
- const controls = p?.controls ?? (budgeted || seek === "none" || rate === "fixed" ? "minimal" : "native");
432
- return {
433
- controls,
434
- maxPlays: budgeted ? p?.maxPlays : null,
435
- seek,
436
- rate,
437
- nativeControlHints: p?.nativeControlHints ?? []
438
- };
433
+ const p = media.playback;
434
+ const budgeted = typeof p?.maxPlays === "number";
435
+ const seek = p?.seek ?? (budgeted ? "none" : "allow");
436
+ const rate = p?.rate ?? "allow";
437
+ return {
438
+ controls: p?.controls ?? (budgeted || seek === "none" || rate === "fixed" ? "minimal" : "native"),
439
+ maxPlays: budgeted ? p?.maxPlays : null,
440
+ seek,
441
+ rate,
442
+ nativeControlHints: p?.nativeControlHints ?? []
443
+ };
439
444
  }
445
+ /**
446
+ * Every budgeted recording a plan contains: budget key → the `maxPlays` that
447
+ * was frozen when the attempt was planned.
448
+ *
449
+ * Use it to build the storage rows an attempt needs, and to check a stored
450
+ * ledger against the paper it claims to belong to.
451
+ */
440
452
  function planMediaBudgets(plan) {
441
- const out = {};
442
- for (const slot of plan.slots) {
443
- for (const budget of slot.mediaBudgets ?? []) {
444
- out[budget.key] = budget.maxPlays;
445
- }
446
- }
447
- return out;
453
+ const out = {};
454
+ for (const slot of plan.slots) for (const budget of slot.mediaBudgets ?? []) out[budget.key] = budget.maxPlays;
455
+ return out;
448
456
  }
449
457
  function assertEntry(key, entry) {
450
- if (entry === null || typeof entry !== "object" || !Number.isInteger(entry.plays) || entry.plays < 0) {
451
- throw new Error(
452
- `serializeMediaPlayLedger: play count for ${JSON.stringify(key)} is ${JSON.stringify(entry?.plays)}. A count must be a non-negative integer; Number(a NULL column) is the usual cause.`
453
- );
454
- }
455
- if (entry.at !== void 0 && (!Number.isFinite(entry.at) || entry.at < 0)) {
456
- throw new Error(
457
- `serializeMediaPlayLedger: position for ${JSON.stringify(key)} is ${JSON.stringify(entry.at)}. A position must be a finite number of seconds >= 0.`
458
- );
459
- }
458
+ if (entry === null || typeof entry !== "object" || !Number.isInteger(entry.plays) || entry.plays < 0) throw new Error(`serializeMediaPlayLedger: play count for ${JSON.stringify(key)} is ${JSON.stringify(entry?.plays)}. A count must be a non-negative integer; Number(a NULL column) is the usual cause.`);
459
+ if (entry.at !== void 0 && (!Number.isFinite(entry.at) || entry.at < 0)) throw new Error(`serializeMediaPlayLedger: position for ${JSON.stringify(key)} is ${JSON.stringify(entry.at)}. A position must be a finite number of seconds >= 0.`);
460
460
  }
461
+ /**
462
+ * Validates a set of spent-play counts against the plan that budgeted them,
463
+ * and stamps the envelope.
464
+ *
465
+ * Validates on the way **in**: a play recorded against a recording the paper
466
+ * does not budget is a bug at the moment it is written, and discovering it
467
+ * when a learner tries to resume is discovering it far too late.
468
+ *
469
+ * @throws Error when a key is not budgeted by the plan, or a count is not a
470
+ * non-negative integer, or a position is not a finite number.
471
+ */
461
472
  function serializeMediaPlayLedger(plan, entries, options = {}) {
462
- if (entries === null || typeof entries !== "object") {
463
- throw new Error("serializeMediaPlayLedger: entries must be an object keyed by media key.");
464
- }
465
- const budgets = planMediaBudgets(plan);
466
- const out = {};
467
- for (const key of Object.keys(entries)) {
468
- if (!Object.hasOwn(budgets, key)) {
469
- throw new Error(
470
- `serializeMediaPlayLedger: media play recorded against a recording the plan does not budget: ${JSON.stringify(key)}. Keys come from slotMediaKey() / stimulusMediaKey(); a key that belongs to no budgeted media means the client and the plan disagree about which paper this is.`
471
- );
472
- }
473
- const entry = entries[key];
474
- assertEntry(key, entry);
475
- out[key] = { plays: entry.plays, ...entry.at !== void 0 ? { at: entry.at } : {} };
476
- }
477
- return {
478
- ledgerVersion: "1.0",
479
- planHash: plan.planHash,
480
- entries: out,
481
- ...options.savedAt !== void 0 ? { savedAt: options.savedAt } : {}
482
- };
473
+ if (entries === null || typeof entries !== "object") throw new Error("serializeMediaPlayLedger: entries must be an object keyed by media key.");
474
+ const budgets = planMediaBudgets(plan);
475
+ const out = {};
476
+ for (const key of Object.keys(entries)) {
477
+ if (!Object.hasOwn(budgets, key)) throw new Error(`serializeMediaPlayLedger: media play recorded against a recording the plan does not budget: ${JSON.stringify(key)}. Keys come from slotMediaKey() / stimulusMediaKey(); a key that belongs to no budgeted media means the client and the plan disagree about which paper this is.`);
478
+ const entry = entries[key];
479
+ assertEntry(key, entry);
480
+ out[key] = {
481
+ plays: entry.plays,
482
+ ...entry.at !== void 0 ? { at: entry.at } : {}
483
+ };
484
+ }
485
+ return {
486
+ ledgerVersion: "1.0",
487
+ planHash: plan.planHash,
488
+ entries: out,
489
+ ...options.savedAt !== void 0 ? { savedAt: options.savedAt } : {}
490
+ };
483
491
  }
492
+ /**
493
+ * Reopens a stored ledger against the paper it was spent on.
494
+ *
495
+ * Refuses a ledger from a different paper for the same reason
496
+ * `restoreAttemptState` does: budget keys are short and repeat across papers
497
+ * (`slot:0`, `stimulus:1`), so a ledger from last term's midterm would hold a
498
+ * learner to a budget from an exam they never sat, and look entirely plausible
499
+ * doing it.
500
+ *
501
+ * @throws Error on an unrecognised `ledgerVersion`, a `planHash` mismatch, or
502
+ * anything `serializeMediaPlayLedger` refuses.
503
+ */
484
504
  function restoreMediaPlayLedger(plan, stored) {
485
- if (stored === null || typeof stored !== "object") {
486
- throw new Error("restoreMediaPlayLedger: the stored ledger is not an object.");
487
- }
488
- if (stored.ledgerVersion !== "1.0") {
489
- throw new Error(
490
- `restoreMediaPlayLedger: unsupported ledgerVersion ${JSON.stringify(stored.ledgerVersion)}. This build understands "1.0"; a newer ledger must be migrated before it is restored.`
491
- );
492
- }
493
- if (stored.entries === null || typeof stored.entries !== "object") {
494
- throw new Error(
495
- "restoreMediaPlayLedger: the ledger carries no entries object (a NULL column, or a partially written row)."
496
- );
497
- }
498
- if (stored.planHash !== plan.planHash) {
499
- throw new Error(
500
- `restoreMediaPlayLedger: this ledger belongs to a different paper (ledger ${stored.planHash}, plan ${plan.planHash}). Restoring it would hold the learner to a play budget from an exam they never sat.`
501
- );
502
- }
503
- return serializeMediaPlayLedger(plan, stored.entries, {
504
- ...stored.savedAt !== void 0 ? { savedAt: stored.savedAt } : {}
505
- });
505
+ if (stored === null || typeof stored !== "object") throw new Error("restoreMediaPlayLedger: the stored ledger is not an object.");
506
+ if (stored.ledgerVersion !== "1.0") throw new Error(`restoreMediaPlayLedger: unsupported ledgerVersion ${JSON.stringify(stored.ledgerVersion)}. This build understands "1.0"; a newer ledger must be migrated before it is restored.`);
507
+ if (stored.entries === null || typeof stored.entries !== "object") throw new Error("restoreMediaPlayLedger: the ledger carries no entries object (a NULL column, or a partially written row).");
508
+ if (stored.planHash !== plan.planHash) throw new Error(`restoreMediaPlayLedger: this ledger belongs to a different paper (ledger ${stored.planHash}, plan ${plan.planHash}). Restoring it would hold the learner to a play budget from an exam they never sat.`);
509
+ return serializeMediaPlayLedger(plan, stored.entries, { ...stored.savedAt !== void 0 ? { savedAt: stored.savedAt } : {} });
506
510
  }
507
-
508
- // src/attempt-plan.ts
511
+ //#endregion
512
+ //#region src/attempt-plan.ts
513
+ /**
514
+ * The activity as CONTENT, with its slot key removed.
515
+ *
516
+ * `slotKey` rides on the same object but is identity, not content — the whole
517
+ * point of the design. Including it in the fingerprint meant that annotating
518
+ * an existing entry with the key that pins its identity reported as
519
+ * "this question was edited", which is precisely backwards.
520
+ */
509
521
  function contentOf(activity) {
510
- if (!Object.hasOwn(activity, "slotKey")) {
511
- return activity;
512
- }
513
- const { slotKey: _slotKey, ...content } = activity;
514
- return content;
522
+ if (!Object.hasOwn(activity, "slotKey")) return activity;
523
+ const { slotKey: _slotKey, ...content } = activity;
524
+ return content;
515
525
  }
526
+ /**
527
+ * The budgeted recordings a slot presents: its own media, and its group's
528
+ * stimulus. Returns `undefined` — not `[]` — when nothing is budgeted, so the
529
+ * conditional spread below leaves the serialized slot byte-identical to what
530
+ * every pre-0.8.0 paper produced.
531
+ */
516
532
  function mediaBudgetsOf(slot) {
517
- const budgets = [];
518
- const own = slot.activity.media;
519
- if (own !== void 0) {
520
- const maxPlays = resolvePlaybackPolicy(own).maxPlays;
521
- if (maxPlays !== null) {
522
- budgets.push({ key: slotMediaKey(slot.slotId), maxPlays });
523
- }
524
- }
525
- const stimulusMedia = slot.group?.stimulus.media;
526
- if (stimulusMedia !== void 0) {
527
- const maxPlays = resolvePlaybackPolicy(stimulusMedia).maxPlays;
528
- if (maxPlays !== null) {
529
- budgets.push({ key: stimulusMediaKey(slot.slotId), maxPlays });
530
- }
531
- }
532
- return budgets.length > 0 ? budgets : void 0;
533
+ const budgets = [];
534
+ const own = slot.activity.media;
535
+ if (own !== void 0) {
536
+ const maxPlays = resolvePlaybackPolicy(own).maxPlays;
537
+ if (maxPlays !== null) budgets.push({
538
+ key: slotMediaKey(slot.slotId),
539
+ maxPlays
540
+ });
541
+ }
542
+ const stimulusMedia = slot.group?.stimulus.media;
543
+ if (stimulusMedia !== void 0) {
544
+ const maxPlays = resolvePlaybackPolicy(stimulusMedia).maxPlays;
545
+ if (maxPlays !== null) budgets.push({
546
+ key: stimulusMediaKey(slot.slotId),
547
+ maxPlays
548
+ });
549
+ }
550
+ return budgets.length > 0 ? budgets : void 0;
533
551
  }
552
+ /**
553
+ * Refuses a paper in which one recording is budgeted under several keys.
554
+ *
555
+ * Six questions that each carry the same `/audio/part2.mp3` with `maxPlays: 2`
556
+ * are six budgets, so the learner gets twelve plays of one recording while the
557
+ * paper says two. The fix is authoring, not arithmetic: questions that share a
558
+ * recording belong in an item group, whose stimulus is one recording with one
559
+ * budget.
560
+ */
534
561
  function assertNoSplitBudgets(slots) {
535
- const keysByUrl = /* @__PURE__ */ new Map();
536
- for (const slot of slots) {
537
- const own = slot.activity.media;
538
- if (own === void 0 || resolvePlaybackPolicy(own).maxPlays === null) {
539
- continue;
540
- }
541
- const keys = keysByUrl.get(own.url) ?? [];
542
- keys.push(slotMediaKey(slot.slotId));
543
- keysByUrl.set(own.url, keys);
544
- }
545
- for (const [url, keys] of keysByUrl) {
546
- if (keys.length > 1) {
547
- throw new Error(
548
- `planAttempt: media ${JSON.stringify(url)} is budgeted under ${keys.length} separate keys (${keys.join(", ")}), so one recording grants ${keys.length} \xD7 maxPlays. Put the questions that share a recording in an item group \u2014 a group's stimulus is one recording with one budget.`
549
- );
550
- }
551
- }
562
+ const keysByUrl = /* @__PURE__ */ new Map();
563
+ for (const slot of slots) {
564
+ const own = slot.activity.media;
565
+ if (own === void 0 || resolvePlaybackPolicy(own).maxPlays === null) continue;
566
+ const keys = keysByUrl.get(own.url) ?? [];
567
+ keys.push(slotMediaKey(slot.slotId));
568
+ keysByUrl.set(own.url, keys);
569
+ }
570
+ for (const [url, keys] of keysByUrl) if (keys.length > 1) throw new Error(`planAttempt: media ${JSON.stringify(url)} is budgeted under ${keys.length} separate keys (${keys.join(", ")}), so one recording grants ${keys.length} × maxPlays. Put the questions that share a recording in an item group — a group's stimulus is one recording with one budget.`);
552
571
  }
553
572
  function planSlot(slot, points) {
554
- if (!Number.isFinite(points) || points < 0) {
555
- throw new Error(
556
- `planAttempt: slot "${slot.slotId}" resolved to ${String(points)} points. Points must be a finite, non-negative number, or the paper has no defensible total.`
557
- );
558
- }
559
- const mediaBudgets = mediaBudgetsOf(slot);
560
- return {
561
- slotId: slot.slotId,
562
- index: slot.index,
563
- activityId: slot.activity.id,
564
- activityType: slot.activity.type,
565
- points,
566
- contentHash: contentHash(contentOf(slot.activity)),
567
- ...slot.group !== void 0 ? {
568
- group: {
569
- id: slot.group.id,
570
- ...slot.group.title !== void 0 ? { title: slot.group.title } : {},
571
- stimulusHash: contentHash(slot.group.stimulus),
572
- ...slot.group.cue !== void 0 ? {
573
- cue: {
574
- id: slot.group.cue.id,
575
- at: slot.group.cue.at,
576
- ...slot.group.cue.required !== void 0 ? { required: slot.group.cue.required } : {}
577
- }
578
- } : {}
579
- }
580
- } : {},
581
- ...mediaBudgets !== void 0 ? { mediaBudgets } : {}
582
- };
573
+ if (!Number.isFinite(points) || points < 0) throw new Error(`planAttempt: slot "${slot.slotId}" resolved to ${String(points)} points. Points must be a finite, non-negative number, or the paper has no defensible total.`);
574
+ const mediaBudgets = mediaBudgetsOf(slot);
575
+ return {
576
+ slotId: slot.slotId,
577
+ index: slot.index,
578
+ activityId: slot.activity.id,
579
+ activityType: slot.activity.type,
580
+ points,
581
+ contentHash: contentHash(contentOf(slot.activity)),
582
+ ...slot.group !== void 0 ? { group: {
583
+ id: slot.group.id,
584
+ ...slot.group.title !== void 0 ? { title: slot.group.title } : {},
585
+ stimulusHash: contentHash(slot.group.stimulus),
586
+ ...slot.group.cue !== void 0 ? { cue: {
587
+ id: slot.group.cue.id,
588
+ at: slot.group.cue.at,
589
+ ...slot.group.cue.required !== void 0 ? { required: slot.group.cue.required } : {}
590
+ } } : {}
591
+ } } : {},
592
+ ...mediaBudgets !== void 0 ? { mediaBudgets } : {}
593
+ };
583
594
  }
595
+ /**
596
+ * Freezes what an attempt is being served: the presented order, each slot's
597
+ * identity and worth, and a fingerprint of the content behind it.
598
+ *
599
+ * Call this once, when the attempt starts, and store the result beside the
600
+ * responses. Everything that decides the grade is then a historical fact
601
+ * rather than a re-read of content that may since have changed — which is what
602
+ * makes a re-grade, a remark or an appeal answerable.
603
+ *
604
+ * Ordering comes from `flattenSequence`, so a plan and a live render of the
605
+ * same entries with the same seed agree slot for slot.
606
+ *
607
+ * @throws Error when a shuffle is requested without a seed, when a group is
608
+ * empty, when two entries collide on a `slotKey`, or when `points`
609
+ * returns a value that is not finite and non-negative.
610
+ */
584
611
  function planAttempt(entries, options = {}) {
585
- const { seed, shuffleEntries, points } = options;
586
- const delivery = frozenDelivery(options.delivery);
587
- const scoring = frozenScoring(options.scoring);
588
- const slots = flattenSequence(entries, {
589
- ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
590
- ...seed !== void 0 ? { seed } : {}
591
- });
592
- assertNoSplitBudgets(slots);
593
- const planned = slots.map((slot) => planSlot(slot, points?.(slot) ?? 1));
594
- const totalPoints = planned.reduce((sum, slot) => sum + slot.points, 0);
595
- return {
596
- planVersion: "1.0",
597
- ...seed !== void 0 ? { seed } : {},
598
- ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
599
- // The plan's own fingerprint covers the slots verbatim — identity, order,
600
- // points and content hashes — so one stored value answers "is this still
601
- // the paper that was sat?" and the per-slot hashes then say what moved.
602
- // A policy joins it when there is one: the same paper sat with hints and
603
- // without is two different attempts. Without one, the fingerprint is the
604
- // one every plan before policies had.
605
- // So does a scoring policy: the same answers are worth something else when
606
- // a hint costs a tenth of the marks. Each joins only when it is there, so
607
- // a plan with neither — or with a delivery policy alone — keeps the
608
- // fingerprint it always had.
609
- planHash: contentHash(
610
- delivery === void 0 && scoring === void 0 ? planned : {
611
- slots: planned,
612
- ...delivery !== void 0 ? { delivery } : {},
613
- ...scoring !== void 0 ? { scoring } : {}
614
- }
615
- ),
616
- ...delivery !== void 0 ? { delivery } : {},
617
- ...scoring !== void 0 ? { scoring } : {},
618
- slots: planned,
619
- totalPoints
620
- };
612
+ const { seed, shuffleEntries, points } = options;
613
+ const delivery = frozenDelivery(options.delivery);
614
+ const scoring = frozenScoring(options.scoring);
615
+ const slots = flattenSequence(entries, {
616
+ ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
617
+ ...seed !== void 0 ? { seed } : {}
618
+ });
619
+ assertNoSplitBudgets(slots);
620
+ const planned = slots.map((slot) => planSlot(slot, points?.(slot) ?? 1));
621
+ const totalPoints = planned.reduce((sum, slot) => sum + slot.points, 0);
622
+ return {
623
+ planVersion: "1.0",
624
+ ...seed !== void 0 ? { seed } : {},
625
+ ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
626
+ planHash: contentHash(delivery === void 0 && scoring === void 0 ? planned : {
627
+ slots: planned,
628
+ ...delivery !== void 0 ? { delivery } : {},
629
+ ...scoring !== void 0 ? { scoring } : {}
630
+ }),
631
+ ...delivery !== void 0 ? { delivery } : {},
632
+ ...scoring !== void 0 ? { scoring } : {},
633
+ slots: planned,
634
+ totalPoints
635
+ };
621
636
  }
637
+ /**
638
+ * Compares a stored plan with the content as it stands now, and reports every
639
+ * way they have drifted apart.
640
+ *
641
+ * This is the question a remark or an appeal actually asks: *is the paper I am
642
+ * looking at the paper this learner sat?* Ids alone cannot answer it, because
643
+ * they survive an edit unchanged.
644
+ *
645
+ * Rebuild the comparison plan with the SAME options the stored one recorded —
646
+ * its `seed`, its `shuffleEntries`, and the same `points` function — or the
647
+ * differences you see will be your own:
648
+ *
649
+ * ```ts
650
+ * const now = planAttempt(currentEntries, {
651
+ * seed: stored.seed,
652
+ * shuffleEntries: stored.shuffleEntries,
653
+ * points: pointsFor, // omit it and every slot reweights to 1
654
+ * });
655
+ * const drift = verifyAttemptPlan(stored, now);
656
+ * ```
657
+ *
658
+ * A drift is not automatically a problem — a fixed typo changes a hash without
659
+ * changing what was asked. It is a fact somebody has to be able to see.
660
+ */
622
661
  function verifyAttemptPlan(plan, current) {
623
- const before = new Map(plan.slots.map((slot) => [slot.slotId, slot]));
624
- const after = new Map(current.slots.map((slot) => [slot.slotId, slot]));
625
- const missingSlotIds = plan.slots.filter((s) => !after.has(s.slotId)).map((s) => s.slotId);
626
- const addedSlotIds = current.slots.filter((s) => !before.has(s.slotId)).map((s) => s.slotId);
627
- const changedSlotIds = [];
628
- const changedStimulusSlotIds = [];
629
- const changedCueSlotIds = [];
630
- const changedPointsSlotIds = [];
631
- const reorderedSlotIds = [];
632
- const deliveryChanged = contentHash(plan.delivery ?? null) !== contentHash(current.delivery ?? null);
633
- const scoringChanged = contentHash(plan.scoring ?? null) !== contentHash(current.scoring ?? null);
634
- for (const slot of plan.slots) {
635
- const now = after.get(slot.slotId);
636
- if (now === void 0) {
637
- continue;
638
- }
639
- if (now.contentHash !== slot.contentHash) {
640
- changedSlotIds.push(slot.slotId);
641
- }
642
- if (now.group?.stimulusHash !== slot.group?.stimulusHash) {
643
- changedStimulusSlotIds.push(slot.slotId);
644
- }
645
- if (contentHash(now.group?.cue ?? null) !== contentHash(slot.group?.cue ?? null)) {
646
- changedCueSlotIds.push(slot.slotId);
647
- }
648
- if (now.points !== slot.points) {
649
- changedPointsSlotIds.push(slot.slotId);
650
- }
651
- if (now.index !== slot.index) {
652
- reorderedSlotIds.push(slot.slotId);
653
- }
654
- }
655
- return {
656
- matches: missingSlotIds.length === 0 && addedSlotIds.length === 0 && changedSlotIds.length === 0 && changedStimulusSlotIds.length === 0 && changedCueSlotIds.length === 0 && changedPointsSlotIds.length === 0 && reorderedSlotIds.length === 0 && !deliveryChanged && !scoringChanged,
657
- missingSlotIds,
658
- addedSlotIds,
659
- changedSlotIds,
660
- changedStimulusSlotIds,
661
- changedCueSlotIds,
662
- changedPointsSlotIds,
663
- reorderedSlotIds,
664
- // Present only when it is true, as `rejectedSlotIds` is on a composed
665
- // score: a drift report between two plans without a policy — every one
666
- // written before policies existed — keeps exactly the shape it had.
667
- ...deliveryChanged ? { deliveryChanged: true } : {},
668
- ...scoringChanged ? { scoringChanged: true } : {}
669
- };
662
+ const before = new Map(plan.slots.map((slot) => [slot.slotId, slot]));
663
+ const after = new Map(current.slots.map((slot) => [slot.slotId, slot]));
664
+ const missingSlotIds = plan.slots.filter((s) => !after.has(s.slotId)).map((s) => s.slotId);
665
+ const addedSlotIds = current.slots.filter((s) => !before.has(s.slotId)).map((s) => s.slotId);
666
+ const changedSlotIds = [];
667
+ const changedStimulusSlotIds = [];
668
+ const changedCueSlotIds = [];
669
+ const changedPointsSlotIds = [];
670
+ const reorderedSlotIds = [];
671
+ const deliveryChanged = contentHash(plan.delivery ?? null) !== contentHash(current.delivery ?? null);
672
+ const scoringChanged = contentHash(plan.scoring ?? null) !== contentHash(current.scoring ?? null);
673
+ for (const slot of plan.slots) {
674
+ const now = after.get(slot.slotId);
675
+ if (now === void 0) continue;
676
+ if (now.contentHash !== slot.contentHash) changedSlotIds.push(slot.slotId);
677
+ if (now.group?.stimulusHash !== slot.group?.stimulusHash) changedStimulusSlotIds.push(slot.slotId);
678
+ if (contentHash(now.group?.cue ?? null) !== contentHash(slot.group?.cue ?? null)) changedCueSlotIds.push(slot.slotId);
679
+ if (now.points !== slot.points) changedPointsSlotIds.push(slot.slotId);
680
+ if (now.index !== slot.index) reorderedSlotIds.push(slot.slotId);
681
+ }
682
+ return {
683
+ matches: missingSlotIds.length === 0 && addedSlotIds.length === 0 && changedSlotIds.length === 0 && changedStimulusSlotIds.length === 0 && changedCueSlotIds.length === 0 && changedPointsSlotIds.length === 0 && reorderedSlotIds.length === 0 && !deliveryChanged && !scoringChanged,
684
+ missingSlotIds,
685
+ addedSlotIds,
686
+ changedSlotIds,
687
+ changedStimulusSlotIds,
688
+ changedCueSlotIds,
689
+ changedPointsSlotIds,
690
+ reorderedSlotIds,
691
+ ...deliveryChanged ? { deliveryChanged: true } : {},
692
+ ...scoringChanged ? { scoringChanged: true } : {}
693
+ };
670
694
  }
695
+ /**
696
+ * The policy a plan records: checked, then spelled out. `undefined` when there
697
+ * is none, so the plan carries no field at all rather than an empty one.
698
+ */
671
699
  function frozenDelivery(policy) {
672
- if (policy === void 0 || policy === null) {
673
- return void 0;
674
- }
675
- const checked = validateDeliveryPolicy(policy);
676
- if (!checked.success) {
677
- const first = checked.issues[0];
678
- throw new Error(
679
- `planAttempt: the delivery policy is not one to record \u2014 ${first?.message ?? "invalid"}` + (checked.issues.length > 1 ? ` (and ${checked.issues.length - 1} more)` : "")
680
- );
681
- }
682
- return resolveDeliveryPolicy(checked.data);
700
+ if (policy === void 0 || policy === null) return;
701
+ const checked = validateDeliveryPolicy(policy);
702
+ if (!checked.success) {
703
+ const first = checked.issues[0];
704
+ throw new Error(`planAttempt: the delivery policy is not one to record — ${first?.message ?? "invalid"}` + (checked.issues.length > 1 ? ` (and ${checked.issues.length - 1} more)` : ""));
705
+ }
706
+ return resolveDeliveryPolicy(checked.data);
683
707
  }
708
+ /** The scoring policy a plan records, as {@link frozenDelivery} records a delivery policy. */
684
709
  function frozenScoring(policy) {
685
- if (policy === void 0 || policy === null) {
686
- return void 0;
687
- }
688
- const checked = validateItemScoringPolicy(policy);
689
- if (!checked.success) {
690
- const first = checked.issues[0];
691
- throw new Error(
692
- `planAttempt: the scoring policy is not one to record \u2014 ${first?.message ?? "invalid"}` + (checked.issues.length > 1 ? ` (and ${checked.issues.length - 1} more)` : "")
693
- );
694
- }
695
- return resolveItemScoringPolicy(checked.data);
710
+ if (policy === void 0 || policy === null) return;
711
+ const checked = validateItemScoringPolicy(policy);
712
+ if (!checked.success) {
713
+ const first = checked.issues[0];
714
+ throw new Error(`planAttempt: the scoring policy is not one to record — ${first?.message ?? "invalid"}` + (checked.issues.length > 1 ? ` (and ${checked.issues.length - 1} more)` : ""));
715
+ }
716
+ return resolveItemScoringPolicy(checked.data);
696
717
  }
697
718
  function missingOutcome(slot, policy) {
698
- if (typeof policy === "function") {
699
- return policy(slot);
700
- }
701
- if (policy === "zero") {
702
- return { status: "scored", score: 0, maxScore: 1, passed: false, feedback: null, details: [] };
703
- }
704
- return { status: "deferred", reason: "no_response_recorded", maxScore: 1 };
719
+ if (typeof policy === "function") return policy(slot);
720
+ if (policy === "zero") return {
721
+ status: "scored",
722
+ score: 0,
723
+ maxScore: 1,
724
+ passed: false,
725
+ feedback: null,
726
+ details: []
727
+ };
728
+ return {
729
+ status: "deferred",
730
+ reason: "no_response_recorded",
731
+ maxScore: 1
732
+ };
705
733
  }
734
+ /**
735
+ * Turns a plan plus whatever outcomes exist into the `ScoredItem[]`
736
+ * `composeAssessmentScore` consumes.
737
+ *
738
+ * The plan is the source of the denominator, not the outcomes. A slot the
739
+ * learner never reached still has to appear — otherwise it silently leaves the
740
+ * denominator and the remaining questions quietly become worth more than the
741
+ * paper says.
742
+ *
743
+ * **A missing outcome defaults to `deferred`, never `unscorable`.** The
744
+ * distinction decides a grade: `unscorable` means "a grade is never coming",
745
+ * so `composeAssessmentScore` drops the slot from the denominator AND lets the
746
+ * result go `final` — which turned a three-question paper with one answer into
747
+ * a final, passing 100%. `deferred` means "not yet", which holds the result
748
+ * `provisional` so nothing can be recorded. Pass `'zero'` once you know the
749
+ * attempt was submitted and the blanks are genuinely blanks.
750
+ *
751
+ * Pass outcomes keyed by `slotId`. Keys the plan does not know are ignored:
752
+ * a plan is the authority on what the attempt contained.
753
+ */
706
754
  function scoredItemsFromPlan(plan, outcomes, options = {}) {
707
- const policy = options.missing ?? "deferred";
708
- return plan.slots.map((slot) => ({
709
- slotId: slot.slotId,
710
- activityId: slot.activityId,
711
- points: slot.points,
712
- // `Object.hasOwn`, not a bare lookup: slot ids come from authored
713
- // `slotKey`s, and a key of `constructor` or `toString` would otherwise
714
- // resolve through the prototype chain and hand a FUNCTION to the scorer
715
- // in place of an outcome.
716
- outcome: Object.hasOwn(outcomes, slot.slotId) ? outcomes[slot.slotId] : missingOutcome(slot, policy)
717
- }));
755
+ const policy = options.missing ?? "deferred";
756
+ return plan.slots.map((slot) => ({
757
+ slotId: slot.slotId,
758
+ activityId: slot.activityId,
759
+ points: slot.points,
760
+ outcome: Object.hasOwn(outcomes, slot.slotId) ? outcomes[slot.slotId] : missingOutcome(slot, policy)
761
+ }));
718
762
  }
719
-
720
- // src/attempt-state.ts
763
+ //#endregion
764
+ //#region src/attempt-state.ts
765
+ /**
766
+ * A DEEP copy of the responses.
767
+ *
768
+ * A one-level spread is not enough: every `LearnerResponse` shape is itself an
769
+ * object (`selectedOptionIds`, `answers`, `text`), so a spread hands back a new
770
+ * map of the caller's SAME response objects. A consumer whose reducer updates
771
+ * an answer in place — an Immer draft, a push onto a multi-select, or
772
+ * `answers[blankId] = text`, which is the natural update for that shape — then
773
+ * mutates every snapshot ever taken. The stored snapshot retroactively becomes
774
+ * the new answer, `diffResponses` sees no change, and a delta autosave writes
775
+ * nothing for an edit the learner really made.
776
+ */
721
777
  function cloneResponses(responses) {
722
- return typeof structuredClone === "function" ? structuredClone(responses) : JSON.parse(JSON.stringify(responses));
778
+ return typeof structuredClone === "function" ? structuredClone(responses) : JSON.parse(JSON.stringify(responses));
723
779
  }
780
+ /** Slot ids present in the object but unknown to the plan. */
724
781
  function unknownKeys(plan, keys) {
725
- const known = new Set(plan.slots.map((slot) => slot.slotId));
726
- return keys.filter((key) => !known.has(key));
782
+ const known = new Set(plan.slots.map((slot) => slot.slotId));
783
+ return keys.filter((key) => !known.has(key));
727
784
  }
785
+ /**
786
+ * Captures an in-progress attempt as a storable snapshot, bound to its plan.
787
+ *
788
+ * Validated against the plan on the way in, not on the way out: a response
789
+ * stored under a slot the paper does not contain is a bug at the moment it is
790
+ * written, and finding it months later — when a learner tries to resume — is
791
+ * finding it far too late.
792
+ *
793
+ * The SDK reads no clock: pass `savedAt` if you want the snapshot stamped, so
794
+ * the function stays pure and its output stays reproducible in a test.
795
+ *
796
+ * @throws Error when a response or submitted slot is not in the plan, or when
797
+ * `index` is not a position the plan actually has.
798
+ */
728
799
  function serializeAttemptState(plan, progress) {
729
- const responseKeys = Object.keys(progress.responses);
730
- const submittedSlotIds = [...progress.submittedSlotIds ?? []];
731
- const strayResponses = unknownKeys(plan, responseKeys);
732
- if (strayResponses.length > 0) {
733
- throw new Error(
734
- `serializeAttemptState: response recorded for slot(s) the plan does not contain: ${strayResponses.join(", ")}. A response that belongs to no question cannot be scored and would be lost silently.`
735
- );
736
- }
737
- const straySubmitted = unknownKeys(plan, submittedSlotIds);
738
- if (straySubmitted.length > 0) {
739
- throw new Error(
740
- `serializeAttemptState: submitted slot(s) the plan does not contain: ${straySubmitted.join(", ")}.`
741
- );
742
- }
743
- const index = progress.index ?? 0;
744
- const lastIndex = Math.max(0, plan.slots.length - 1);
745
- if (!Number.isInteger(index) || index < 0 || index > lastIndex) {
746
- throw new Error(
747
- `serializeAttemptState: index ${String(index)} is not a position in a ${plan.slots.length}-slot plan.`
748
- );
749
- }
750
- return {
751
- stateVersion: "1.0",
752
- planHash: plan.planHash,
753
- // Copied DEEPLY, not aliased: a snapshot that keeps mutating with the
754
- // live attempt is not a snapshot. See cloneResponses.
755
- responses: cloneResponses(progress.responses),
756
- submittedSlotIds,
757
- index,
758
- ...progress.savedAt !== void 0 ? { savedAt: progress.savedAt } : {}
759
- };
800
+ const responseKeys = Object.keys(progress.responses);
801
+ const submittedSlotIds = [...progress.submittedSlotIds ?? []];
802
+ const strayResponses = unknownKeys(plan, responseKeys);
803
+ if (strayResponses.length > 0) throw new Error(`serializeAttemptState: response recorded for slot(s) the plan does not contain: ${strayResponses.join(", ")}. A response that belongs to no question cannot be scored and would be lost silently.`);
804
+ const straySubmitted = unknownKeys(plan, submittedSlotIds);
805
+ if (straySubmitted.length > 0) throw new Error(`serializeAttemptState: submitted slot(s) the plan does not contain: ${straySubmitted.join(", ")}.`);
806
+ const index = progress.index ?? 0;
807
+ const lastIndex = Math.max(0, plan.slots.length - 1);
808
+ if (!Number.isInteger(index) || index < 0 || index > lastIndex) throw new Error(`serializeAttemptState: index ${String(index)} is not a position in a ${plan.slots.length}-slot plan.`);
809
+ return {
810
+ stateVersion: "1.0",
811
+ planHash: plan.planHash,
812
+ responses: cloneResponses(progress.responses),
813
+ submittedSlotIds,
814
+ index,
815
+ ...progress.savedAt !== void 0 ? { savedAt: progress.savedAt } : {}
816
+ };
760
817
  }
818
+ /**
819
+ * Reopens a stored snapshot against a plan, refusing anything that does not
820
+ * belong to it.
821
+ *
822
+ * The `planHash` check is the point. Slot ids are short and stable by design,
823
+ * so a snapshot from a DIFFERENT paper — last term's midterm, a sibling
824
+ * version, a copy-pasted attempt row — will happily line its answers up
825
+ * against the wrong questions and look entirely plausible doing it. Comparing
826
+ * the paper's fingerprint is what makes that impossible rather than unlikely.
827
+ *
828
+ * @throws Error when the snapshot belongs to a different plan, or references
829
+ * slots the plan does not contain.
830
+ */
761
831
  function restoreAttemptState(plan, state) {
762
- if (state === null || typeof state !== "object") {
763
- throw new Error("restoreAttemptState: the snapshot is not an object.");
764
- }
765
- if (state.stateVersion !== "1.0") {
766
- throw new Error(
767
- `restoreAttemptState: unsupported stateVersion ${JSON.stringify(state.stateVersion)}. This build understands "1.0"; a newer snapshot must be migrated before it is restored.`
768
- );
769
- }
770
- if (state.responses === null || typeof state.responses !== "object") {
771
- throw new Error(
772
- "restoreAttemptState: the snapshot carries no responses object (a NULL column, or a partially written row)."
773
- );
774
- }
775
- if (state.planHash !== plan.planHash) {
776
- throw new Error(
777
- `restoreAttemptState: this snapshot belongs to a different paper (snapshot ${state.planHash}, plan ${plan.planHash}). Restoring it would attach the learner's answers to questions they never saw.`
778
- );
779
- }
780
- return serializeAttemptState(plan, {
781
- responses: state.responses,
782
- submittedSlotIds: state.submittedSlotIds,
783
- index: state.index,
784
- ...state.savedAt !== void 0 ? { savedAt: state.savedAt } : {}
785
- });
832
+ if (state === null || typeof state !== "object") throw new Error("restoreAttemptState: the snapshot is not an object.");
833
+ if (state.stateVersion !== "1.0") throw new Error(`restoreAttemptState: unsupported stateVersion ${JSON.stringify(state.stateVersion)}. This build understands "1.0"; a newer snapshot must be migrated before it is restored.`);
834
+ if (state.responses === null || typeof state.responses !== "object") throw new Error("restoreAttemptState: the snapshot carries no responses object (a NULL column, or a partially written row).");
835
+ if (state.planHash !== plan.planHash) throw new Error(`restoreAttemptState: this snapshot belongs to a different paper (snapshot ${state.planHash}, plan ${plan.planHash}). Restoring it would attach the learner's answers to questions they never saw.`);
836
+ return serializeAttemptState(plan, {
837
+ responses: state.responses,
838
+ submittedSlotIds: state.submittedSlotIds,
839
+ index: state.index,
840
+ ...state.savedAt !== void 0 ? { savedAt: state.savedAt } : {}
841
+ });
786
842
  }
843
+ /**
844
+ * Reports how two snapshots' responses differ, slot by slot.
845
+ *
846
+ * Useful for an autosave that should only write what moved, and for an audit
847
+ * trail that has to show what a learner changed between two saves — including
848
+ * an answer they cleared, which a naive comparison of the later snapshot
849
+ * alone cannot see.
850
+ *
851
+ * Entries come back sorted by `slotId`, so the output is stable regardless of
852
+ * the order the two objects happened to be written in.
853
+ */
787
854
  function diffResponses(before, after) {
788
- const slotIds = [.../* @__PURE__ */ new Set([...Object.keys(before.responses), ...Object.keys(after.responses)])];
789
- slotIds.sort();
790
- const entries = [];
791
- for (const slotId of slotIds) {
792
- const had = Object.hasOwn(before.responses, slotId);
793
- const has = Object.hasOwn(after.responses, slotId);
794
- const from = before.responses[slotId];
795
- const to = after.responses[slotId];
796
- if (had && !has) {
797
- entries.push({ slotId, change: "removed", ...from !== void 0 ? { before: from } : {} });
798
- continue;
799
- }
800
- if (!had && has) {
801
- entries.push({ slotId, change: "added", ...to !== void 0 ? { after: to } : {} });
802
- continue;
803
- }
804
- if (canonicalJson(from) !== canonicalJson(to)) {
805
- entries.push({
806
- slotId,
807
- change: "changed",
808
- ...from !== void 0 ? { before: from } : {},
809
- ...to !== void 0 ? { after: to } : {}
810
- });
811
- }
812
- }
813
- return entries;
814
- }
815
-
816
- // src/authoring/item-group.ts
817
- function createItemGroupDraft(context) {
818
- const issued = /* @__PURE__ */ new Set();
819
- const newId = () => {
820
- const id = context.newId();
821
- if (typeof id !== "string" || id === "") {
822
- throw new Error("createItemGroupDraft: newId() must return a non-empty string.");
823
- }
824
- if (issued.has(id)) {
825
- throw new Error(
826
- `createItemGroupDraft: newId() returned "${id}" twice. Ids within one draft must differ.`
827
- );
828
- }
829
- issued.add(id);
830
- return id;
831
- };
832
- return {
833
- schemaVersion: "1.0",
834
- type: "item-group",
835
- id: newId(),
836
- stimulus: { id: newId(), kind: "text", body: "" },
837
- items: []
838
- };
839
- }
840
- function createInteractiveVideoDraft(context) {
841
- const draft = createItemGroupDraft(context);
842
- return {
843
- ...draft,
844
- stimulus: { id: draft.stimulus.id, kind: "video", media: { type: "video", url: "" } },
845
- timeline: { cues: [] }
846
- };
847
- }
848
- function validateItemGroupDraft(draft) {
849
- return withValidationScope(() => validateItemGroupDraftInScope(draft));
850
- }
851
- function validateItemGroupDraftInScope(draft) {
852
- const issues = [];
853
- if (!isRecord(draft)) {
854
- issues.push(
855
- issue("ig_not_an_object", [], "A group must be an object with a stimulus and its items.")
856
- );
857
- return { status: "invalid", issues };
858
- }
859
- issues.push(...checkGroupIdentity(draft));
860
- if (isRecord(draft.stimulus)) {
861
- issues.push(...checkStimulus(draft.stimulus));
862
- } else if (isUnset(draft.stimulus)) {
863
- issues.push(
864
- issue(
865
- "ig_stimulus_required",
866
- ["stimulus"],
867
- "Add the passage, recording or image the questions are about."
868
- )
869
- );
870
- }
871
- issues.push(...checkItems(draft));
872
- if (draft.timeline !== void 0 && draft.timeline !== null) {
873
- issues.push(...checkTimeline(draft));
874
- }
875
- const captions = groupCaptionsField(draft, (captionsUrl) => !isUnwritten(captionsUrl));
876
- if (captions !== void 0) {
877
- issues.push(
878
- issue(
879
- "dc_captions_not_allowed",
880
- ["stimulus", "media", captions],
881
- GROUP_CAPTIONS_REVEAL_DICTATION
882
- )
883
- );
884
- }
885
- const parsed = ItemGroupSchema.safeParse(draft, { reportInput: true });
886
- if (!parsed.success) {
887
- for (const schemaIssue of parsed.error.issues) {
888
- const path = schemaIssue.path.map(String);
889
- if (issues.some((known) => covers(known.path, path))) {
890
- continue;
891
- }
892
- if (path.length > 0 && refusesEmpty(draft, schemaIssue)) {
893
- issues.push(
894
- issue(
895
- "null_not_allowed",
896
- path,
897
- "This field cannot be null. Leave it out if it is optional, or give it a value."
898
- )
899
- );
900
- continue;
901
- }
902
- issues.push({
903
- path,
904
- message: schemaIssue.message,
905
- code: schemaIssue.code,
906
- severity: "invalid"
907
- });
908
- }
909
- }
910
- const stored = validateItemGroup(draft);
911
- if (issues.length === 0 && stored.success) {
912
- return { status: "complete", data: stored.data, issues };
913
- }
914
- if (issues.length === 0) {
915
- for (const error of stored.success ? [] : stored.errors) {
916
- issues.push({ ...error, severity: "invalid" });
917
- }
918
- }
919
- const invalid = issues.some((found) => found.severity !== "incomplete");
920
- return { status: invalid ? "invalid" : "incomplete", issues };
921
- }
922
- function checkTimeline(draft) {
923
- const issues = [];
924
- const timeline = draft.timeline;
925
- if (!isRecord(timeline)) {
926
- return issues;
927
- }
928
- const stimulus = isRecord(draft.stimulus) ? draft.stimulus : void 0;
929
- if (stimulus !== void 0 && !isUnwritten(stimulus.kind) && stimulus.kind !== "video") {
930
- issues.push(
931
- issue(
932
- "ig_timeline_stimulus_kind",
933
- ["stimulus", "kind"],
934
- "An interactive video needs a video: quizzes open at moments of it."
935
- )
936
- );
937
- } else if (stimulus !== void 0 && isRecord(stimulus.media) && !isUnwritten(stimulus.media.type) && stimulus.media.type !== "video") {
938
- issues.push(
939
- issue(
940
- "ig_timeline_stimulus_kind",
941
- ["stimulus", "media", "type"],
942
- "Upload a video file. An embedded player from another site cannot be paused when a quiz opens."
943
- )
944
- );
945
- }
946
- if (draft.shuffle === "within-group") {
947
- issues.push(
948
- issue(
949
- "ig_timeline_shuffle",
950
- ["shuffle"],
951
- "The questions of an interactive video appear in the order their quizzes open, so they cannot be shuffled."
952
- )
953
- );
954
- }
955
- const items = Array.isArray(draft.items) ? draft.items : [];
956
- const itemIndexById = /* @__PURE__ */ new Map();
957
- items.forEach((item, index) => {
958
- if (!isRecord(item)) {
959
- return;
960
- }
961
- if (typeof item.id === "string" && item.id !== "") {
962
- itemIndexById.set(item.id, index);
963
- }
964
- const type = item.type;
965
- if (typeof type === "string" && type !== "" && type !== "item-group" && !isInteractiveVideoItemType(type) && getActivityTypeDescriptor(type) !== void 0) {
966
- issues.push(
967
- issue(
968
- "ig_timeline_item_type",
969
- ["items", index, "type"],
970
- `An interactive video can hold ${INTERACTIVE_VIDEO_ITEM_TYPES.join(", ")} questions only.`
971
- )
972
- );
973
- }
974
- if (type === "dictation" && isUnset(item.media)) {
975
- issues.push(
976
- issue(
977
- "ig_timeline_dictation_media",
978
- ["items", index, "media"],
979
- "Add the recording this dictation plays: inside a video it cannot play the video."
980
- )
981
- );
982
- }
983
- });
984
- const cues = Array.isArray(timeline.cues) ? timeline.cues : [];
985
- const quizIds = /* @__PURE__ */ new Set();
986
- const placed = /* @__PURE__ */ new Set();
987
- cues.forEach((cue, cueIndex) => {
988
- if (!isRecord(cue)) {
989
- return;
990
- }
991
- const at = (field, ...rest) => [
992
- "timeline",
993
- "cues",
994
- cueIndex,
995
- field,
996
- ...rest
997
- ];
998
- if (isMissingId(cue.id)) {
999
- issues.push(issue("ig_timeline_quiz_id_required", at("id"), "This quiz has no id."));
1000
- } else if (typeof cue.id === "string") {
1001
- if (quizIds.has(cue.id)) {
1002
- issues.push(
1003
- issue("ig_timeline_quiz_id_duplicate", at("id"), `Two quizzes share the id "${cue.id}".`)
1004
- );
1005
- }
1006
- quizIds.add(cue.id);
1007
- }
1008
- if (isUnset(cue.at)) {
1009
- issues.push(
1010
- issue(
1011
- "ig_timeline_quiz_time_required",
1012
- at("at"),
1013
- "Choose when in the video this quiz opens."
1014
- )
1015
- );
1016
- } else if (typeof cue.at !== "number" || !Number.isFinite(cue.at) || cue.at < 0) {
1017
- issues.push(
1018
- issue(
1019
- "ig_timeline_quiz_time_invalid",
1020
- at("at"),
1021
- "A quiz opens at a number of seconds, 0 or more."
1022
- )
1023
- );
1024
- }
1025
- if (isUnset(cue.itemIds) || Array.isArray(cue.itemIds) && cue.itemIds.length === 0) {
1026
- issues.push(
1027
- issue("ig_timeline_quiz_empty", at("itemIds"), "Add at least one question to this quiz.")
1028
- );
1029
- return;
1030
- }
1031
- if (!Array.isArray(cue.itemIds)) {
1032
- return;
1033
- }
1034
- cue.itemIds.forEach((itemId, position) => {
1035
- if (typeof itemId !== "string") {
1036
- return;
1037
- }
1038
- if (!itemIndexById.has(itemId)) {
1039
- issues.push(
1040
- issue(
1041
- "ig_timeline_quiz_unknown_item",
1042
- at("itemIds", position),
1043
- `This quiz names a question that is not in the video ("${itemId}").`
1044
- )
1045
- );
1046
- } else if (placed.has(itemId)) {
1047
- issues.push(
1048
- issue(
1049
- "ig_timeline_item_duplicate",
1050
- at("itemIds", position),
1051
- "This question is already in a quiz: each question belongs to one quiz."
1052
- )
1053
- );
1054
- }
1055
- placed.add(itemId);
1056
- });
1057
- });
1058
- for (const [itemId, index] of itemIndexById) {
1059
- if (!placed.has(itemId)) {
1060
- issues.push(
1061
- issue(
1062
- "ig_timeline_item_unplaced",
1063
- ["items", index],
1064
- "Add this question to a quiz, or the video never shows it."
1065
- )
1066
- );
1067
- }
1068
- }
1069
- const chapters = Array.isArray(timeline.chapters) ? timeline.chapters : [];
1070
- let previousAt;
1071
- chapters.forEach((chapter, index) => {
1072
- if (!isRecord(chapter)) {
1073
- return;
1074
- }
1075
- if (isUnwritten(chapter.title)) {
1076
- issues.push(
1077
- issue(
1078
- "ig_timeline_chapter_title",
1079
- ["timeline", "chapters", index, "title"],
1080
- "Give this chapter a title."
1081
- )
1082
- );
1083
- }
1084
- if (typeof chapter.at === "number" && Number.isFinite(chapter.at)) {
1085
- if (previousAt !== void 0 && chapter.at <= previousAt) {
1086
- issues.push(
1087
- issue(
1088
- "ig_timeline_chapter_order",
1089
- ["timeline", "chapters", index, "at"],
1090
- "Chapters must start in order, each after the one before it."
1091
- )
1092
- );
1093
- }
1094
- previousAt = chapter.at;
1095
- }
1096
- });
1097
- return issues;
1098
- }
1099
- function checkGroupIdentity(draft) {
1100
- const issues = [];
1101
- if (draft.schemaVersion !== "1.0") {
1102
- issues.push(
1103
- issue(
1104
- "schema_version_invalid",
1105
- ["schemaVersion"],
1106
- 'The draft must have schemaVersion "1.0". A draft from createItemGroupDraft has it.'
1107
- )
1108
- );
1109
- }
1110
- if (draft.type !== "item-group") {
1111
- issues.push(issue("type_mismatch", ["type"], `The draft's type must be "item-group".`));
1112
- }
1113
- if (isMissingId(draft.id)) {
1114
- issues.push(issue("id_required", ["id"], "The group has no id."));
1115
- }
1116
- if (!isUnset(draft.shuffle) && draft.shuffle !== "none" && draft.shuffle !== "within-group") {
1117
- issues.push(
1118
- issue(
1119
- "ig_shuffle_invalid",
1120
- ["shuffle"],
1121
- 'Shuffling is either "none" or "within-group". Leave it out to keep the authored order.'
1122
- )
1123
- );
1124
- }
1125
- return issues;
855
+ const slotIds = [.../* @__PURE__ */ new Set([...Object.keys(before.responses), ...Object.keys(after.responses)])];
856
+ slotIds.sort();
857
+ const entries = [];
858
+ for (const slotId of slotIds) {
859
+ const had = Object.hasOwn(before.responses, slotId);
860
+ const has = Object.hasOwn(after.responses, slotId);
861
+ const from = before.responses[slotId];
862
+ const to = after.responses[slotId];
863
+ if (had && !has) {
864
+ entries.push({
865
+ slotId,
866
+ change: "removed",
867
+ ...from !== void 0 ? { before: from } : {}
868
+ });
869
+ continue;
870
+ }
871
+ if (!had && has) {
872
+ entries.push({
873
+ slotId,
874
+ change: "added",
875
+ ...to !== void 0 ? { after: to } : {}
876
+ });
877
+ continue;
878
+ }
879
+ if (canonicalJson(from) !== canonicalJson(to)) entries.push({
880
+ slotId,
881
+ change: "changed",
882
+ ...from !== void 0 ? { before: from } : {},
883
+ ...to !== void 0 ? { after: to } : {}
884
+ });
885
+ }
886
+ return entries;
1126
887
  }
1127
- var KINDS = /* @__PURE__ */ new Set(["text", "audio", "video", "image", "mixed"]);
1128
- var MEDIA_FOR_KIND = {
1129
- audio: ["audio"],
1130
- video: ["video", "embed"],
1131
- image: ["image"],
1132
- mixed: ["audio", "video", "image", "embed"]
1133
- };
1134
- function checkStimulus(stimulus) {
1135
- const issues = [];
1136
- const at = (...rest) => ["stimulus", ...rest];
1137
- if (isMissingId(stimulus.id)) {
1138
- issues.push(issue("ig_stimulus_id_required", at("id"), "The stimulus has no id."));
1139
- }
1140
- const kind = stimulus.kind;
1141
- if (isUnwritten(kind)) {
1142
- issues.push(
1143
- issue(
1144
- "ig_stimulus_kind_required",
1145
- at("kind"),
1146
- "Choose what the questions are about: a text, a recording, a video, an image, or a mix."
1147
- )
1148
- );
1149
- } else if (typeof kind !== "string" || !KINDS.has(kind)) {
1150
- if (typeof kind === "string") {
1151
- issues.push(
1152
- issue(
1153
- "ig_stimulus_kind_invalid",
1154
- at("kind"),
1155
- `"${kind}" is not a stimulus kind. Use text, audio, video, image or mixed.`
1156
- )
1157
- );
1158
- }
1159
- if (isRecord(stimulus.media)) {
1160
- issues.push(...checkMedia(stimulus.media, at("media")));
1161
- }
1162
- return issues;
1163
- }
1164
- const hasBody = typeof stimulus.body === "string" && stimulus.body.trim() !== "";
1165
- const htmlPresent = !isUnset(stimulus.bodyHtml);
1166
- if (!hasBody && (kind === "text" || kind === "mixed" || htmlPresent)) {
1167
- issues.push(
1168
- issue(
1169
- "ig_stimulus_body_required",
1170
- at("body"),
1171
- isUnwritten(stimulus.bodyHtml) ? "Write the passage." : "Write the passage as plain text too. The rich-text version is shown only where a sanitiser is supplied."
1172
- )
1173
- );
1174
- }
1175
- if (kind !== "text" && isUnset(stimulus.media)) {
1176
- issues.push(
1177
- issue("ig_stimulus_media_required", at("media"), "Add the recording, video or image.")
1178
- );
1179
- } else if (isRecord(stimulus.media)) {
1180
- const allowed = MEDIA_FOR_KIND[kind];
1181
- const mediaType = stimulus.media.type;
1182
- if (allowed !== void 0 && typeof mediaType === "string" && !allowed.includes(mediaType)) {
1183
- issues.push(
1184
- issue(
1185
- "ig_stimulus_media_kind",
1186
- at("media", "type"),
1187
- `A "${kind}" stimulus cannot carry ${mediaType} media. Use ${allowed.join(" or ")}.`
1188
- )
1189
- );
1190
- }
1191
- issues.push(...checkMedia(stimulus.media, at("media")));
1192
- }
1193
- return issues;
1194
- }
1195
- function checkItems(draft) {
1196
- const issues = [];
1197
- const items = isUnset(draft.items) ? [] : draft.items;
1198
- if (!Array.isArray(items)) {
1199
- return issues;
1200
- }
1201
- if (items.length === 0) {
1202
- issues.push(
1203
- issue("ig_items_required", ["items"], "Add at least one question about this material.")
1204
- );
1205
- return issues;
1206
- }
1207
- const seen = /* @__PURE__ */ new Set();
1208
- const repeated = /* @__PURE__ */ new Set();
1209
- for (const [index, item] of items.entries()) {
1210
- if (!isRecord(item)) {
1211
- continue;
1212
- }
1213
- const ordinal = index + 1;
1214
- if (isMissingId(item.id)) {
1215
- issues.push(
1216
- issue("ig_item_id_required", ["items", index, "id"], `Question ${ordinal} has no id.`)
1217
- );
1218
- } else if (typeof item.id === "string") {
1219
- if (seen.has(item.id)) {
1220
- repeated.add(item.id);
1221
- }
1222
- seen.add(item.id);
1223
- }
1224
- if (item.type === "item-group") {
1225
- issues.push(
1226
- issue(
1227
- "ig_item_nested_group",
1228
- ["items", index, "type"],
1229
- "Groups do not nest: every item must be an activity."
1230
- )
1231
- );
1232
- continue;
1233
- }
1234
- if (isUnwritten(item.type)) {
1235
- issues.push(
1236
- issue(
1237
- "ig_item_type_required",
1238
- ["items", index, "type"],
1239
- `Choose what kind of question ${ordinal} is.`
1240
- )
1241
- );
1242
- continue;
1243
- }
1244
- if (typeof item.type !== "string") {
1245
- continue;
1246
- }
1247
- let result;
1248
- try {
1249
- result = validateDraft(item.type, item);
1250
- } catch (error) {
1251
- if (!(error instanceof UnknownActivityTypeError) || error.activityType !== item.type) {
1252
- throw error;
1253
- }
1254
- issues.push(
1255
- issue(
1256
- "ig_item_type_unknown",
1257
- ["items", index, "type"],
1258
- `"${item.type}" is not a registered activity type.`
1259
- )
1260
- );
1261
- continue;
1262
- }
1263
- for (const found of result.issues) {
1264
- issues.push({ ...found, path: ["items", String(index), ...found.path] });
1265
- }
1266
- }
1267
- for (const id of repeated) {
1268
- issues.push(
1269
- issue("ig_item_id_duplicate", ["items"], `More than one question has the id "${id}".`)
1270
- );
1271
- }
1272
- return issues;
1273
- }
1274
-
1275
- // src/authoring/index.ts
1276
- function validateDraft(type, draft) {
1277
- return withValidationScope(() => validateDraftInScope(type, draft));
1278
- }
1279
- function validateDraftInScope(type, draft) {
1280
- const descriptor = getActivityTypeDescriptor(type);
1281
- if (descriptor === void 0) {
1282
- throw new UnknownActivityTypeError(String(type));
1283
- }
1284
- const reported = isRecord(draft) && descriptor.authoring?.checkDraft !== void 0 ? descriptor.authoring.checkDraft(draft).map(normalise) : [];
1285
- const issues = [...reported];
1286
- const parsed = readSchema(descriptor.schema, draft, `Activity type "${descriptor.type}"`, {
1287
- reportInput: true
1288
- });
1289
- if (!parsed.success) {
1290
- const covered = coveredPathsOf(reported);
1291
- const reportedEmpty = /* @__PURE__ */ new Set();
1292
- for (const schemaIssue of parsed.issues) {
1293
- const path = schemaIssue.path.map(String);
1294
- if (covered.has(pathKey(path))) {
1295
- continue;
1296
- }
1297
- if (path.length > 0 && refusesEmpty(draft, schemaIssue)) {
1298
- const key = JSON.stringify(path);
1299
- if (!reportedEmpty.has(key)) {
1300
- reportedEmpty.add(key);
1301
- issues.push(
1302
- issue(
1303
- "null_not_allowed",
1304
- path,
1305
- typeof schemaIssue.path.at(-1) === "number" ? "This entry has no value. Remove it, or fill it in." : "This field cannot be null. Leave it out if it is optional, or give it a value."
1306
- )
1307
- );
1308
- }
1309
- continue;
1310
- }
1311
- issues.push({
1312
- path,
1313
- message: schemaIssue.message,
1314
- code: schemaIssue.code,
1315
- severity: "invalid"
1316
- });
1317
- }
1318
- }
1319
- if (parsed.success && issues.length === 0) {
1320
- return { status: "complete", data: parsed.data, issues };
1321
- }
1322
- const invalid = issues.some((found) => found.severity !== "incomplete");
1323
- return { status: invalid ? "invalid" : "incomplete", issues };
1324
- }
1325
- function createDraft(type, context) {
1326
- const descriptor = getActivityTypeDescriptor(type);
1327
- if (descriptor === void 0) {
1328
- throw new UnknownActivityTypeError(String(type));
1329
- }
1330
- const create = descriptor.authoring?.createDraft;
1331
- if (create === void 0) {
1332
- throw new Error(
1333
- `Activity type "${String(type)}" declares no authoring.createDraft, so there is no empty draft to create. Build the draft yourself; validateDraft works for every registered type.`
1334
- );
1335
- }
1336
- const issued = /* @__PURE__ */ new Set();
1337
- const newId = () => {
1338
- const id = context.newId();
1339
- if (typeof id !== "string" || id === "") {
1340
- throw new Error("createDraft: newId() must return a non-empty string.");
1341
- }
1342
- if (issued.has(id)) {
1343
- throw new Error(
1344
- `createDraft: newId() returned "${id}" twice. Ids within one draft must differ \u2014 two options sharing an id cannot be scored apart.`
1345
- );
1346
- }
1347
- issued.add(id);
1348
- return id;
1349
- };
1350
- return create({ newId });
1351
- }
1352
- function normalise(found) {
1353
- const documented = Object.hasOwn(DRAFT_ISSUE_SEVERITY, found.code) ? DRAFT_ISSUE_SEVERITY[found.code] : void 0;
1354
- return {
1355
- ...found,
1356
- path: found.path.map(String),
1357
- severity: documented ?? (found.severity === "incomplete" ? "incomplete" : "invalid")
1358
- };
1359
- }
1360
-
1361
- // src/redact.ts
888
+ //#endregion
889
+ //#region src/redact.ts
890
+ /** Merges per-call overrides over a registered policy, one level deep. */
1362
891
  function mergePolicy(base, overrides) {
1363
- if (overrides === void 0) {
1364
- return base;
1365
- }
1366
- const merged = { ...base };
1367
- for (const [key, override] of Object.entries(overrides)) {
1368
- const current = merged[key];
1369
- merged[key] = typeof override === "object" && typeof current === "object" ? { ...current, ...override } : override;
1370
- }
1371
- return merged;
892
+ if (overrides === void 0) return base;
893
+ const merged = { ...base };
894
+ for (const [key, override] of Object.entries(overrides)) {
895
+ const current = merged[key];
896
+ merged[key] = typeof override === "object" && typeof current === "object" ? {
897
+ ...current,
898
+ ...override
899
+ } : override;
900
+ }
901
+ return merged;
1372
902
  }
1373
903
  function isSensitivity(value) {
1374
- return typeof value === "string";
904
+ return typeof value === "string";
1375
905
  }
1376
906
  function keepField(sensitivity, reveal) {
1377
- if (sensitivity === "public") {
1378
- return true;
1379
- }
1380
- return sensitivity === "answer-key" && reveal === "after-submit";
907
+ if (sensitivity === "public") return true;
908
+ return sensitivity === "answer-key" && reveal === "after-submit";
1381
909
  }
910
+ /** An object projection that kept no fields at all. Arrays are never dropped. */
1382
911
  function isEmptyObject(value) {
1383
- return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0;
912
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0;
1384
913
  }
1385
914
  function redactValue(value, policy, reveal) {
1386
- if (Array.isArray(value)) {
1387
- return value.map((element) => redactValue(element, policy, reveal));
1388
- }
1389
- if (value === null || typeof value !== "object") {
1390
- return void 0;
1391
- }
1392
- const source = value;
1393
- const output = {};
1394
- for (const [key, fieldValue] of Object.entries(source)) {
1395
- if (fieldValue === void 0) {
1396
- continue;
1397
- }
1398
- const classification = policy[key];
1399
- if (classification === void 0) {
1400
- continue;
1401
- }
1402
- if (isSensitivity(classification)) {
1403
- if (keepField(classification, reveal)) {
1404
- output[key] = fieldValue;
1405
- }
1406
- continue;
1407
- }
1408
- const nested = redactValue(fieldValue, classification, reveal);
1409
- if (nested !== void 0 && !isEmptyObject(nested)) {
1410
- output[key] = nested;
1411
- }
1412
- }
1413
- return output;
915
+ if (Array.isArray(value)) return value.map((element) => redactValue(element, policy, reveal));
916
+ if (value === null || typeof value !== "object") return;
917
+ const source = value;
918
+ const output = {};
919
+ for (const [key, fieldValue] of Object.entries(source)) {
920
+ if (fieldValue === void 0) continue;
921
+ const classification = policy[key];
922
+ if (classification === void 0) continue;
923
+ if (isSensitivity(classification)) {
924
+ if (keepField(classification, reveal)) output[key] = fieldValue;
925
+ continue;
926
+ }
927
+ const nested = redactValue(fieldValue, classification, reveal);
928
+ if (nested !== void 0 && !isEmptyObject(nested)) output[key] = nested;
929
+ }
930
+ return output;
1414
931
  }
932
+ /**
933
+ * Produces the learner-safe projection of activity data (R7), driven by the
934
+ * `fieldPolicy` registered for `data.type`. Fail-closed and exhaustive by
935
+ * construction: a field the policy does not classify is removed — including
936
+ * unknown passthrough fields — so a NEW field added by a future SDK or a
937
+ * consumer sidecar can never leak through an out-of-date redactor.
938
+ *
939
+ * With the default `reveal: 'none'`, the output validates against the type's
940
+ * strict redacted schema (verified here; an invalid projection throws
941
+ * {@link ActivitySchemaError} rather than shipping an unproven payload).
942
+ *
943
+ * @throws UnknownActivityTypeError when `data.type` is not registered.
944
+ * @throws Error when the registered descriptor declares no `fieldPolicy`
945
+ * (redaction cannot guess sensitivities).
946
+ */
1415
947
  function redact(data, options = {}) {
1416
- const reveal = options.reveal ?? "none";
1417
- const descriptor = getActivityTypeDescriptor(data.type);
1418
- if (descriptor === void 0) {
1419
- throw new UnknownActivityTypeError(String(data.type));
1420
- }
1421
- if (descriptor.fieldPolicy === void 0) {
1422
- throw new Error(
1423
- `Activity type "${descriptor.type}" has no fieldPolicy; redact() cannot run fail-closed redaction without one.`
1424
- );
1425
- }
1426
- const effectivePolicy = mergePolicy(descriptor.fieldPolicy, options.policy);
1427
- const projected = redactValue(data, effectivePolicy, reveal);
1428
- const result = { ...projected, redacted: true };
1429
- if (reveal === "none" && descriptor.redactedSchema !== void 0) {
1430
- const parsed = readSchema(
1431
- descriptor.redactedSchema,
1432
- result,
1433
- `Activity type "${descriptor.type}"`
1434
- );
1435
- if (!parsed.success) {
1436
- throw new ActivitySchemaError(
1437
- descriptor.type,
1438
- parsed.issues.map((issue2) => ({
1439
- path: issue2.path.map(String),
1440
- message: issue2.message,
1441
- code: issue2.code
1442
- }))
1443
- );
1444
- }
1445
- }
1446
- return result;
948
+ const reveal = options.reveal ?? "none";
949
+ const descriptor = getActivityTypeDescriptor(data.type);
950
+ if (descriptor === void 0) throw new UnknownActivityTypeError(String(data.type));
951
+ if (descriptor.fieldPolicy === void 0) throw new Error(`Activity type "${descriptor.type}" has no fieldPolicy; redact() cannot run fail-closed redaction without one.`);
952
+ const result = {
953
+ ...redactValue(data, mergePolicy(descriptor.fieldPolicy, options.policy), reveal),
954
+ redacted: true
955
+ };
956
+ if (reveal === "none" && descriptor.redactedSchema !== void 0) {
957
+ const parsed = readSchema(descriptor.redactedSchema, result, `Activity type "${descriptor.type}"`);
958
+ if (!parsed.success) throw new ActivitySchemaError(descriptor.type, parsed.issues.map((issue) => ({
959
+ path: issue.path.map(String),
960
+ message: issue.message,
961
+ code: issue.code
962
+ })));
963
+ }
964
+ return result;
1447
965
  }
966
+ /**
967
+ * Asserts that `data` is a learner-safe redacted projection: it carries the
968
+ * `redacted: true` marker and, when its type registers a strict redacted
969
+ * schema, validates against it (proving the absence of answer-key fields).
970
+ * Use this at the server boundary before sending activity data to a client
971
+ * that must not hold the key.
972
+ */
1448
973
  function assertRedacted(data) {
1449
- if (typeof data !== "object" || data === null) {
1450
- throw new ActivitySchemaError("unknown", [
1451
- { path: [], message: "Redacted activity data must be an object.", code: "invalid_type" }
1452
- ]);
1453
- }
1454
- const candidate = data;
1455
- if (candidate.redacted !== true) {
1456
- throw new ActivitySchemaError(String(candidate.type ?? "unknown"), [
1457
- {
1458
- path: ["redacted"],
1459
- message: "Missing redacted marker \u2014 this payload is not a redact() projection.",
1460
- code: "custom"
1461
- }
1462
- ]);
1463
- }
1464
- const type = typeof candidate.type === "string" ? candidate.type : "";
1465
- const descriptor = getActivityTypeDescriptor(type);
1466
- if (descriptor === void 0) {
1467
- throw new UnknownActivityTypeError(type);
1468
- }
1469
- if (descriptor.redactedSchema === void 0) {
1470
- throw new ActivitySchemaError(descriptor.type, [
1471
- {
1472
- path: [],
1473
- message: `Activity type "${descriptor.type}" registers no redactedSchema; assertRedacted cannot prove this payload is learner-safe.`,
1474
- code: "custom"
1475
- }
1476
- ]);
1477
- }
1478
- const parsed = readSchema(
1479
- descriptor.redactedSchema,
1480
- candidate,
1481
- `Activity type "${descriptor.type}"`
1482
- );
1483
- if (!parsed.success) {
1484
- throw new ActivitySchemaError(
1485
- descriptor.type,
1486
- parsed.issues.map((issue2) => ({
1487
- path: issue2.path.map(String),
1488
- message: issue2.message,
1489
- code: issue2.code
1490
- }))
1491
- );
1492
- }
974
+ if (typeof data !== "object" || data === null) throw new ActivitySchemaError("unknown", [{
975
+ path: [],
976
+ message: "Redacted activity data must be an object.",
977
+ code: "invalid_type"
978
+ }]);
979
+ const candidate = data;
980
+ if (candidate.redacted !== true) throw new ActivitySchemaError(String(candidate.type ?? "unknown"), [{
981
+ path: ["redacted"],
982
+ message: "Missing redacted marker — this payload is not a redact() projection.",
983
+ code: "custom"
984
+ }]);
985
+ const type = typeof candidate.type === "string" ? candidate.type : "";
986
+ const descriptor = getActivityTypeDescriptor(type);
987
+ if (descriptor === void 0) throw new UnknownActivityTypeError(type);
988
+ if (descriptor.redactedSchema === void 0) throw new ActivitySchemaError(descriptor.type, [{
989
+ path: [],
990
+ message: `Activity type "${descriptor.type}" registers no redactedSchema; assertRedacted cannot prove this payload is learner-safe.`,
991
+ code: "custom"
992
+ }]);
993
+ const parsed = readSchema(descriptor.redactedSchema, candidate, `Activity type "${descriptor.type}"`);
994
+ if (!parsed.success) throw new ActivitySchemaError(descriptor.type, parsed.issues.map((issue) => ({
995
+ path: issue.path.map(String),
996
+ message: issue.message,
997
+ code: issue.code
998
+ })));
1493
999
  }
1494
- var STIMULUS_FIELD_POLICY = {
1495
- id: "public",
1496
- kind: "public",
1497
- title: "public",
1498
- body: "public",
1499
- bodyHtml: "public",
1500
- media: MEDIA_FIELD_POLICY,
1501
- locale: "public",
1502
- attribution: "public",
1503
- transcript: "author-only"
1504
- };
1505
- var ITEM_GROUP_FIELD_POLICY = {
1506
- schemaVersion: "public",
1507
- type: "public",
1508
- id: "public",
1509
- title: "public",
1510
- // See the note on the built-in activity policies: a slot key is identity,
1511
- // and identity has to cross the redaction boundary intact.
1512
- slotKey: "public",
1513
- shuffle: "public",
1514
- stimulus: STIMULUS_FIELD_POLICY,
1515
- // Public, and classified key by key rather than as one leaf: the learner's
1516
- // player needs every part of it, none of it is a key — and a leaf would hand
1517
- // over the author's object by reference, with whatever else was parked in it.
1518
- timeline: {
1519
- // Applies to every element of the array.
1520
- cues: {
1521
- id: "public",
1522
- at: "public",
1523
- itemIds: "public",
1524
- title: "public",
1525
- required: "public"
1526
- },
1527
- chapters: {
1528
- at: "public",
1529
- title: "public"
1530
- },
1531
- navigation: "public"
1532
- }
1000
+ /** The group container's own fields. `items` is handled separately, per item type. */
1001
+ const ITEM_GROUP_FIELD_POLICY = {
1002
+ schemaVersion: "public",
1003
+ type: "public",
1004
+ id: "public",
1005
+ title: "public",
1006
+ slotKey: "public",
1007
+ shuffle: "public",
1008
+ stimulus: {
1009
+ id: "public",
1010
+ kind: "public",
1011
+ title: "public",
1012
+ body: "public",
1013
+ bodyHtml: "public",
1014
+ media: MEDIA_FIELD_POLICY,
1015
+ locale: "public",
1016
+ attribution: "public",
1017
+ transcript: "author-only"
1018
+ },
1019
+ timeline: {
1020
+ cues: {
1021
+ id: "public",
1022
+ at: "public",
1023
+ itemIds: "public",
1024
+ title: "public",
1025
+ required: "public"
1026
+ },
1027
+ chapters: {
1028
+ at: "public",
1029
+ title: "public"
1030
+ },
1031
+ navigation: "public"
1032
+ }
1533
1033
  };
1034
+ /**
1035
+ * Produces the learner-safe projection of an item group: the container and
1036
+ * stimulus under their own fail-closed policy (the author transcript goes;
1037
+ * the passage, media and attribution stay — the learner is meant to see
1038
+ * them), and every item through {@link redact} with the same `options`, so
1039
+ * a per-call `policy` tightens each item exactly as it would alone.
1040
+ *
1041
+ * With the default `reveal: 'none'` the container is verified against the
1042
+ * strict redacted schema; each item was already verified by `redact`.
1043
+ */
1534
1044
  function redactItemGroup(group, options = {}) {
1535
- const reveal = options.reveal ?? "none";
1536
- const { items, ...container } = group;
1537
- const projected = redactValue(container, ITEM_GROUP_FIELD_POLICY, reveal);
1538
- const result = {
1539
- ...projected,
1540
- items: items.map((item) => redact(item, options)),
1541
- redacted: true
1542
- };
1543
- if (reveal === "none") {
1544
- const parsed = RedactedItemGroupSchema.safeParse(result);
1545
- if (!parsed.success) {
1546
- throw new ActivitySchemaError(
1547
- "item-group",
1548
- parsed.error.issues.map((issue2) => ({
1549
- path: issue2.path.map(String),
1550
- message: issue2.message,
1551
- code: issue2.code
1552
- }))
1553
- );
1554
- }
1555
- }
1556
- return result;
1045
+ const reveal = options.reveal ?? "none";
1046
+ const { items, ...container } = group;
1047
+ const result = {
1048
+ ...redactValue(container, ITEM_GROUP_FIELD_POLICY, reveal),
1049
+ items: items.map((item) => redact(item, options)),
1050
+ redacted: true
1051
+ };
1052
+ if (reveal === "none") {
1053
+ const parsed = RedactedItemGroupSchema.safeParse(result);
1054
+ if (!parsed.success) throw new ActivitySchemaError("item-group", parsed.error.issues.map((issue) => ({
1055
+ path: issue.path.map(String),
1056
+ message: issue.message,
1057
+ code: issue.code
1058
+ })));
1059
+ }
1060
+ return result;
1557
1061
  }
1062
+ /**
1063
+ * Asserts that `data` is a learner-safe item group: it carries the marker,
1064
+ * its container and stimulus satisfy the strict redacted schema (so no
1065
+ * transcript, no unclassified field), and EVERY item passes
1066
+ * {@link assertRedacted} against its own type's redacted schema. Item
1067
+ * failures are reported at `items.<index>.…`. Use it at the server boundary
1068
+ * before sending a group to a client that must not hold the key.
1069
+ */
1558
1070
  function assertRedactedItemGroup(data) {
1559
- if (typeof data !== "object" || data === null) {
1560
- throw new ActivitySchemaError("item-group", [
1561
- { path: [], message: "Redacted item group must be an object.", code: "invalid_type" }
1562
- ]);
1563
- }
1564
- const candidate = data;
1565
- if (candidate.redacted !== true) {
1566
- throw new ActivitySchemaError("item-group", [
1567
- {
1568
- path: ["redacted"],
1569
- message: "Missing redacted marker \u2014 this payload is not a redactItemGroup() projection.",
1570
- code: "custom"
1571
- }
1572
- ]);
1573
- }
1574
- const parsed = RedactedItemGroupSchema.safeParse(candidate);
1575
- if (!parsed.success) {
1576
- throw new ActivitySchemaError(
1577
- "item-group",
1578
- parsed.error.issues.map((issue2) => ({
1579
- path: issue2.path.map(String),
1580
- message: issue2.message,
1581
- code: issue2.code
1582
- }))
1583
- );
1584
- }
1585
- parsed.data.items.forEach((item, index) => {
1586
- try {
1587
- assertRedacted(item);
1588
- } catch (error) {
1589
- if (error instanceof ActivitySchemaError) {
1590
- throw new ActivitySchemaError(
1591
- "item-group",
1592
- error.errors.map((issue2) => ({
1593
- ...issue2,
1594
- path: ["items", String(index), ...issue2.path]
1595
- }))
1596
- );
1597
- }
1598
- throw error;
1599
- }
1600
- });
1071
+ if (typeof data !== "object" || data === null) throw new ActivitySchemaError("item-group", [{
1072
+ path: [],
1073
+ message: "Redacted item group must be an object.",
1074
+ code: "invalid_type"
1075
+ }]);
1076
+ const candidate = data;
1077
+ if (candidate.redacted !== true) throw new ActivitySchemaError("item-group", [{
1078
+ path: ["redacted"],
1079
+ message: "Missing redacted marker — this payload is not a redactItemGroup() projection.",
1080
+ code: "custom"
1081
+ }]);
1082
+ const parsed = RedactedItemGroupSchema.safeParse(candidate);
1083
+ if (!parsed.success) throw new ActivitySchemaError("item-group", parsed.error.issues.map((issue) => ({
1084
+ path: issue.path.map(String),
1085
+ message: issue.message,
1086
+ code: issue.code
1087
+ })));
1088
+ parsed.data.items.forEach((item, index) => {
1089
+ try {
1090
+ assertRedacted(item);
1091
+ } catch (error) {
1092
+ if (error instanceof ActivitySchemaError) throw new ActivitySchemaError("item-group", error.errors.map((issue) => ({
1093
+ ...issue,
1094
+ path: [
1095
+ "items",
1096
+ String(index),
1097
+ ...issue.path
1098
+ ]
1099
+ })));
1100
+ throw error;
1101
+ }
1102
+ });
1601
1103
  }
1602
-
1603
- // src/timeline.ts
1104
+ //#endregion
1105
+ //#region src/timeline.ts
1106
+ /**
1107
+ * Reads a stored {@link MediaProgress}. Never throws: anything that is not one
1108
+ * — a string, a stale shape, an object whose getters throw — answers `null`,
1109
+ * and the player starts from the beginning.
1110
+ *
1111
+ * What it keeps, it clamps. A stored position is host storage, which is input
1112
+ * from a stranger by the time it is read back: a negative `at`, a `furthest`
1113
+ * behind `at`, or a position past the end of a video that has since been
1114
+ * re-cut must not put the playhead somewhere it cannot be. Give `duration`
1115
+ * once the video's metadata is known, and both positions are held inside it.
1116
+ */
1604
1117
  function readMediaProgress(value, duration) {
1605
- let version;
1606
- let at;
1607
- let furthest;
1608
- try {
1609
- if (typeof value !== "object" || value === null) {
1610
- return null;
1611
- }
1612
- ({ progressVersion: version, at, furthest } = value);
1613
- } catch {
1614
- return null;
1615
- }
1616
- if (version !== "1.0" || typeof at !== "number" || !Number.isFinite(at)) {
1617
- return null;
1618
- }
1619
- const end = typeof duration === "number" && Number.isFinite(duration) && duration >= 0 ? duration : Number.POSITIVE_INFINITY;
1620
- const clampedAt = Math.min(Math.max(0, at), end);
1621
- const reached = typeof furthest === "number" && Number.isFinite(furthest) ? furthest : clampedAt;
1622
- return {
1623
- progressVersion: "1.0",
1624
- at: clampedAt,
1625
- furthest: Math.min(Math.max(clampedAt, reached), end)
1626
- };
1118
+ let version;
1119
+ let at;
1120
+ let furthest;
1121
+ try {
1122
+ if (typeof value !== "object" || value === null) return null;
1123
+ ({progressVersion: version, at, furthest} = value);
1124
+ } catch {
1125
+ return null;
1126
+ }
1127
+ if (version !== "1.0" || typeof at !== "number" || !Number.isFinite(at)) return null;
1128
+ const end = typeof duration === "number" && Number.isFinite(duration) && duration >= 0 ? duration : Number.POSITIVE_INFINITY;
1129
+ const clampedAt = Math.min(Math.max(0, at), end);
1130
+ return {
1131
+ progressVersion: "1.0",
1132
+ at: clampedAt,
1133
+ furthest: Math.min(Math.max(clampedAt, typeof furthest === "number" && Number.isFinite(furthest) ? furthest : clampedAt), end)
1134
+ };
1627
1135
  }
1136
+ /**
1137
+ * One interactive video's composed result: the scored items whose slot belongs
1138
+ * to the entry, composed as one section of weight 1. A slot belongs when
1139
+ * `entryKeyOf(item.slotId) === entryKey`, so a host can pass a whole attempt's
1140
+ * items and get the video's share of it.
1141
+ *
1142
+ * `entryKey` is the group's `slotKey` when it has one — which every published
1143
+ * video should — or its position in the sequence otherwise. A group object
1144
+ * alone cannot know its position, which is why this takes the key.
1145
+ *
1146
+ * @throws Error when no item belongs to the entry. A mistyped key would
1147
+ * otherwise compose nothing into a `final` result, and a refusal must
1148
+ * never read as a grade.
1149
+ */
1628
1150
  function composeTimelineScore(entryKey, items, policy) {
1629
- const own = items.filter((item) => entryKeyOf(item.slotId) === entryKey);
1630
- if (own.length === 0) {
1631
- throw new Error(
1632
- `composeTimelineScore: no scored item belongs to entry "${entryKey}". Pass the video's slotKey (or its position in the sequence), and the items of the attempt that holds it.`
1633
- );
1634
- }
1635
- return composeAssessmentScore([{ id: entryKey, weight: 1, items: own }], policy);
1151
+ const own = items.filter((item) => entryKeyOf(item.slotId) === entryKey);
1152
+ if (own.length === 0) throw new Error(`composeTimelineScore: no scored item belongs to entry "${entryKey}". Pass the video's slotKey (or its position in the sequence), and the items of the attempt that holds it.`);
1153
+ return composeAssessmentScore([{
1154
+ id: entryKey,
1155
+ weight: 1,
1156
+ items: own
1157
+ }], policy);
1636
1158
  }
1637
- export {
1638
- AI_COACHING_MAX_TIP_LENGTH,
1639
- AI_COACHING_MAX_WORDS,
1640
- AI_EXPLANATION_TYPES,
1641
- AI_HINT_TYPES,
1642
- AI_TEXT_MAX_LENGTH,
1643
- AI_WRITING_MAX_CORRECTIONS,
1644
- AI_WRITING_MAX_FIELD_LENGTH,
1645
- ActivitySchemaError,
1646
- DEFAULT_ITEM_SCORING_POLICY,
1647
- DEFAULT_PASS_THRESHOLD,
1648
- DICTATION_MAX_ACCEPTED_TRANSCRIPTS,
1649
- DICTATION_MAX_EQUIVALENCES,
1650
- DICTATION_MAX_EQUIVALENCE_LENGTH,
1651
- DICTATION_MAX_TEXT_LENGTH,
1652
- DICTATION_MAX_TRANSCRIPT_LENGTH,
1653
- DeferredScoringError,
1654
- INTERACTIVE_VIDEO_ITEM_TYPES,
1655
- ITEM_SCORING_MAX_RETRIES,
1656
- OPEN_DELIVERY_POLICY,
1657
- READ_ALOUD_MAX_DIMENSION_WEIGHT,
1658
- READ_ALOUD_MAX_REFERENCE_LENGTH,
1659
- READ_ALOUD_MAX_SECONDS,
1660
- READ_ALOUD_MAX_TAKES,
1661
- RedactedScoringError,
1662
- SPEECH_ASSESSMENT_MAX_WORDS,
1663
- TIMELINE_MAX_CHAPTERS,
1664
- TIMELINE_MAX_ITEMS,
1665
- TIMELINE_MAX_QUIZZES,
1666
- TIMELINE_MAX_TITLE_LENGTH,
1667
- UnknownActivityTypeError,
1668
- XAPIVerb,
1669
- XAPI_VERB_DISPLAY,
1670
- aiAllowedByContent,
1671
- aiCoachingRequest,
1672
- aiExplanationRequest,
1673
- aiGradeOf,
1674
- aiHintRequest,
1675
- aiSupports,
1676
- aiWritingFeedbackRequest,
1677
- alignDictation,
1678
- alignReadAloud,
1679
- assertRedacted,
1680
- assertRedactedItemGroup,
1681
- buildAiFacts,
1682
- canonicalJson,
1683
- checkAiCoaching,
1684
- checkAiExplanation,
1685
- checkAiHint,
1686
- checkAiWritingFeedback,
1687
- classifyBand,
1688
- combineDeliveryPolicies,
1689
- composeAssessmentScore,
1690
- composeTimelineScore,
1691
- computePassThreshold,
1692
- contentHash,
1693
- countWords,
1694
- createDraft,
1695
- createInteractiveVideoDraft,
1696
- createItemGroupDraft,
1697
- defineActivityType,
1698
- dictationJsonSchema,
1699
- dictationReferenceWords,
1700
- dictationType,
1701
- diffDictationChars,
1702
- diffResponses,
1703
- entryKeyOf,
1704
- evaluate,
1705
- evaluateTries,
1706
- fillInTheBlanksJsonSchema,
1707
- fillInTheBlanksType,
1708
- fingerprint,
1709
- flattenSequence,
1710
- gapSelectJsonSchema,
1711
- gapSelectType,
1712
- getActivityTypeDescriptor,
1713
- gradeFromRubric,
1714
- gradeReadAloud,
1715
- gte,
1716
- hasGrade,
1717
- hashSeed,
1718
- hintRevealsAnswer,
1719
- inspectWav,
1720
- isInteractiveVideoItemType,
1721
- isItemGroup,
1722
- itemGroupJsonSchema,
1723
- jsonSchemaFor,
1724
- levenshteinDistance,
1725
- matchText,
1726
- multipleChoiceJsonSchema,
1727
- multipleChoiceType,
1728
- outcomeFromGrade,
1729
- outcomeFromUnscorable,
1730
- planAttempt,
1731
- planMediaBudgets,
1732
- readAiTextResult,
1733
- readAloudJsonSchema,
1734
- readAloudType,
1735
- readMediaProgress,
1736
- redact,
1737
- redactItemGroup,
1738
- registerActivityType,
1739
- registeredActivityTypes,
1740
- resolveDeliveryPolicy,
1741
- resolveItemScoringPolicy,
1742
- resolvePlaybackPolicy,
1743
- restoreAttemptState,
1744
- restoreMediaPlayLedger,
1745
- roundGrade,
1746
- score,
1747
- scoreTries,
1748
- scoredItemsFromPlan,
1749
- seededShuffle,
1750
- serializeAttemptState,
1751
- serializeMediaPlayLedger,
1752
- slotMediaKey,
1753
- stimulusJsonSchema,
1754
- stimulusMediaKey,
1755
- validateActivity,
1756
- validateDeliveryPolicy,
1757
- validateDraft,
1758
- validateItemGroup,
1759
- validateItemGroupDraft,
1760
- validateItemScoringPolicy,
1761
- validateMedia,
1762
- validateOptionMedia,
1763
- validateSpeechAssessment,
1764
- validateXAPIStatement,
1765
- verifyAttemptPlan,
1766
- writtenResponseJsonSchema,
1767
- writtenResponseType,
1768
- xAPIBuilder,
1769
- xapiDefinitionFor
1770
- };
1159
+ //#endregion
1160
+ export { AI_COACHING_MAX_TIP_LENGTH, AI_COACHING_MAX_WORDS, AI_CRITIQUE_MAX_FIELD_LENGTH, AI_CRITIQUE_MAX_FINDINGS, AI_DRAFTS_MAX_COUNT, AI_DRAFTS_MAX_REPAIRS, AI_EXPLANATION_TYPES, AI_HINT_TYPES, AI_TEXT_MAX_LENGTH, AI_WRITING_MAX_CORRECTIONS, AI_WRITING_MAX_FIELD_LENGTH, ActivitySchemaError, BUILT_IN_ACTIVITY_TYPES, DEFAULT_ITEM_SCORING_POLICY, DEFAULT_PASS_THRESHOLD, DICTATION_MAX_ACCEPTED_TRANSCRIPTS, DICTATION_MAX_EQUIVALENCES, DICTATION_MAX_EQUIVALENCE_LENGTH, DICTATION_MAX_TEXT_LENGTH, DICTATION_MAX_TRANSCRIPT_LENGTH, DeferredScoringError, INTERACTIVE_VIDEO_ITEM_TYPES, ITEM_SCORING_MAX_RETRIES, OPEN_DELIVERY_POLICY, READ_ALOUD_MAX_DIMENSION_WEIGHT, READ_ALOUD_MAX_REFERENCE_LENGTH, READ_ALOUD_MAX_SECONDS, READ_ALOUD_MAX_TAKES, RedactedScoringError, SPEECH_ASSESSMENT_MAX_WORDS, TIMELINE_MAX_CHAPTERS, TIMELINE_MAX_ITEMS, TIMELINE_MAX_QUIZZES, TIMELINE_MAX_TITLE_LENGTH, UnknownActivityTypeError, XAPIVerb, XAPI_VERB_DISPLAY, aiAllowedByContent, aiCoachingRequest, aiCritiqueRequest, aiDraftsRepairRequest, aiDraftsRequest, aiExplanationRequest, aiGradeOf, aiHintRequest, aiSupports, aiWritingFeedbackRequest, alignDictation, alignReadAloud, assertRedacted, assertRedactedItemGroup, buildAiFacts, canonicalJson, checkAiCoaching, checkAiCritique, checkAiDrafts, checkAiExplanation, checkAiHint, checkAiWritingFeedback, classifyBand, combineDeliveryPolicies, composeAssessmentScore, composeTimelineScore, computePassThreshold, contentHash, countWords, createDraft, createInteractiveVideoDraft, createItemGroupDraft, critiqueDraft, critiqueDrafts, critiqueItemGroupDraft, defineActivityType, dictationJsonSchema, dictationReferenceWords, dictationType, diffDictationChars, diffResponses, entryKeyOf, evaluate, evaluateTries, fillInTheBlanksJsonSchema, fillInTheBlanksType, fingerprint, flattenSequence, gapSelectJsonSchema, gapSelectType, generateDrafts, getActivityTypeDescriptor, gradeFromRubric, gradeReadAloud, gte, hasGrade, hashSeed, hintRevealsAnswer, inspectWav, interactiveVideoFromDrafts, isBuiltInActivityType, isInteractiveVideoItemType, isItemGroup, itemGroupJsonSchema, jsonSchemaFor, levenshteinDistance, matchText, multipleChoiceJsonSchema, multipleChoiceType, outcomeFromGrade, outcomeFromUnscorable, planAttempt, planMediaBudgets, readAiTextResult, readAloudJsonSchema, readAloudType, readMediaProgress, redact, redactItemGroup, registerActivityType, registeredActivityTypes, resolveDeliveryPolicy, resolveItemScoringPolicy, resolvePlaybackPolicy, restoreAttemptState, restoreMediaPlayLedger, roundGrade, score, scoreTries, scoredItemsFromPlan, seededShuffle, serializeAttemptState, serializeMediaPlayLedger, slotMediaKey, stimulusJsonSchema, stimulusMediaKey, validateActivity, validateDeliveryPolicy, validateDraft, validateItemGroup, validateItemGroupDraft, validateItemScoringPolicy, validateMedia, validateOptionMedia, validateSpeechAssessment, validateXAPIStatement, verifyAttemptPlan, writtenResponseJsonSchema, writtenResponseType, xAPIBuilder, xapiDefinitionFor };
1161
+
1771
1162
  //# sourceMappingURL=index.js.map