@intellectif/lk-core 1.2.0 → 1.4.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 (105) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +2 -2
  3. package/dist/ai-CnmLPMzd.d.cts +2417 -0
  4. package/dist/ai-CnmLPMzd.d.cts.map +1 -0
  5. package/dist/ai-CnmLPMzd.d.ts +2417 -0
  6. package/dist/ai-CnmLPMzd.d.ts.map +1 -0
  7. package/dist/ai-check.cjs +845 -620
  8. package/dist/ai-check.cjs.map +1 -1
  9. package/dist/ai-check.d.cts +82 -80
  10. package/dist/ai-check.d.cts.map +1 -0
  11. package/dist/ai-check.d.ts +82 -80
  12. package/dist/ai-check.d.ts.map +1 -0
  13. package/dist/ai-check.js +843 -621
  14. package/dist/ai-check.js.map +1 -1
  15. package/dist/ai-writing-CPpH9Qxq.js +2601 -0
  16. package/dist/ai-writing-CPpH9Qxq.js.map +1 -0
  17. package/dist/ai-writing-G6tnCGzw.cjs +2846 -0
  18. package/dist/ai-writing-G6tnCGzw.cjs.map +1 -0
  19. package/dist/index-2nigSf4N.d.cts +339 -0
  20. package/dist/index-2nigSf4N.d.cts.map +1 -0
  21. package/dist/index-B54baFUA.d.ts +339 -0
  22. package/dist/index-B54baFUA.d.ts.map +1 -0
  23. package/dist/index-BAfEHCnD.d.cts +1071 -0
  24. package/dist/index-BAfEHCnD.d.cts.map +1 -0
  25. package/dist/index-BqMXWuNC.d.cts +153 -0
  26. package/dist/index-BqMXWuNC.d.cts.map +1 -0
  27. package/dist/index-CVWvymVb.d.ts +1071 -0
  28. package/dist/index-CVWvymVb.d.ts.map +1 -0
  29. package/dist/index-CcHDTxIZ.d.ts +153 -0
  30. package/dist/index-CcHDTxIZ.d.ts.map +1 -0
  31. package/dist/index.cjs +1211 -1146
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +941 -861
  34. package/dist/index.d.cts.map +1 -0
  35. package/dist/index.d.ts +941 -861
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +1063 -1147
  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 -34
  52. package/dist/schemas.d.cts +2 -2
  53. package/dist/schemas.d.ts +2 -2
  54. package/dist/schemas.js +3 -34
  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-D705CXng.d.cts +0 -2162
  73. package/dist/activity-D705CXng.d.ts +0 -2162
  74. package/dist/chunk-46BXIGLG.cjs +0 -272
  75. package/dist/chunk-46BXIGLG.cjs.map +0 -1
  76. package/dist/chunk-4YANYTFN.cjs +0 -1256
  77. package/dist/chunk-4YANYTFN.cjs.map +0 -1
  78. package/dist/chunk-7KOWU4RO.js +0 -2207
  79. package/dist/chunk-7KOWU4RO.js.map +0 -1
  80. package/dist/chunk-7THXD7AN.cjs +0 -5057
  81. package/dist/chunk-7THXD7AN.cjs.map +0 -1
  82. package/dist/chunk-CYCTIXUN.cjs +0 -118
  83. package/dist/chunk-CYCTIXUN.cjs.map +0 -1
  84. package/dist/chunk-CYPA5BW5.js +0 -118
  85. package/dist/chunk-CYPA5BW5.js.map +0 -1
  86. package/dist/chunk-JTNDIBZO.js +0 -272
  87. package/dist/chunk-JTNDIBZO.js.map +0 -1
  88. package/dist/chunk-MV2N2WNS.js +0 -352
  89. package/dist/chunk-MV2N2WNS.js.map +0 -1
  90. package/dist/chunk-MXI26H62.cjs +0 -2207
  91. package/dist/chunk-MXI26H62.cjs.map +0 -1
  92. package/dist/chunk-QS7B42ZR.js +0 -5057
  93. package/dist/chunk-QS7B42ZR.js.map +0 -1
  94. package/dist/chunk-QX2ERL72.js +0 -1256
  95. package/dist/chunk-QX2ERL72.js.map +0 -1
  96. package/dist/chunk-ZWXQSKCX.cjs +0 -352
  97. package/dist/chunk-ZWXQSKCX.cjs.map +0 -1
  98. package/dist/index-BChYtrEe.d.ts +0 -548
  99. package/dist/index-VXt_v3YI.d.cts +0 -548
  100. package/dist/schemas.cjs.map +0 -1
  101. package/dist/schemas.js.map +0 -1
  102. package/dist/scoring.cjs.map +0 -1
  103. package/dist/scoring.js.map +0 -1
  104. package/dist/xapi.cjs.map +0 -1
  105. package/dist/xapi.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,1246 +1,1162 @@
1
- import {
2
- XAPIVerb,
3
- XAPI_VERB_DISPLAY,
4
- validateXAPIStatement,
5
- xAPIBuilder,
6
- xapiDefinitionFor
7
- } from "./chunk-JTNDIBZO.js";
8
- import {
9
- dictationJsonSchema,
10
- fillInTheBlanksJsonSchema,
11
- gapSelectJsonSchema,
12
- itemGroupJsonSchema,
13
- jsonSchemaFor,
14
- multipleChoiceJsonSchema,
15
- readAloudJsonSchema,
16
- stimulusJsonSchema,
17
- validateActivity,
18
- validateMedia,
19
- validateOptionMedia,
20
- writtenResponseJsonSchema
21
- } from "./chunk-CYPA5BW5.js";
22
- import {
23
- AI_COACHING_MAX_TIP_LENGTH,
24
- AI_COACHING_MAX_WORDS,
25
- AI_CRITIQUE_MAX_FIELD_LENGTH,
26
- AI_CRITIQUE_MAX_FINDINGS,
27
- AI_DRAFTS_MAX_COUNT,
28
- AI_DRAFTS_MAX_REPAIRS,
29
- AI_EXPLANATION_TYPES,
30
- AI_HINT_TYPES,
31
- AI_TEXT_MAX_LENGTH,
32
- AI_WRITING_MAX_CORRECTIONS,
33
- AI_WRITING_MAX_FIELD_LENGTH,
34
- aiAllowedByContent,
35
- aiCoachingRequest,
36
- aiCritiqueRequest,
37
- aiDraftsRepairRequest,
38
- aiDraftsRequest,
39
- aiExplanationRequest,
40
- aiGradeOf,
41
- aiHintRequest,
42
- aiSupports,
43
- aiWritingFeedbackRequest,
44
- buildAiFacts,
45
- checkAiCoaching,
46
- checkAiCritique,
47
- checkAiDrafts,
48
- checkAiExplanation,
49
- checkAiHint,
50
- checkAiWritingFeedback,
51
- createDraft,
52
- createInteractiveVideoDraft,
53
- createItemGroupDraft,
54
- critiqueDraft,
55
- critiqueDrafts,
56
- critiqueItemGroupDraft,
57
- generateDrafts,
58
- hintRevealsAnswer,
59
- interactiveVideoFromDrafts,
60
- readAiTextResult,
61
- validateDraft,
62
- validateItemGroupDraft
63
- } from "./chunk-7KOWU4RO.js";
64
- import {
65
- DEFAULT_ITEM_SCORING_POLICY,
66
- DEFAULT_PASS_THRESHOLD,
67
- ITEM_SCORING_MAX_RETRIES,
68
- alignReadAloud,
69
- classifyBand,
70
- composeAssessmentScore,
71
- computePassThreshold,
72
- diffDictationChars,
73
- evaluate,
74
- evaluateTries,
75
- gradeFromRubric,
76
- gradeReadAloud,
77
- gte,
78
- hasGrade,
79
- inspectWav,
80
- outcomeFromGrade,
81
- outcomeFromUnscorable,
82
- resolveItemScoringPolicy,
83
- roundGrade,
84
- score,
85
- scoreTries,
86
- validateItemScoringPolicy,
87
- validateSpeechAssessment
88
- } from "./chunk-QX2ERL72.js";
89
- import {
90
- INTERACTIVE_VIDEO_ITEM_TYPES,
91
- RedactedItemGroupSchema,
92
- TIMELINE_MAX_CHAPTERS,
93
- TIMELINE_MAX_ITEMS,
94
- TIMELINE_MAX_QUIZZES,
95
- TIMELINE_MAX_TITLE_LENGTH,
96
- isInteractiveVideoItemType,
97
- validateItemGroup
98
- } from "./chunk-MV2N2WNS.js";
99
- import {
100
- ActivitySchemaError,
101
- DICTATION_MAX_ACCEPTED_TRANSCRIPTS,
102
- DICTATION_MAX_EQUIVALENCES,
103
- DICTATION_MAX_EQUIVALENCE_LENGTH,
104
- DICTATION_MAX_TEXT_LENGTH,
105
- DICTATION_MAX_TRANSCRIPT_LENGTH,
106
- DeferredScoringError,
107
- MEDIA_FIELD_POLICY,
108
- READ_ALOUD_MAX_DIMENSION_WEIGHT,
109
- READ_ALOUD_MAX_REFERENCE_LENGTH,
110
- READ_ALOUD_MAX_SECONDS,
111
- READ_ALOUD_MAX_TAKES,
112
- RedactedScoringError,
113
- SPEECH_ASSESSMENT_MAX_WORDS,
114
- UnknownActivityTypeError,
115
- alignDictation,
116
- countWords,
117
- defineActivityType,
118
- dictationReferenceWords,
119
- dictationType,
120
- fillInTheBlanksType,
121
- gapSelectType,
122
- getActivityTypeDescriptor,
123
- levenshteinDistance,
124
- matchText,
125
- multipleChoiceType,
126
- readAloudType,
127
- readSchema,
128
- registerActivityType,
129
- registeredActivityTypes,
130
- writtenResponseType
131
- } from "./chunk-QS7B42ZR.js";
132
-
133
- // 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, V as AI_MATERIAL_MAX_LENGTH, _ 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-CPpH9Qxq.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
+ */
134
28
  function canonicalJson(value, seen = /* @__PURE__ */ new Set()) {
135
- if (value === null) {
136
- return "null";
137
- }
138
- if (typeof value === "number") {
139
- return Number.isFinite(value) ? JSON.stringify(value === 0 ? 0 : value) : `"#${String(value)}"`;
140
- }
141
- if (typeof value === "string" || typeof value === "boolean") {
142
- return JSON.stringify(value);
143
- }
144
- if (typeof value === "bigint") {
145
- return `"#${value.toString()}n"`;
146
- }
147
- if (typeof value === "object") {
148
- if (seen.has(value)) {
149
- throw new Error(
150
- "canonicalJson: the value contains a circular reference and cannot be fingerprinted."
151
- );
152
- }
153
- seen.add(value);
154
- try {
155
- if (Array.isArray(value)) {
156
- return `[${value.map((element) => element === void 0 ? "null" : canonicalJson(element, seen)).join(",")}]`;
157
- }
158
- const source = value;
159
- const parts = [];
160
- for (const key of Object.keys(source).sort()) {
161
- const entry = source[key];
162
- if (entry === void 0) {
163
- continue;
164
- }
165
- parts.push(`${JSON.stringify(key)}:${canonicalJson(entry, seen)}`);
166
- }
167
- return `{${parts.join(",")}}`;
168
- } finally {
169
- seen.delete(value);
170
- }
171
- }
172
- 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";
173
51
  }
174
- var FNV_OFFSET = 14695981039346656037n;
175
- var FNV_PRIME = 1099511628211n;
176
- 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
+ */
177
65
  function fingerprint(input) {
178
- const bytes = new TextEncoder().encode(input);
179
- let hash = FNV_OFFSET;
180
- for (const byte of bytes) {
181
- hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK64;
182
- }
183
- 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");
184
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
+ */
185
75
  function contentHash(value) {
186
- return fingerprint(canonicalJson(value));
76
+ return fingerprint(canonicalJson(value));
187
77
  }
188
-
189
- // src/delivery.ts
190
- var OPEN_DELIVERY_POLICY = Object.freeze({
191
- feedback: true,
192
- solutions: true,
193
- hints: true,
194
- 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
+ })
195
93
  });
196
- var SETTINGS = ["feedback", "solutions", "hints"];
197
- 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
+ */
198
110
  function allows(value) {
199
- return value === void 0 || value === null || value === true;
111
+ return value === void 0 || value === null || value === true;
200
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
+ */
201
121
  function resolveDeliveryPolicy(policy) {
202
- if (policy === void 0 || policy === null) {
203
- return OPEN_DELIVERY_POLICY;
204
- }
205
- if (typeof policy !== "object" || Array.isArray(policy)) {
206
- return {
207
- feedback: false,
208
- solutions: false,
209
- hints: false,
210
- ai: { hints: false, explanations: false }
211
- };
212
- }
213
- const given = policy;
214
- const ai = given.ai;
215
- const aiGiven = ai === void 0 || ai === null || ai === true ? {} : typeof ai === "object" && !Array.isArray(ai) ? ai : { hints: false, explanations: false };
216
- return {
217
- feedback: allows(given.feedback),
218
- solutions: allows(given.solutions),
219
- hints: allows(given.hints),
220
- ai: { hints: allows(aiGiven.hints), explanations: allows(aiGiven.explanations) }
221
- };
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
+ };
222
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
+ */
223
153
  function combineDeliveryPolicies(...policies) {
224
- const resolved = policies.map(resolveDeliveryPolicy);
225
- const every = (read) => resolved.every(read);
226
- return {
227
- feedback: every((one) => one.feedback),
228
- solutions: every((one) => one.solutions),
229
- hints: every((one) => one.hints),
230
- ai: {
231
- hints: every((one) => one.ai.hints),
232
- explanations: every((one) => one.ai.explanations)
233
- }
234
- };
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
+ };
235
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
+ */
236
176
  function validateDeliveryPolicy(policy) {
237
- const issues = [];
238
- if (policy === void 0 || policy === null) {
239
- return { success: true, data: {} };
240
- }
241
- if (typeof policy !== "object" || Array.isArray(policy)) {
242
- return {
243
- success: false,
244
- issues: [{ path: "", message: "A delivery policy is an object of settings." }]
245
- };
246
- }
247
- const given = policy;
248
- for (const key of Object.keys(given)) {
249
- if (key === "ai") {
250
- continue;
251
- }
252
- if (!SETTINGS.includes(key)) {
253
- issues.push({
254
- path: key,
255
- message: `"${key}" is not a delivery setting. The settings are feedback, solutions, hints and ai.`
256
- });
257
- continue;
258
- }
259
- const value = given[key];
260
- if (value !== true && value !== false && value !== null && value !== void 0) {
261
- issues.push({ path: key, message: `"${key}" must be true, false or null.` });
262
- }
263
- }
264
- const ai = given.ai;
265
- if (ai !== void 0 && ai !== null && ai !== true && ai !== false) {
266
- if (typeof ai !== "object" || Array.isArray(ai)) {
267
- issues.push({
268
- path: "ai",
269
- message: '"ai" must be true, false, or an object of hints and explanations.'
270
- });
271
- } else {
272
- for (const [key, value] of Object.entries(ai)) {
273
- if (!AI_SETTINGS.includes(key)) {
274
- issues.push({
275
- path: `ai.${key}`,
276
- message: `"ai.${key}" is not an AI setting. The settings are hints and explanations.`
277
- });
278
- continue;
279
- }
280
- if (value !== true && value !== false && value !== null && value !== void 0) {
281
- issues.push({ path: `ai.${key}`, message: `"ai.${key}" must be true, false or null.` });
282
- }
283
- }
284
- }
285
- }
286
- 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
+ };
287
232
  }
288
-
289
- // 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. */
290
249
  function hashSeed(input) {
291
- let h = 2166136261 >>> 0;
292
- for (let i = 0; i < input.length; i += 1) {
293
- h ^= input.charCodeAt(i);
294
- h = Math.imul(h, 16777619) >>> 0;
295
- }
296
- 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;
297
256
  }
257
+ /** LCG-driven Fisher–Yates over a 32-bit seed; returns a permutation (no loss, no duplicate). */
298
258
  function shuffleWithSeed(items, seed, version) {
299
- const out = [...items];
300
- let s = seed >>> 0 || 1;
301
- for (let i = out.length - 1; i > 0; i -= 1) {
302
- s = Math.imul(s, 1664525) + 1013904223 >>> 0;
303
- const j = version === 2 ? Math.floor(s / 4294967296 * (i + 1)) : s % (i + 1);
304
- [out[i], out[j]] = [out[j], out[i]];
305
- }
306
- 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;
307
267
  }
308
268
  function seededShuffle(items, seed, options = {}) {
309
- return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);
269
+ return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);
310
270
  }
311
-
312
- // src/item-group.ts
271
+ //#endregion
272
+ //#region src/item-group.ts
273
+ /** Narrows a sequence entry to an item group. */
313
274
  function isItemGroup(entry) {
314
- return entry.type === "item-group";
275
+ return entry.type === "item-group";
315
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
+ */
316
287
  function keyOf(entry) {
317
- const key = entry.slotKey;
318
- if (key === void 0) {
319
- return void 0;
320
- }
321
- if (typeof key !== "string" || key.length === 0) {
322
- throw new Error(
323
- `flattenSequence: slotKey must be a non-empty string, received ${String(key)}.`
324
- );
325
- }
326
- if (key.includes(".")) {
327
- throw new Error(
328
- `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.`
329
- );
330
- }
331
- 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;
332
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
+ */
333
301
  function inQuizOrder(items, timeline) {
334
- const placement = /* @__PURE__ */ new Map();
335
- timeline.cues.forEach((cue, cueIndex) => {
336
- cue.itemIds.forEach((itemId, position) => {
337
- if (!placement.has(itemId)) {
338
- placement.set(itemId, { at: cue.at, cue: cueIndex, position });
339
- }
340
- });
341
- });
342
- const unplaced = { at: Number.POSITIVE_INFINITY, cue: Number.POSITIVE_INFINITY, position: 0 };
343
- return items.map((entry) => ({ entry, place: placement.get(entry.item.id) ?? unplaced })).sort(
344
- (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
345
- ).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);
346
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
+ */
347
336
  function flattenSequence(entries, options = {}) {
348
- const shuffleEntries = options.shuffleEntries === true;
349
- const needsSeed = shuffleEntries || entries.some((entry) => isItemGroup(entry) && entry.shuffle === "within-group");
350
- if (needsSeed && options.seed === void 0) {
351
- throw new Error(
352
- '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.'
353
- );
354
- }
355
- const seed = options.seed ?? "";
356
- const authored = entries.map((entry, entryIndex) => ({ entry, entryIndex }));
357
- const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`) : authored;
358
- const slots = [];
359
- for (const { entry, entryIndex } of ordered) {
360
- const entryKey = keyOf(entry) ?? String(entryIndex);
361
- if (!isItemGroup(entry)) {
362
- slots.push({ slotId: entryKey, index: slots.length, activity: entry });
363
- continue;
364
- }
365
- if (entry.items.length === 0) {
366
- throw new Error(
367
- `flattenSequence: item group "${entry.id}" has no items. An empty group would silently remove its stimulus and its questions from the presented sequence.`
368
- );
369
- }
370
- const timeline = entry.timeline;
371
- if (timeline !== void 0 && entry.shuffle === "within-group") {
372
- throw new Error(
373
- `flattenSequence: item group "${entry.id}" has a timeline and shuffle: "within-group". An interactive video presents its questions in the order its quizzes open.`
374
- );
375
- }
376
- const items = entry.items.map((item, itemIndex) => ({ item, itemIndex }));
377
- const presented = timeline !== void 0 ? inQuizOrder(items, timeline) : entry.shuffle === "within-group" ? seededShuffle(items, `${seed}:group:${entry.id}`) : items;
378
- const size = presented.length;
379
- presented.forEach(({ item, itemIndex }, position) => {
380
- const cue = timeline?.cues.find((candidate) => candidate.itemIds.includes(item.id));
381
- slots.push({
382
- // Slot ids stay AUTHORED — the item's index or its key — whatever the
383
- // presented order: moving a quiz must never re-map a stored answer.
384
- slotId: `${entryKey}.${keyOf(item) ?? String(itemIndex)}`,
385
- index: slots.length,
386
- activity: item,
387
- group: {
388
- id: entry.id,
389
- ...entry.title !== void 0 ? { title: entry.title } : {},
390
- stimulus: entry.stimulus,
391
- position,
392
- size,
393
- ...timeline !== void 0 ? { timeline } : {},
394
- ...cue !== void 0 ? { cue } : {}
395
- }
396
- });
397
- });
398
- }
399
- const seenSlotIds = /* @__PURE__ */ new Set();
400
- const seenEntryKeys = /* @__PURE__ */ new Set();
401
- for (const slot of slots) {
402
- if (seenSlotIds.has(slot.slotId)) {
403
- throw new Error(
404
- `flattenSequence: duplicate slot id "${slot.slotId}". Two entries declare the same slotKey, so responses stored against them could not be told apart.`
405
- );
406
- }
407
- seenSlotIds.add(slot.slotId);
408
- }
409
- for (const { entry, entryIndex } of ordered) {
410
- const entryKey = keyOf(entry) ?? String(entryIndex);
411
- if (seenEntryKeys.has(entryKey)) {
412
- throw new Error(
413
- `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.`
414
- );
415
- }
416
- seenEntryKeys.add(entryKey);
417
- }
418
- 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;
419
395
  }
420
-
421
- // 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
+ */
422
405
  function entryKeyOf(slotId) {
423
- const dot = slotId.indexOf(".");
424
- return dot === -1 ? slotId : slotId.slice(0, dot);
406
+ const dot = slotId.indexOf(".");
407
+ return dot === -1 ? slotId : slotId.slice(0, dot);
425
408
  }
409
+ /** Budget key for an activity's OWN `data.media`. One budget per slot. */
426
410
  function slotMediaKey(slotId) {
427
- return `slot:${slotId}`;
411
+ return `slot:${slotId}`;
428
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
+ */
429
422
  function stimulusMediaKey(slotId) {
430
- return `stimulus:${entryKeyOf(slotId)}`;
423
+ return `stimulus:${entryKeyOf(slotId)}`;
431
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
+ */
432
432
  function resolvePlaybackPolicy(media) {
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
- const controls = p?.controls ?? (budgeted || seek === "none" || rate === "fixed" ? "minimal" : "native");
438
- return {
439
- controls,
440
- maxPlays: budgeted ? p?.maxPlays : null,
441
- seek,
442
- rate,
443
- nativeControlHints: p?.nativeControlHints ?? []
444
- };
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
+ };
445
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
+ */
446
452
  function planMediaBudgets(plan) {
447
- const out = {};
448
- for (const slot of plan.slots) {
449
- for (const budget of slot.mediaBudgets ?? []) {
450
- out[budget.key] = budget.maxPlays;
451
- }
452
- }
453
- 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;
454
456
  }
455
457
  function assertEntry(key, entry) {
456
- if (entry === null || typeof entry !== "object" || !Number.isInteger(entry.plays) || entry.plays < 0) {
457
- throw new Error(
458
- `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
- );
460
- }
461
- if (entry.at !== void 0 && (!Number.isFinite(entry.at) || entry.at < 0)) {
462
- throw new Error(
463
- `serializeMediaPlayLedger: position for ${JSON.stringify(key)} is ${JSON.stringify(entry.at)}. A position must be a finite number of seconds >= 0.`
464
- );
465
- }
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.`);
466
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
+ */
467
472
  function serializeMediaPlayLedger(plan, entries, options = {}) {
468
- if (entries === null || typeof entries !== "object") {
469
- throw new Error("serializeMediaPlayLedger: entries must be an object keyed by media key.");
470
- }
471
- const budgets = planMediaBudgets(plan);
472
- const out = {};
473
- for (const key of Object.keys(entries)) {
474
- if (!Object.hasOwn(budgets, key)) {
475
- throw new Error(
476
- `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.`
477
- );
478
- }
479
- const entry = entries[key];
480
- assertEntry(key, entry);
481
- out[key] = { plays: entry.plays, ...entry.at !== void 0 ? { at: entry.at } : {} };
482
- }
483
- return {
484
- ledgerVersion: "1.0",
485
- planHash: plan.planHash,
486
- entries: out,
487
- ...options.savedAt !== void 0 ? { savedAt: options.savedAt } : {}
488
- };
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
+ };
489
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
+ */
490
504
  function restoreMediaPlayLedger(plan, stored) {
491
- if (stored === null || typeof stored !== "object") {
492
- throw new Error("restoreMediaPlayLedger: the stored ledger is not an object.");
493
- }
494
- if (stored.ledgerVersion !== "1.0") {
495
- throw new Error(
496
- `restoreMediaPlayLedger: unsupported ledgerVersion ${JSON.stringify(stored.ledgerVersion)}. This build understands "1.0"; a newer ledger must be migrated before it is restored.`
497
- );
498
- }
499
- if (stored.entries === null || typeof stored.entries !== "object") {
500
- throw new Error(
501
- "restoreMediaPlayLedger: the ledger carries no entries object (a NULL column, or a partially written row)."
502
- );
503
- }
504
- if (stored.planHash !== plan.planHash) {
505
- throw new Error(
506
- `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.`
507
- );
508
- }
509
- return serializeMediaPlayLedger(plan, stored.entries, {
510
- ...stored.savedAt !== void 0 ? { savedAt: stored.savedAt } : {}
511
- });
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 } : {} });
512
510
  }
513
-
514
- // 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
+ */
515
521
  function contentOf(activity) {
516
- if (!Object.hasOwn(activity, "slotKey")) {
517
- return activity;
518
- }
519
- const { slotKey: _slotKey, ...content } = activity;
520
- return content;
522
+ if (!Object.hasOwn(activity, "slotKey")) return activity;
523
+ const { slotKey: _slotKey, ...content } = activity;
524
+ return content;
521
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
+ */
522
532
  function mediaBudgetsOf(slot) {
523
- const budgets = [];
524
- const own = slot.activity.media;
525
- if (own !== void 0) {
526
- const maxPlays = resolvePlaybackPolicy(own).maxPlays;
527
- if (maxPlays !== null) {
528
- budgets.push({ key: slotMediaKey(slot.slotId), maxPlays });
529
- }
530
- }
531
- const stimulusMedia = slot.group?.stimulus.media;
532
- if (stimulusMedia !== void 0) {
533
- const maxPlays = resolvePlaybackPolicy(stimulusMedia).maxPlays;
534
- if (maxPlays !== null) {
535
- budgets.push({ key: stimulusMediaKey(slot.slotId), maxPlays });
536
- }
537
- }
538
- 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;
539
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
+ */
540
561
  function assertNoSplitBudgets(slots) {
541
- const keysByUrl = /* @__PURE__ */ new Map();
542
- for (const slot of slots) {
543
- const own = slot.activity.media;
544
- if (own === void 0 || resolvePlaybackPolicy(own).maxPlays === null) {
545
- continue;
546
- }
547
- const keys = keysByUrl.get(own.url) ?? [];
548
- keys.push(slotMediaKey(slot.slotId));
549
- keysByUrl.set(own.url, keys);
550
- }
551
- for (const [url, keys] of keysByUrl) {
552
- if (keys.length > 1) {
553
- throw new Error(
554
- `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.`
555
- );
556
- }
557
- }
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.`);
558
571
  }
559
572
  function planSlot(slot, points) {
560
- if (!Number.isFinite(points) || points < 0) {
561
- throw new Error(
562
- `planAttempt: slot "${slot.slotId}" resolved to ${String(points)} points. Points must be a finite, non-negative number, or the paper has no defensible total.`
563
- );
564
- }
565
- const mediaBudgets = mediaBudgetsOf(slot);
566
- return {
567
- slotId: slot.slotId,
568
- index: slot.index,
569
- activityId: slot.activity.id,
570
- activityType: slot.activity.type,
571
- points,
572
- contentHash: contentHash(contentOf(slot.activity)),
573
- ...slot.group !== void 0 ? {
574
- group: {
575
- id: slot.group.id,
576
- ...slot.group.title !== void 0 ? { title: slot.group.title } : {},
577
- stimulusHash: contentHash(slot.group.stimulus),
578
- ...slot.group.cue !== void 0 ? {
579
- cue: {
580
- id: slot.group.cue.id,
581
- at: slot.group.cue.at,
582
- ...slot.group.cue.required !== void 0 ? { required: slot.group.cue.required } : {}
583
- }
584
- } : {}
585
- }
586
- } : {},
587
- ...mediaBudgets !== void 0 ? { mediaBudgets } : {}
588
- };
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
+ };
589
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
+ */
590
611
  function planAttempt(entries, options = {}) {
591
- const { seed, shuffleEntries, points } = options;
592
- const delivery = frozenDelivery(options.delivery);
593
- const scoring = frozenScoring(options.scoring);
594
- const slots = flattenSequence(entries, {
595
- ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
596
- ...seed !== void 0 ? { seed } : {}
597
- });
598
- assertNoSplitBudgets(slots);
599
- const planned = slots.map((slot) => planSlot(slot, points?.(slot) ?? 1));
600
- const totalPoints = planned.reduce((sum, slot) => sum + slot.points, 0);
601
- return {
602
- planVersion: "1.0",
603
- ...seed !== void 0 ? { seed } : {},
604
- ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
605
- // The plan's own fingerprint covers the slots verbatim — identity, order,
606
- // points and content hashes — so one stored value answers "is this still
607
- // the paper that was sat?" and the per-slot hashes then say what moved.
608
- // A policy joins it when there is one: the same paper sat with hints and
609
- // without is two different attempts. Without one, the fingerprint is the
610
- // one every plan before policies had.
611
- // So does a scoring policy: the same answers are worth something else when
612
- // a hint costs a tenth of the marks. Each joins only when it is there, so
613
- // a plan with neither — or with a delivery policy alone — keeps the
614
- // fingerprint it always had.
615
- planHash: contentHash(
616
- delivery === void 0 && scoring === void 0 ? planned : {
617
- slots: planned,
618
- ...delivery !== void 0 ? { delivery } : {},
619
- ...scoring !== void 0 ? { scoring } : {}
620
- }
621
- ),
622
- ...delivery !== void 0 ? { delivery } : {},
623
- ...scoring !== void 0 ? { scoring } : {},
624
- slots: planned,
625
- totalPoints
626
- };
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
+ };
627
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
+ */
628
661
  function verifyAttemptPlan(plan, current) {
629
- const before = new Map(plan.slots.map((slot) => [slot.slotId, slot]));
630
- const after = new Map(current.slots.map((slot) => [slot.slotId, slot]));
631
- const missingSlotIds = plan.slots.filter((s) => !after.has(s.slotId)).map((s) => s.slotId);
632
- const addedSlotIds = current.slots.filter((s) => !before.has(s.slotId)).map((s) => s.slotId);
633
- const changedSlotIds = [];
634
- const changedStimulusSlotIds = [];
635
- const changedCueSlotIds = [];
636
- const changedPointsSlotIds = [];
637
- const reorderedSlotIds = [];
638
- const deliveryChanged = contentHash(plan.delivery ?? null) !== contentHash(current.delivery ?? null);
639
- const scoringChanged = contentHash(plan.scoring ?? null) !== contentHash(current.scoring ?? null);
640
- for (const slot of plan.slots) {
641
- const now = after.get(slot.slotId);
642
- if (now === void 0) {
643
- continue;
644
- }
645
- if (now.contentHash !== slot.contentHash) {
646
- changedSlotIds.push(slot.slotId);
647
- }
648
- if (now.group?.stimulusHash !== slot.group?.stimulusHash) {
649
- changedStimulusSlotIds.push(slot.slotId);
650
- }
651
- if (contentHash(now.group?.cue ?? null) !== contentHash(slot.group?.cue ?? null)) {
652
- changedCueSlotIds.push(slot.slotId);
653
- }
654
- if (now.points !== slot.points) {
655
- changedPointsSlotIds.push(slot.slotId);
656
- }
657
- if (now.index !== slot.index) {
658
- reorderedSlotIds.push(slot.slotId);
659
- }
660
- }
661
- return {
662
- matches: missingSlotIds.length === 0 && addedSlotIds.length === 0 && changedSlotIds.length === 0 && changedStimulusSlotIds.length === 0 && changedCueSlotIds.length === 0 && changedPointsSlotIds.length === 0 && reorderedSlotIds.length === 0 && !deliveryChanged && !scoringChanged,
663
- missingSlotIds,
664
- addedSlotIds,
665
- changedSlotIds,
666
- changedStimulusSlotIds,
667
- changedCueSlotIds,
668
- changedPointsSlotIds,
669
- reorderedSlotIds,
670
- // Present only when it is true, as `rejectedSlotIds` is on a composed
671
- // score: a drift report between two plans without a policy — every one
672
- // written before policies existed — keeps exactly the shape it had.
673
- ...deliveryChanged ? { deliveryChanged: true } : {},
674
- ...scoringChanged ? { scoringChanged: true } : {}
675
- };
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
+ };
676
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
+ */
677
699
  function frozenDelivery(policy) {
678
- if (policy === void 0 || policy === null) {
679
- return void 0;
680
- }
681
- const checked = validateDeliveryPolicy(policy);
682
- if (!checked.success) {
683
- const first = checked.issues[0];
684
- throw new Error(
685
- `planAttempt: the delivery policy is not one to record \u2014 ${first?.message ?? "invalid"}` + (checked.issues.length > 1 ? ` (and ${checked.issues.length - 1} more)` : "")
686
- );
687
- }
688
- 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);
689
707
  }
708
+ /** The scoring policy a plan records, as {@link frozenDelivery} records a delivery policy. */
690
709
  function frozenScoring(policy) {
691
- if (policy === void 0 || policy === null) {
692
- return void 0;
693
- }
694
- const checked = validateItemScoringPolicy(policy);
695
- if (!checked.success) {
696
- const first = checked.issues[0];
697
- throw new Error(
698
- `planAttempt: the scoring policy is not one to record \u2014 ${first?.message ?? "invalid"}` + (checked.issues.length > 1 ? ` (and ${checked.issues.length - 1} more)` : "")
699
- );
700
- }
701
- 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);
702
717
  }
703
718
  function missingOutcome(slot, policy) {
704
- if (typeof policy === "function") {
705
- return policy(slot);
706
- }
707
- if (policy === "zero") {
708
- return { status: "scored", score: 0, maxScore: 1, passed: false, feedback: null, details: [] };
709
- }
710
- 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
+ };
711
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
+ */
712
754
  function scoredItemsFromPlan(plan, outcomes, options = {}) {
713
- const policy = options.missing ?? "deferred";
714
- return plan.slots.map((slot) => ({
715
- slotId: slot.slotId,
716
- activityId: slot.activityId,
717
- points: slot.points,
718
- // `Object.hasOwn`, not a bare lookup: slot ids come from authored
719
- // `slotKey`s, and a key of `constructor` or `toString` would otherwise
720
- // resolve through the prototype chain and hand a FUNCTION to the scorer
721
- // in place of an outcome.
722
- outcome: Object.hasOwn(outcomes, slot.slotId) ? outcomes[slot.slotId] : missingOutcome(slot, policy)
723
- }));
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
+ }));
724
762
  }
725
-
726
- // 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
+ */
727
777
  function cloneResponses(responses) {
728
- return typeof structuredClone === "function" ? structuredClone(responses) : JSON.parse(JSON.stringify(responses));
778
+ return typeof structuredClone === "function" ? structuredClone(responses) : JSON.parse(JSON.stringify(responses));
729
779
  }
780
+ /** Slot ids present in the object but unknown to the plan. */
730
781
  function unknownKeys(plan, keys) {
731
- const known = new Set(plan.slots.map((slot) => slot.slotId));
732
- 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));
733
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
+ */
734
799
  function serializeAttemptState(plan, progress) {
735
- const responseKeys = Object.keys(progress.responses);
736
- const submittedSlotIds = [...progress.submittedSlotIds ?? []];
737
- const strayResponses = unknownKeys(plan, responseKeys);
738
- if (strayResponses.length > 0) {
739
- throw new Error(
740
- `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.`
741
- );
742
- }
743
- const straySubmitted = unknownKeys(plan, submittedSlotIds);
744
- if (straySubmitted.length > 0) {
745
- throw new Error(
746
- `serializeAttemptState: submitted slot(s) the plan does not contain: ${straySubmitted.join(", ")}.`
747
- );
748
- }
749
- const index = progress.index ?? 0;
750
- const lastIndex = Math.max(0, plan.slots.length - 1);
751
- if (!Number.isInteger(index) || index < 0 || index > lastIndex) {
752
- throw new Error(
753
- `serializeAttemptState: index ${String(index)} is not a position in a ${plan.slots.length}-slot plan.`
754
- );
755
- }
756
- return {
757
- stateVersion: "1.0",
758
- planHash: plan.planHash,
759
- // Copied DEEPLY, not aliased: a snapshot that keeps mutating with the
760
- // live attempt is not a snapshot. See cloneResponses.
761
- responses: cloneResponses(progress.responses),
762
- submittedSlotIds,
763
- index,
764
- ...progress.savedAt !== void 0 ? { savedAt: progress.savedAt } : {}
765
- };
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
+ };
766
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
+ */
767
831
  function restoreAttemptState(plan, state) {
768
- if (state === null || typeof state !== "object") {
769
- throw new Error("restoreAttemptState: the snapshot is not an object.");
770
- }
771
- if (state.stateVersion !== "1.0") {
772
- throw new Error(
773
- `restoreAttemptState: unsupported stateVersion ${JSON.stringify(state.stateVersion)}. This build understands "1.0"; a newer snapshot must be migrated before it is restored.`
774
- );
775
- }
776
- if (state.responses === null || typeof state.responses !== "object") {
777
- throw new Error(
778
- "restoreAttemptState: the snapshot carries no responses object (a NULL column, or a partially written row)."
779
- );
780
- }
781
- if (state.planHash !== plan.planHash) {
782
- throw new Error(
783
- `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.`
784
- );
785
- }
786
- return serializeAttemptState(plan, {
787
- responses: state.responses,
788
- submittedSlotIds: state.submittedSlotIds,
789
- index: state.index,
790
- ...state.savedAt !== void 0 ? { savedAt: state.savedAt } : {}
791
- });
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
+ });
792
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
+ */
793
854
  function diffResponses(before, after) {
794
- const slotIds = [.../* @__PURE__ */ new Set([...Object.keys(before.responses), ...Object.keys(after.responses)])];
795
- slotIds.sort();
796
- const entries = [];
797
- for (const slotId of slotIds) {
798
- const had = Object.hasOwn(before.responses, slotId);
799
- const has = Object.hasOwn(after.responses, slotId);
800
- const from = before.responses[slotId];
801
- const to = after.responses[slotId];
802
- if (had && !has) {
803
- entries.push({ slotId, change: "removed", ...from !== void 0 ? { before: from } : {} });
804
- continue;
805
- }
806
- if (!had && has) {
807
- entries.push({ slotId, change: "added", ...to !== void 0 ? { after: to } : {} });
808
- continue;
809
- }
810
- if (canonicalJson(from) !== canonicalJson(to)) {
811
- entries.push({
812
- slotId,
813
- change: "changed",
814
- ...from !== void 0 ? { before: from } : {},
815
- ...to !== void 0 ? { after: to } : {}
816
- });
817
- }
818
- }
819
- return entries;
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;
820
887
  }
821
-
822
- // src/redact.ts
888
+ //#endregion
889
+ //#region src/redact.ts
890
+ /** Merges per-call overrides over a registered policy, one level deep. */
823
891
  function mergePolicy(base, overrides) {
824
- if (overrides === void 0) {
825
- return base;
826
- }
827
- const merged = { ...base };
828
- for (const [key, override] of Object.entries(overrides)) {
829
- const current = merged[key];
830
- merged[key] = typeof override === "object" && typeof current === "object" ? { ...current, ...override } : override;
831
- }
832
- 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;
833
902
  }
834
903
  function isSensitivity(value) {
835
- return typeof value === "string";
904
+ return typeof value === "string";
836
905
  }
837
906
  function keepField(sensitivity, reveal) {
838
- if (sensitivity === "public") {
839
- return true;
840
- }
841
- return sensitivity === "answer-key" && reveal === "after-submit";
907
+ if (sensitivity === "public") return true;
908
+ return sensitivity === "answer-key" && reveal === "after-submit";
842
909
  }
910
+ /** An object projection that kept no fields at all. Arrays are never dropped. */
843
911
  function isEmptyObject(value) {
844
- 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;
845
913
  }
846
914
  function redactValue(value, policy, reveal) {
847
- if (Array.isArray(value)) {
848
- return value.map((element) => redactValue(element, policy, reveal));
849
- }
850
- if (value === null || typeof value !== "object") {
851
- return void 0;
852
- }
853
- const source = value;
854
- const output = {};
855
- for (const [key, fieldValue] of Object.entries(source)) {
856
- if (fieldValue === void 0) {
857
- continue;
858
- }
859
- const classification = policy[key];
860
- if (classification === void 0) {
861
- continue;
862
- }
863
- if (isSensitivity(classification)) {
864
- if (keepField(classification, reveal)) {
865
- output[key] = fieldValue;
866
- }
867
- continue;
868
- }
869
- const nested = redactValue(fieldValue, classification, reveal);
870
- if (nested !== void 0 && !isEmptyObject(nested)) {
871
- output[key] = nested;
872
- }
873
- }
874
- 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;
875
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
+ */
876
947
  function redact(data, options = {}) {
877
- const reveal = options.reveal ?? "none";
878
- const descriptor = getActivityTypeDescriptor(data.type);
879
- if (descriptor === void 0) {
880
- throw new UnknownActivityTypeError(String(data.type));
881
- }
882
- if (descriptor.fieldPolicy === void 0) {
883
- throw new Error(
884
- `Activity type "${descriptor.type}" has no fieldPolicy; redact() cannot run fail-closed redaction without one.`
885
- );
886
- }
887
- const effectivePolicy = mergePolicy(descriptor.fieldPolicy, options.policy);
888
- const projected = redactValue(data, effectivePolicy, reveal);
889
- const result = { ...projected, redacted: true };
890
- if (reveal === "none" && descriptor.redactedSchema !== void 0) {
891
- const parsed = readSchema(
892
- descriptor.redactedSchema,
893
- result,
894
- `Activity type "${descriptor.type}"`
895
- );
896
- if (!parsed.success) {
897
- throw new ActivitySchemaError(
898
- descriptor.type,
899
- parsed.issues.map((issue) => ({
900
- path: issue.path.map(String),
901
- message: issue.message,
902
- code: issue.code
903
- }))
904
- );
905
- }
906
- }
907
- 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;
908
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
+ */
909
973
  function assertRedacted(data) {
910
- if (typeof data !== "object" || data === null) {
911
- throw new ActivitySchemaError("unknown", [
912
- { path: [], message: "Redacted activity data must be an object.", code: "invalid_type" }
913
- ]);
914
- }
915
- const candidate = data;
916
- if (candidate.redacted !== true) {
917
- throw new ActivitySchemaError(String(candidate.type ?? "unknown"), [
918
- {
919
- path: ["redacted"],
920
- message: "Missing redacted marker \u2014 this payload is not a redact() projection.",
921
- code: "custom"
922
- }
923
- ]);
924
- }
925
- const type = typeof candidate.type === "string" ? candidate.type : "";
926
- const descriptor = getActivityTypeDescriptor(type);
927
- if (descriptor === void 0) {
928
- throw new UnknownActivityTypeError(type);
929
- }
930
- if (descriptor.redactedSchema === void 0) {
931
- throw new ActivitySchemaError(descriptor.type, [
932
- {
933
- path: [],
934
- message: `Activity type "${descriptor.type}" registers no redactedSchema; assertRedacted cannot prove this payload is learner-safe.`,
935
- code: "custom"
936
- }
937
- ]);
938
- }
939
- const parsed = readSchema(
940
- descriptor.redactedSchema,
941
- candidate,
942
- `Activity type "${descriptor.type}"`
943
- );
944
- if (!parsed.success) {
945
- throw new ActivitySchemaError(
946
- descriptor.type,
947
- parsed.issues.map((issue) => ({
948
- path: issue.path.map(String),
949
- message: issue.message,
950
- code: issue.code
951
- }))
952
- );
953
- }
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
+ })));
954
999
  }
955
- var STIMULUS_FIELD_POLICY = {
956
- id: "public",
957
- kind: "public",
958
- title: "public",
959
- body: "public",
960
- bodyHtml: "public",
961
- media: MEDIA_FIELD_POLICY,
962
- locale: "public",
963
- attribution: "public",
964
- transcript: "author-only"
965
- };
966
- var ITEM_GROUP_FIELD_POLICY = {
967
- schemaVersion: "public",
968
- type: "public",
969
- id: "public",
970
- title: "public",
971
- // See the note on the built-in activity policies: a slot key is identity,
972
- // and identity has to cross the redaction boundary intact.
973
- slotKey: "public",
974
- shuffle: "public",
975
- stimulus: STIMULUS_FIELD_POLICY,
976
- // Public, and classified key by key rather than as one leaf: the learner's
977
- // player needs every part of it, none of it is a key — and a leaf would hand
978
- // over the author's object by reference, with whatever else was parked in it.
979
- timeline: {
980
- // Applies to every element of the array.
981
- cues: {
982
- id: "public",
983
- at: "public",
984
- itemIds: "public",
985
- title: "public",
986
- required: "public"
987
- },
988
- chapters: {
989
- at: "public",
990
- title: "public"
991
- },
992
- navigation: "public"
993
- }
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
+ }
994
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
+ */
995
1044
  function redactItemGroup(group, options = {}) {
996
- const reveal = options.reveal ?? "none";
997
- const { items, ...container } = group;
998
- const projected = redactValue(container, ITEM_GROUP_FIELD_POLICY, reveal);
999
- const result = {
1000
- ...projected,
1001
- items: items.map((item) => redact(item, options)),
1002
- redacted: true
1003
- };
1004
- if (reveal === "none") {
1005
- const parsed = RedactedItemGroupSchema.safeParse(result);
1006
- if (!parsed.success) {
1007
- throw new ActivitySchemaError(
1008
- "item-group",
1009
- parsed.error.issues.map((issue) => ({
1010
- path: issue.path.map(String),
1011
- message: issue.message,
1012
- code: issue.code
1013
- }))
1014
- );
1015
- }
1016
- }
1017
- 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;
1018
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
+ */
1019
1070
  function assertRedactedItemGroup(data) {
1020
- if (typeof data !== "object" || data === null) {
1021
- throw new ActivitySchemaError("item-group", [
1022
- { path: [], message: "Redacted item group must be an object.", code: "invalid_type" }
1023
- ]);
1024
- }
1025
- const candidate = data;
1026
- if (candidate.redacted !== true) {
1027
- throw new ActivitySchemaError("item-group", [
1028
- {
1029
- path: ["redacted"],
1030
- message: "Missing redacted marker \u2014 this payload is not a redactItemGroup() projection.",
1031
- code: "custom"
1032
- }
1033
- ]);
1034
- }
1035
- const parsed = RedactedItemGroupSchema.safeParse(candidate);
1036
- if (!parsed.success) {
1037
- throw new ActivitySchemaError(
1038
- "item-group",
1039
- parsed.error.issues.map((issue) => ({
1040
- path: issue.path.map(String),
1041
- message: issue.message,
1042
- code: issue.code
1043
- }))
1044
- );
1045
- }
1046
- parsed.data.items.forEach((item, index) => {
1047
- try {
1048
- assertRedacted(item);
1049
- } catch (error) {
1050
- if (error instanceof ActivitySchemaError) {
1051
- throw new ActivitySchemaError(
1052
- "item-group",
1053
- error.errors.map((issue) => ({
1054
- ...issue,
1055
- path: ["items", String(index), ...issue.path]
1056
- }))
1057
- );
1058
- }
1059
- throw error;
1060
- }
1061
- });
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
+ });
1062
1103
  }
1063
-
1064
- // 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
+ */
1065
1117
  function readMediaProgress(value, duration) {
1066
- let version;
1067
- let at;
1068
- let furthest;
1069
- try {
1070
- if (typeof value !== "object" || value === null) {
1071
- return null;
1072
- }
1073
- ({ progressVersion: version, at, furthest } = value);
1074
- } catch {
1075
- return null;
1076
- }
1077
- if (version !== "1.0" || typeof at !== "number" || !Number.isFinite(at)) {
1078
- return null;
1079
- }
1080
- const end = typeof duration === "number" && Number.isFinite(duration) && duration >= 0 ? duration : Number.POSITIVE_INFINITY;
1081
- const clampedAt = Math.min(Math.max(0, at), end);
1082
- const reached = typeof furthest === "number" && Number.isFinite(furthest) ? furthest : clampedAt;
1083
- return {
1084
- progressVersion: "1.0",
1085
- at: clampedAt,
1086
- furthest: Math.min(Math.max(clampedAt, reached), end)
1087
- };
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
+ };
1088
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
+ */
1089
1150
  function composeTimelineScore(entryKey, items, policy) {
1090
- const own = items.filter((item) => entryKeyOf(item.slotId) === entryKey);
1091
- if (own.length === 0) {
1092
- throw new Error(
1093
- `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.`
1094
- );
1095
- }
1096
- 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);
1097
1158
  }
1098
- export {
1099
- AI_COACHING_MAX_TIP_LENGTH,
1100
- AI_COACHING_MAX_WORDS,
1101
- AI_CRITIQUE_MAX_FIELD_LENGTH,
1102
- AI_CRITIQUE_MAX_FINDINGS,
1103
- AI_DRAFTS_MAX_COUNT,
1104
- AI_DRAFTS_MAX_REPAIRS,
1105
- AI_EXPLANATION_TYPES,
1106
- AI_HINT_TYPES,
1107
- AI_TEXT_MAX_LENGTH,
1108
- AI_WRITING_MAX_CORRECTIONS,
1109
- AI_WRITING_MAX_FIELD_LENGTH,
1110
- ActivitySchemaError,
1111
- DEFAULT_ITEM_SCORING_POLICY,
1112
- DEFAULT_PASS_THRESHOLD,
1113
- DICTATION_MAX_ACCEPTED_TRANSCRIPTS,
1114
- DICTATION_MAX_EQUIVALENCES,
1115
- DICTATION_MAX_EQUIVALENCE_LENGTH,
1116
- DICTATION_MAX_TEXT_LENGTH,
1117
- DICTATION_MAX_TRANSCRIPT_LENGTH,
1118
- DeferredScoringError,
1119
- INTERACTIVE_VIDEO_ITEM_TYPES,
1120
- ITEM_SCORING_MAX_RETRIES,
1121
- OPEN_DELIVERY_POLICY,
1122
- READ_ALOUD_MAX_DIMENSION_WEIGHT,
1123
- READ_ALOUD_MAX_REFERENCE_LENGTH,
1124
- READ_ALOUD_MAX_SECONDS,
1125
- READ_ALOUD_MAX_TAKES,
1126
- RedactedScoringError,
1127
- SPEECH_ASSESSMENT_MAX_WORDS,
1128
- TIMELINE_MAX_CHAPTERS,
1129
- TIMELINE_MAX_ITEMS,
1130
- TIMELINE_MAX_QUIZZES,
1131
- TIMELINE_MAX_TITLE_LENGTH,
1132
- UnknownActivityTypeError,
1133
- XAPIVerb,
1134
- XAPI_VERB_DISPLAY,
1135
- aiAllowedByContent,
1136
- aiCoachingRequest,
1137
- aiCritiqueRequest,
1138
- aiDraftsRepairRequest,
1139
- aiDraftsRequest,
1140
- aiExplanationRequest,
1141
- aiGradeOf,
1142
- aiHintRequest,
1143
- aiSupports,
1144
- aiWritingFeedbackRequest,
1145
- alignDictation,
1146
- alignReadAloud,
1147
- assertRedacted,
1148
- assertRedactedItemGroup,
1149
- buildAiFacts,
1150
- canonicalJson,
1151
- checkAiCoaching,
1152
- checkAiCritique,
1153
- checkAiDrafts,
1154
- checkAiExplanation,
1155
- checkAiHint,
1156
- checkAiWritingFeedback,
1157
- classifyBand,
1158
- combineDeliveryPolicies,
1159
- composeAssessmentScore,
1160
- composeTimelineScore,
1161
- computePassThreshold,
1162
- contentHash,
1163
- countWords,
1164
- createDraft,
1165
- createInteractiveVideoDraft,
1166
- createItemGroupDraft,
1167
- critiqueDraft,
1168
- critiqueDrafts,
1169
- critiqueItemGroupDraft,
1170
- defineActivityType,
1171
- dictationJsonSchema,
1172
- dictationReferenceWords,
1173
- dictationType,
1174
- diffDictationChars,
1175
- diffResponses,
1176
- entryKeyOf,
1177
- evaluate,
1178
- evaluateTries,
1179
- fillInTheBlanksJsonSchema,
1180
- fillInTheBlanksType,
1181
- fingerprint,
1182
- flattenSequence,
1183
- gapSelectJsonSchema,
1184
- gapSelectType,
1185
- generateDrafts,
1186
- getActivityTypeDescriptor,
1187
- gradeFromRubric,
1188
- gradeReadAloud,
1189
- gte,
1190
- hasGrade,
1191
- hashSeed,
1192
- hintRevealsAnswer,
1193
- inspectWav,
1194
- interactiveVideoFromDrafts,
1195
- isInteractiveVideoItemType,
1196
- isItemGroup,
1197
- itemGroupJsonSchema,
1198
- jsonSchemaFor,
1199
- levenshteinDistance,
1200
- matchText,
1201
- multipleChoiceJsonSchema,
1202
- multipleChoiceType,
1203
- outcomeFromGrade,
1204
- outcomeFromUnscorable,
1205
- planAttempt,
1206
- planMediaBudgets,
1207
- readAiTextResult,
1208
- readAloudJsonSchema,
1209
- readAloudType,
1210
- readMediaProgress,
1211
- redact,
1212
- redactItemGroup,
1213
- registerActivityType,
1214
- registeredActivityTypes,
1215
- resolveDeliveryPolicy,
1216
- resolveItemScoringPolicy,
1217
- resolvePlaybackPolicy,
1218
- restoreAttemptState,
1219
- restoreMediaPlayLedger,
1220
- roundGrade,
1221
- score,
1222
- scoreTries,
1223
- scoredItemsFromPlan,
1224
- seededShuffle,
1225
- serializeAttemptState,
1226
- serializeMediaPlayLedger,
1227
- slotMediaKey,
1228
- stimulusJsonSchema,
1229
- stimulusMediaKey,
1230
- validateActivity,
1231
- validateDeliveryPolicy,
1232
- validateDraft,
1233
- validateItemGroup,
1234
- validateItemGroupDraft,
1235
- validateItemScoringPolicy,
1236
- validateMedia,
1237
- validateOptionMedia,
1238
- validateSpeechAssessment,
1239
- validateXAPIStatement,
1240
- verifyAttemptPlan,
1241
- writtenResponseJsonSchema,
1242
- writtenResponseType,
1243
- xAPIBuilder,
1244
- xapiDefinitionFor
1245
- };
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_MATERIAL_MAX_LENGTH, 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
+
1246
1162
  //# sourceMappingURL=index.js.map