@intellectif/lk-core 0.13.0 → 0.13.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/index.cjs","../src/content-hash.ts","../src/shuffle.ts","../src/item-group.ts","../src/media-budget.ts","../src/attempt-plan.ts","../src/attempt-state.ts","../src/authoring/item-group.ts","../src/authoring/index.ts","../src/redact.ts"],"names":["issue"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AC5FO,SAAS,aAAA,CAAc,KAAA,EAAgB,KAAA,kBAAoB,IAAI,GAAA,CAAI,CAAA,EAAW;AACnF,EAAA,GAAA,CAAI,MAAA,IAAU,IAAA,EAAM;AAClB,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,GAAA,CAAI,OAAO,MAAA,IAAU,QAAA,EAAU;AAK7B,IAAA,OAAO,MAAA,CAAO,QAAA,CAAS,KAAK,EAAA,EAAI,IAAA,CAAK,SAAA,CAAU,MAA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AACF,EAAA;AACO,EAAA;AACT;AN+ZoB;AACA;AOtkBJ;AACC,EAAA;AACD,EAAA;AACQ,IAAA;AACT,IAAA;AACC,MAAA;AACZ,IAAA;AACe,IAAA;AACH,MAAA;AACR,QAAA;AACF,MAAA;AACF,IAAA;AACa,IAAA;AACN,IAAA;AACT,EAAA;AACO,EAAA;AACU,IAAA;AACT,IAAA;AACI,IAAA;AACM,IAAA;AACR,IAAA;AACV,EAAA;AACF;AAsBgB;AAGP,EAAA;AACT;AAES;AACuB,EAAA;AAChB,EAAA;AACL,IAAA;AACC,MAAA;AACR,IAAA;AACS,IAAA;AACX,EAAA;AAEe,EAAA;AACF,EAAA;AACI,IAAA;AACN,EAAA;AACF,IAAA;AACL,MAAA;AACE,QAAA;AACW,QAAA;AACX,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACe,EAAA;AACX,EAAA;AACK,IAAA;AACL,MAAA;AACE,QAAA;AACC,QAAA;AACD,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AAKe,EAAA;AACH,EAAA;AACC,IAAA;AACI,MAAA;AACF,MAAA;AACT,QAAA;AACF,MAAA;AACS,MAAA;AACA,QAAA;AACL,UAAA;AACE,YAAA;AACA,YAAA;AACA,YAAA;AACF,UAAA;AACF,QAAA;AACA,QAAA;AACF,MAAA;AACY,MAAA;AACV,QAAA;AACS,QAAA;AACH,QAAA;AACI,QAAA;AACX,MAAA;AACH,IAAA;AACF,EAAA;AAEe,EAAA;AACJ,EAAA;AACA,IAAA;AACX,EAAA;AACW,EAAA;AAIE,IAAA;AACK,MAAA;AAChB,IAAA;AACF,EAAA;AACgB,EAAA;AACC,EAAA;AACnB;AAGS;AACuB,EAAA;AACpB,EAAA;AACD,IAAA;AACL,MAAA;AACE,QAAA;AACC,QAAA;AACD,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACU,EAAA;AACI,IAAA;AACd,EAAA;AACgB,EAAA;AACF,IAAA;AACd,EAAA;AACa,EAAA;AAC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;AACE,QAAA;AACH,QAAA;AACR,MAAA;AACD,IAAA;AACH,EAAA;AACe,EAAA;AACH,EAAA;AACA,IAAA;AACG,MAAA;AACE,MAAA;AACLA,QAAAA;AACGA,QAAAA;AACHA,QAAAA;AACN,MAAA;AACJ,IAAA;AACF,EAAA;AACF;AAQM;AACA,EAAA;AACE,EAAA;AACC,EAAA;AACD,EAAA;AACI,EAAA;AACH,EAAA;AACC,EAAA;AACK,EAAA;AACD,EAAA;AACd;AAGM;AACW,EAAA;AACT,EAAA;AACF,EAAA;AACG,EAAA;AAAA;AAAA;AAGE,EAAA;AACA,EAAA;AACC,EAAA;AACZ;AAegB;AAIC,EAAA;AACG,EAAA;AACA,EAAA;AAIH,EAAA;AACV,IAAA;AACU,IAAA;AACH,IAAA;AACZ,EAAA;AAEe,EAAA;AACE,IAAA;AACH,IAAA;AACA,MAAA;AACR,QAAA;AACO,QAAA;AACCA,UAAAA;AACGA,UAAAA;AACHA,UAAAA;AACN,QAAA;AACJ,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAUgB;AACH,EAAA;AACC,IAAA;AACI,MAAA;AACb,IAAA;AACH,EAAA;AACkB,EAAA;AACJ,EAAA;AACF,IAAA;AACR,MAAA;AACS,QAAA;AACE,QAAA;AACH,QAAA;AACR,MAAA;AACD,IAAA;AACH,EAAA;AACe,EAAA;AACH,EAAA;AACA,IAAA;AACR,MAAA;AACa,MAAA;AACLA,QAAAA;AACGA,QAAAA;AACHA,QAAAA;AACN,MAAA;AACJ,IAAA;AACF,EAAA;AACkB,EAAA;AACZ,IAAA;AACF,MAAA;AACc,IAAA;AACV,MAAA;AACQ,QAAA;AACR,UAAA;AACM,UAAA;AACDA,YAAAA;AACI,YAAA;AACP,UAAA;AACJ,QAAA;AACF,MAAA;AACM,MAAA;AACR,IAAA;AACD,EAAA;AACH;AT2yBoB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/index.cjs","sourcesContent":[null,"/**\n * Content fingerprinting — \"is this the same content the learner was served?\"\n *\n * A recorded attempt outlives the content it was taken against. Papers get\n * corrected, a typo is fixed, an option is reworded — and six months later a\n * remark, an appeal, or a per-item analysis is run against content that is no\n * longer what the learner saw. Nothing warns anybody, because the ids all still\n * match. A fingerprint stored with the attempt turns that silent drift into a\n * question somebody can answer.\n */\n\n/**\n * Deterministic JSON: object keys sorted, arrays left in order, `undefined`\n * omitted from objects (matching `JSON.stringify`) and rendered as `null`\n * inside arrays.\n *\n * Key order is the whole point. Two objects that differ only in the order\n * their keys happened to be written are the SAME content, and a fingerprint\n * that disagreed would raise a false alarm every time a payload made a\n * round-trip through a different serializer.\n */\nexport function canonicalJson(value: unknown, seen: Set<object> = new Set()): string {\n if (value === null) {\n return 'null';\n }\n if (typeof value === 'number') {\n // JSON.stringify renders every non-finite number as `null`, which would\n // fingerprint NaN, Infinity and -Infinity identically — and identically to\n // a real null. Content carrying one of those is already broken; it must at\n // least be distinguishable.\n return Number.isFinite(value) ? JSON.stringify(value === 0 ? 0 : value) : `\"#${String(value)}\"`;\n }\n if (typeof value === 'string' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n return `\"#${value.toString()}n\"`;\n }\n if (typeof value === 'object') {\n // A cycle would recurse until the stack gave out, and a stack overflow\n // while fingerprinting an exam is a far worse failure than being told the\n // content is not serialisable. Content is JSON, so this should never fire —\n // but \"should never\" is not a guard.\n if (seen.has(value)) {\n throw new Error(\n 'canonicalJson: the value contains a circular reference and cannot be fingerprinted.',\n );\n }\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return `[${value.map((element) => (element === undefined ? 'null' : canonicalJson(element, seen))).join(',')}]`;\n }\n const source = value as Record<string, unknown>;\n const parts: string[] = [];\n for (const key of Object.keys(source).sort()) {\n const entry = source[key];\n if (entry === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(key)}:${canonicalJson(entry, seen)}`);\n }\n return `{${parts.join(',')}}`;\n } finally {\n // Released on the way out, so a value legitimately appearing twice in\n // SIBLING positions is not mistaken for a cycle.\n seen.delete(value);\n }\n }\n // Functions, symbols and undefined have no place in content.\n return 'null';\n}\n\nconst FNV_OFFSET = 14695981039346656037n;\nconst FNV_PRIME = 1099511628211n;\nconst MASK64 = (1n << 64n) - 1n;\n\n/**\n * FNV-1a over the UTF-8 bytes of `input`, as 16 lowercase hex digits.\n *\n * **This is a change-detection fingerprint, not a tamper-evident signature.**\n * It is deterministic across runtimes and dependency-free, which is what makes\n * it usable in a stored grade record — but an adversary who can edit content\n * can also, with effort, preserve the fingerprint. If you need the stronger\n * property, sign the plan with a key the content author does not hold; this\n * exists to catch honest edits, which is what actually happens.\n */\nexport function fingerprint(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let hash = FNV_OFFSET;\n for (const byte of bytes) {\n hash = ((hash ^ BigInt(byte)) * FNV_PRIME) & MASK64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n\n/**\n * Fingerprints any JSON-serialisable value through {@link canonicalJson}, so\n * the result depends on the content and not on how it was written.\n */\nexport function contentHash(value: unknown): string {\n return fingerprint(canonicalJson(value));\n}\n","/**\n * Seeded, deterministic shuffling — the ONE algorithm every presentation-order\n * decision in the SDK goes through: option order in a multiple-choice item,\n * item order inside an item group, entry order in a sequence. A server and a\n * client holding the same seed derive the same order, and an order recorded\n * against an attempt can be rebuilt later from nothing but its seed.\n *\n * STABILITY: the hash and the generator are part of the wire contract. A\n * stored attempt may hold only a seed and rely on this function to reproduce\n * the order it presented; changing either would silently re-order every\n * recorded attempt. Any change here is a package major, and the pinned\n * permutation test exists so an accidental one fails loudly.\n */\n\n/** FNV-1a hash of a string → unsigned 32-bit integer. */\nexport function hashSeed(input: string): number {\n let h = 2166136261 >>> 0;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 16777619) >>> 0;\n }\n return h;\n}\n\n/**\n * Which draw the Fisher–Yates step uses.\n *\n * - `1` — the original. Takes the index from the LCG's LOW bits (`s % (i+1)`).\n * - `2` — takes it from the HIGH bits. Same LCG, same seed, different draw.\n *\n * The difference is not cosmetic. In a linear congruential generator with a\n * power-of-two modulus, the low bits have drastically short periods: bit 0\n * alternates, bit 1 has period 4, and so on. `% (i+1)` reads exactly those\n * bits, so consecutive draws are correlated and most permutations become\n * unreachable FOR EVERY SEED THAT WILL EVER EXIST:\n *\n * | items | permutations | reachable under v1 | under v2 |\n * | ----- | ------------ | ------------------ | -------- |\n * | 4 | 24 | 12 | 24 |\n * | 5 | 120 | 60 | 120 |\n * | 6 | 720 | 180 | 720 |\n *\n * It also biases WHERE an option lands. On a four-option item under v1 the\n * last authored option takes the first presented position 8.3% of the time\n * and the second position 41.7%, against 25% each — a systematic advantage to\n * anyone who notices. For a summative exam that is a fairness defect, not a\n * curiosity.\n *\n * v1 remains the DEFAULT regardless, because these permutations are a wire\n * contract: an attempt may be stored with nothing but its seed, and a review\n * render of that attempt has to reproduce the order the learner actually saw.\n * Switching the default would silently re-order every recorded attempt, so it\n * is a package major — scheduled, not smuggled in. Choose v2 for new content\n * where no attempt has been recorded yet.\n */\nexport type ShuffleVersion = 1 | 2;\n\n/** Options for {@link seededShuffle}. */\nexport interface SeededShuffleOptions {\n /** Draw algorithm. Defaults to `1` — see {@link ShuffleVersion}. */\n version?: ShuffleVersion;\n}\n\n/** LCG-driven Fisher–Yates over a 32-bit seed; returns a permutation (no loss, no duplicate). */\nfunction shuffleWithSeed<T>(items: readonly T[], seed: number, version: ShuffleVersion): T[] {\n const out = [...items];\n let s = seed >>> 0 || 1;\n for (let i = out.length - 1; i > 0; i -= 1) {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n // v1 reads the low bits; v2 scales the whole 32-bit word, which uses the\n // high bits and reaches every permutation.\n const j = version === 2 ? Math.floor((s / 4294967296) * (i + 1)) : s % (i + 1);\n [out[i], out[j]] = [out[j] as T, out[i] as T];\n }\n return out;\n}\n\n/**\n * Returns a new array holding a permutation of `items` determined entirely by\n * `seed` (and the chosen {@link ShuffleVersion}): same inputs, same order —\n * across processes, runtimes and releases. The input is never mutated.\n *\n * Compose the seed from the attempt identity AND the thing being shuffled\n * (`${attemptId}:${itemId}`), so two shuffles in one attempt do not share an\n * order.\n */\nexport function seededShuffle<T>(\n items: readonly T[],\n seed: string,\n options: SeededShuffleOptions = {},\n): T[] {\n return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);\n}\n","import { seededShuffle } from './shuffle.js';\nimport type { ItemGroup, SequenceEntry, SequenceSlot } from './types/item-group.js';\n\n/** Narrows a sequence entry to an item group. */\nexport function isItemGroup<TItem extends { type: string }>(\n entry: SequenceEntry<TItem>,\n): entry is ItemGroup<TItem> {\n return entry.type === 'item-group';\n}\n\n/**\n * An entry's declared `slotKey`, if it has one. Read structurally rather than\n * from the type, because a plain activity may carry one too — `slotKey` is a\n * property of an item's PLACE in a paper, so any entry can declare it without\n * every activity schema having to know about assessment assembly.\n *\n * A key containing `.` is rejected: `.` separates a group from its item in a\n * slot id, so `\"a.b\"` as a group key would be indistinguishable from item `b`\n * of group `a`.\n */\nfunction keyOf(entry: unknown): string | undefined {\n const key = (entry as { slotKey?: unknown }).slotKey;\n if (key === undefined) {\n return undefined;\n }\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `flattenSequence: slotKey must be a non-empty string, received ${String(key)}.`,\n );\n }\n if (key.includes('.')) {\n throw new Error(\n `flattenSequence: slotKey \"${key}\" contains a \".\" , which separates a group from its item ` +\n 'in a slot id. Choose a key without it, or the two become indistinguishable.',\n );\n }\n return key;\n}\n\n/** Options for {@link flattenSequence}. */\nexport interface FlattenSequenceOptions {\n /**\n * Shuffle the top-level entries. A group moves as ONE block — its items are\n * never interleaved with other entries — which is the reason a group exists\n * as a container rather than as a flag on each item.\n */\n shuffleEntries?: boolean;\n /**\n * Seed for every shuffle in this call: the entries, and each group whose\n * `shuffle` is `within-group`. REQUIRED whenever anything shuffles. The SDK\n * never invents one, because the server that stores an attempt and the\n * client that renders it must derive the SAME order, and only a shared seed\n * makes that true. The attempt id is the natural choice.\n */\n seed?: string;\n}\n\n/**\n * Turns a sequence definition — loose activities and item groups, in authored\n * order — into the ordered list of slots to present. Pure and deterministic:\n * call it on the server to record an attempt's order, and on the client to\n * render it, and the two agree.\n *\n * Shuffling is opt-in and seeded. Groups are shuffle-atomic: with\n * `shuffleEntries` a group changes position but stays one contiguous block,\n * and only a group that declares `shuffle: 'within-group'` has its items\n * reordered. Every slot carries a `slotId` derived from the authored\n * position, so identities survive shuffling.\n *\n * @throws Error when a shuffle is requested without a `seed`.\n */\nexport function flattenSequence<TItem extends { id: string; type: string }>(\n entries: readonly SequenceEntry<TItem>[],\n options: FlattenSequenceOptions = {},\n): SequenceSlot<TItem>[] {\n const shuffleEntries = options.shuffleEntries === true;\n const needsSeed =\n shuffleEntries ||\n entries.some((entry) => isItemGroup(entry) && entry.shuffle === 'within-group');\n if (needsSeed && options.seed === undefined) {\n throw new Error(\n 'flattenSequence: a seed is required when shuffling (shuffleEntries, or a group with ' +\n 'shuffle: \"within-group\"). Pass the attempt id so the server and the client derive the same order.',\n );\n }\n const seed = options.seed ?? '';\n\n // Carry the AUTHORED index through the shuffle: slot identity comes from\n // where an entry was written, never from where it happens to be shown.\n const authored = entries.map((entry, entryIndex) => ({ entry, entryIndex }));\n const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`) : authored;\n\n const slots: SequenceSlot<TItem>[] = [];\n for (const { entry, entryIndex } of ordered) {\n // An authored `slotKey` wins over the positional path. A positional id is\n // only valid against ONE version of the entries array; a declared key\n // survives insertion, deletion and re-ordering, which is what makes a\n // stored slot id safe to re-grade against later.\n const entryKey = keyOf(entry) ?? String(entryIndex);\n if (!isItemGroup(entry)) {\n slots.push({ slotId: entryKey, index: slots.length, activity: entry });\n continue;\n }\n // An empty group contributes no slots, so it would DISAPPEAR — stimulus,\n // questions and all — from a sequence that still looks well-formed. A\n // listening section filtered to nothing upstream would leave an 18-slot\n // paper presented as 12 slots, and `composeAssessmentScore` would then\n // report a `final` grade over the survivors with nothing pending. The\n // type already declares `items` non-empty; this makes that enforceable at\n // the point where the omission would otherwise become invisible.\n if (entry.items.length === 0) {\n throw new Error(\n `flattenSequence: item group \"${entry.id}\" has no items. An empty group would silently ` +\n 'remove its stimulus and its questions from the presented sequence.',\n );\n }\n const items = entry.items.map((item, itemIndex) => ({ item, itemIndex }));\n const presented =\n entry.shuffle === 'within-group' ? seededShuffle(items, `${seed}:group:${entry.id}`) : items;\n const size = presented.length;\n presented.forEach(({ item, itemIndex }, position) => {\n slots.push({\n slotId: `${entryKey}.${keyOf(item) ?? String(itemIndex)}`,\n index: slots.length,\n activity: item,\n group: {\n id: entry.id,\n ...(entry.title !== undefined ? { title: entry.title } : {}),\n stimulus: entry.stimulus,\n position,\n size,\n },\n });\n });\n }\n\n // Positional ids are unique by construction; authored keys are not. Two\n // entries sharing a key would collapse into one identity, so every response\n // stored against it would overwrite the other's — and `composeAssessmentScore`\n // would score one question twice and the other never.\n const seenSlotIds = new Set<string>();\n // ENTRY keys are checked separately, because a loose entry keyed \"reading\"\n // and a group keyed \"reading\" produce slot ids \"reading\" and \"reading.0\"\n // that never collide — while everything reading the entry prefix (the\n // pager's stimulus grouping, for one) treats them as the same entry, and\n // shows the group's passage above the unrelated loose question. Positional\n // ids could not express this: an index is a loose item or a group, never\n // both.\n const seenEntryKeys = new Set<string>();\n for (const slot of slots) {\n if (seenSlotIds.has(slot.slotId)) {\n throw new Error(\n `flattenSequence: duplicate slot id \"${slot.slotId}\". Two entries declare the same ` +\n 'slotKey, so responses stored against them could not be told apart.',\n );\n }\n seenSlotIds.add(slot.slotId);\n }\n for (const { entry, entryIndex } of ordered) {\n const entryKey = keyOf(entry) ?? String(entryIndex);\n if (seenEntryKeys.has(entryKey)) {\n throw new Error(\n `flattenSequence: duplicate entry key \"${entryKey}\". A loose activity and an item group ` +\n 'cannot share a slotKey — their slot ids would not collide, but everything that reads ' +\n 'the entry they belong to would treat them as one entry.',\n );\n }\n seenEntryKeys.add(entryKey);\n }\n return slots;\n}\n","import type { ActivityMedia, NativeControlHint } from './types/activity.js';\nimport type { AttemptPlan } from './types/attempt-plan.js';\nimport type { MediaPlayLedger, MediaPlayLedgerEntry } from './types/media-budget.js';\n\nexport type {\n MediaPlayClaim,\n MediaPlayGrant,\n MediaPlayLedger,\n MediaPlayLedgerEntry,\n} from './types/media-budget.js';\n\n/**\n * The authored-entry prefix of a slot id: `\"3\"` for both `\"3\"` and `\"3.1\"`.\n *\n * Safe because every slot id in a plan is produced by `flattenSequence`, and\n * `keyOf` rejects a `.` in both an entry key and an item key — so the first\n * `.` is always the group/item separator.\n */\nexport function entryKeyOf(slotId: string): string {\n const dot = slotId.indexOf('.');\n return dot === -1 ? slotId : slotId.slice(0, dot);\n}\n\n/** Budget key for an activity's OWN `data.media`. One budget per slot. */\nexport function slotMediaKey(slotId: string): string {\n return `slot:${slotId}`;\n}\n\n/**\n * Budget key for an item group's `stimulus.media`.\n *\n * Keyed by the ENTRY, not the slot: one recording serves every question in the\n * group, so `\"3.0\"`…`\"3.5\"` share one budget. Keying by `slotId` would hand a\n * six-question `maxPlays: 2` listening group twelve plays; keying by\n * `stimulus.id` would collide across papers, which is the thing slot keys and\n * `planHash` exist to prevent.\n */\nexport function stimulusMediaKey(slotId: string): string {\n return `stimulus:${entryKeyOf(slotId)}`;\n}\n\n/** A playback policy with every default resolved. One derivation, used everywhere. */\nexport interface ResolvedPlaybackPolicy {\n controls: 'native' | 'minimal';\n /** `null` when the recording is unbudgeted. */\n maxPlays: number | null;\n seek: 'allow' | 'none';\n rate: 'allow' | 'fixed';\n nativeControlHints: readonly NativeControlHint[];\n}\n\n/**\n * Resolves the defaults once, so the schema refinements, the plan and the\n * renderer cannot drift apart about what a policy means.\n *\n * Absent `playback` resolves to exactly the SDK's pre-0.8.0 behaviour:\n * `controls: 'native'`, no budget, free seeking, free speed, no hints.\n */\nexport function resolvePlaybackPolicy(media: ActivityMedia): ResolvedPlaybackPolicy {\n const p = media.playback;\n const budgeted = typeof p?.maxPlays === 'number';\n const seek = p?.seek ?? (budgeted ? 'none' : 'allow');\n const rate = p?.rate ?? 'allow';\n const controls =\n p?.controls ?? (budgeted || seek === 'none' || rate === 'fixed' ? 'minimal' : 'native');\n return {\n controls,\n maxPlays: budgeted ? (p?.maxPlays as number) : null,\n seek,\n rate,\n nativeControlHints: p?.nativeControlHints ?? [],\n };\n}\n\n/**\n * Every budgeted recording a plan contains: budget key → the `maxPlays` that\n * was frozen when the attempt was planned.\n *\n * Use it to build the storage rows an attempt needs, and to check a stored\n * ledger against the paper it claims to belong to.\n */\nexport function planMediaBudgets(plan: AttemptPlan): Record<string, number> {\n const out: Record<string, number> = {};\n for (const slot of plan.slots) {\n for (const budget of slot.mediaBudgets ?? []) {\n out[budget.key] = budget.maxPlays;\n }\n }\n return out;\n}\n\nfunction assertEntry(key: string, entry: MediaPlayLedgerEntry): void {\n if (\n entry === null ||\n typeof entry !== 'object' ||\n !Number.isInteger(entry.plays) ||\n entry.plays < 0\n ) {\n throw new Error(\n `serializeMediaPlayLedger: play count for ${JSON.stringify(key)} is ` +\n `${JSON.stringify((entry as MediaPlayLedgerEntry | null)?.plays)}. A count must be a ` +\n 'non-negative integer; Number(a NULL column) is the usual cause.',\n );\n }\n if (entry.at !== undefined && (!Number.isFinite(entry.at) || entry.at < 0)) {\n throw new Error(\n `serializeMediaPlayLedger: position for ${JSON.stringify(key)} is ` +\n `${JSON.stringify(entry.at)}. A position must be a finite number of seconds >= 0.`,\n );\n }\n}\n\n/**\n * Validates a set of spent-play counts against the plan that budgeted them,\n * and stamps the envelope.\n *\n * Validates on the way **in**: a play recorded against a recording the paper\n * does not budget is a bug at the moment it is written, and discovering it\n * when a learner tries to resume is discovering it far too late.\n *\n * @throws Error when a key is not budgeted by the plan, or a count is not a\n * non-negative integer, or a position is not a finite number.\n */\nexport function serializeMediaPlayLedger(\n plan: AttemptPlan,\n entries: Readonly<Record<string, MediaPlayLedgerEntry>>,\n options: { savedAt?: string } = {},\n): MediaPlayLedger {\n if (entries === null || typeof entries !== 'object') {\n throw new Error('serializeMediaPlayLedger: entries must be an object keyed by media key.');\n }\n const budgets = planMediaBudgets(plan);\n const out: Record<string, MediaPlayLedgerEntry> = {};\n\n for (const key of Object.keys(entries)) {\n if (!Object.hasOwn(budgets, key)) {\n throw new Error(\n `serializeMediaPlayLedger: media play recorded against a recording the plan does not ` +\n `budget: ${JSON.stringify(key)}. Keys come from slotMediaKey() / stimulusMediaKey(); a ` +\n 'key that belongs to no budgeted media means the client and the plan disagree about ' +\n 'which paper this is.',\n );\n }\n const entry = entries[key] as MediaPlayLedgerEntry;\n assertEntry(key, entry);\n out[key] = { plays: entry.plays, ...(entry.at !== undefined ? { at: entry.at } : {}) };\n }\n\n return {\n ledgerVersion: '1.0',\n planHash: plan.planHash,\n entries: out,\n ...(options.savedAt !== undefined ? { savedAt: options.savedAt } : {}),\n };\n}\n\n/**\n * Reopens a stored ledger against the paper it was spent on.\n *\n * Refuses a ledger from a different paper for the same reason\n * `restoreAttemptState` does: budget keys are short and repeat across papers\n * (`slot:0`, `stimulus:1`), so a ledger from last term's midterm would hold a\n * learner to a budget from an exam they never sat, and look entirely plausible\n * doing it.\n *\n * @throws Error on an unrecognised `ledgerVersion`, a `planHash` mismatch, or\n * anything `serializeMediaPlayLedger` refuses.\n */\nexport function restoreMediaPlayLedger(\n plan: AttemptPlan,\n stored: MediaPlayLedger,\n): MediaPlayLedger {\n if (stored === null || typeof stored !== 'object') {\n throw new Error('restoreMediaPlayLedger: the stored ledger is not an object.');\n }\n if (stored.ledgerVersion !== '1.0') {\n throw new Error(\n `restoreMediaPlayLedger: unsupported ledgerVersion ${JSON.stringify(stored.ledgerVersion)}. ` +\n 'This build understands \"1.0\"; a newer ledger must be migrated before it is restored.',\n );\n }\n if (stored.entries === null || typeof stored.entries !== 'object') {\n throw new Error(\n 'restoreMediaPlayLedger: the ledger carries no entries object (a NULL column, or a ' +\n 'partially written row).',\n );\n }\n if (stored.planHash !== plan.planHash) {\n throw new Error(\n 'restoreMediaPlayLedger: this ledger belongs to a different paper ' +\n `(ledger ${stored.planHash}, plan ${plan.planHash}). Restoring it would hold the learner ` +\n 'to a play budget from an exam they never sat.',\n );\n }\n return serializeMediaPlayLedger(plan, stored.entries, {\n ...(stored.savedAt !== undefined ? { savedAt: stored.savedAt } : {}),\n });\n}\n","import { contentHash } from './content-hash.js';\nimport { flattenSequence } from './item-group.js';\nimport { resolvePlaybackPolicy, slotMediaKey, stimulusMediaKey } from './media-budget.js';\nimport type { ScoredItem } from './scoring/compose.js';\nimport type { ActivityData, ActivityMedia, ItemOutcome } from './types/activity.js';\nimport type {\n AttemptPlan,\n AttemptPlanDrift,\n AttemptPlanSlot,\n MediaBudgetRef,\n} from './types/attempt-plan.js';\nimport type { SequenceEntry, SequenceSlot } from './types/item-group.js';\n\nexport type {\n AttemptPlan,\n AttemptPlanDrift,\n AttemptPlanSlot,\n MediaBudgetRef,\n} from './types/attempt-plan.js';\n\n/** Options for {@link planAttempt}. */\nexport interface PlanAttemptOptions<TItem> {\n /** Shuffle the top-level entries. A group moves as one block. */\n shuffleEntries?: boolean;\n /**\n * Seed for every shuffle in this attempt. Required whenever anything\n * shuffles — the attempt has to be reproducible, which is the entire point\n * of writing a plan down. Use the attempt id.\n */\n seed?: string;\n /**\n * What each slot is worth. Defaults to 1 for every slot.\n *\n * Points are resolved HERE, not read from content, because they belong to\n * the paper rather than the item: the same question is worth 1 in a practice\n * quiz and 3 in a final. Whatever this returns is frozen into the plan and\n * is what `composeAssessmentScore` will weight by.\n *\n * @throws Error when it returns a value that is not a finite, non-negative\n * number — a slot worth `NaN` points would poison the whole total.\n */\n points?: (slot: SequenceSlot<TItem>) => number;\n}\n\n/**\n * The activity as CONTENT, with its slot key removed.\n *\n * `slotKey` rides on the same object but is identity, not content — the whole\n * point of the design. Including it in the fingerprint meant that annotating\n * an existing entry with the key that pins its identity reported as\n * \"this question was edited\", which is precisely backwards.\n */\nfunction contentOf(activity: object): object {\n if (!Object.hasOwn(activity, 'slotKey')) {\n return activity;\n }\n const { slotKey: _slotKey, ...content } = activity as { slotKey?: unknown };\n return content;\n}\n\n/**\n * The budgeted recordings a slot presents: its own media, and its group's\n * stimulus. Returns `undefined` — not `[]` — when nothing is budgeted, so the\n * conditional spread below leaves the serialized slot byte-identical to what\n * every pre-0.8.0 paper produced.\n */\nfunction mediaBudgetsOf<TItem extends { id: string; type: string }>(\n slot: SequenceSlot<TItem>,\n): MediaBudgetRef[] | undefined {\n const budgets: MediaBudgetRef[] = [];\n // Read structurally: `media` is a shared optional field, not part of the\n // `{ id, type }` bound this function is generic over.\n const own = (slot.activity as { media?: ActivityMedia }).media;\n if (own !== undefined) {\n const maxPlays = resolvePlaybackPolicy(own).maxPlays;\n if (maxPlays !== null) {\n budgets.push({ key: slotMediaKey(slot.slotId), maxPlays });\n }\n }\n const stimulusMedia = slot.group?.stimulus.media;\n if (stimulusMedia !== undefined) {\n const maxPlays = resolvePlaybackPolicy(stimulusMedia).maxPlays;\n if (maxPlays !== null) {\n budgets.push({ key: stimulusMediaKey(slot.slotId), maxPlays });\n }\n }\n return budgets.length > 0 ? budgets : undefined;\n}\n\n/**\n * Refuses a paper in which one recording is budgeted under several keys.\n *\n * Six questions that each carry the same `/audio/part2.mp3` with `maxPlays: 2`\n * are six budgets, so the learner gets twelve plays of one recording while the\n * paper says two. The fix is authoring, not arithmetic: questions that share a\n * recording belong in an item group, whose stimulus is one recording with one\n * budget.\n */\nfunction assertNoSplitBudgets<TItem extends { id: string; type: string }>(\n slots: readonly SequenceSlot<TItem>[],\n): void {\n const keysByUrl = new Map<string, string[]>();\n for (const slot of slots) {\n const own = (slot.activity as { media?: ActivityMedia }).media;\n if (own === undefined || resolvePlaybackPolicy(own).maxPlays === null) {\n continue;\n }\n const keys = keysByUrl.get(own.url) ?? [];\n keys.push(slotMediaKey(slot.slotId));\n keysByUrl.set(own.url, keys);\n }\n for (const [url, keys] of keysByUrl) {\n if (keys.length > 1) {\n throw new Error(\n `planAttempt: media ${JSON.stringify(url)} is budgeted under ${keys.length} separate ` +\n `keys (${keys.join(', ')}), so one recording grants ${keys.length} × maxPlays. Put the ` +\n \"questions that share a recording in an item group — a group's stimulus is one \" +\n 'recording with one budget.',\n );\n }\n }\n}\n\nfunction planSlot<TItem extends { id: string; type: string }>(\n slot: SequenceSlot<TItem>,\n points: number,\n): AttemptPlanSlot {\n if (!Number.isFinite(points) || points < 0) {\n throw new Error(\n `planAttempt: slot \"${slot.slotId}\" resolved to ${String(points)} points. Points must be a ` +\n 'finite, non-negative number, or the paper has no defensible total.',\n );\n }\n const mediaBudgets = mediaBudgetsOf(slot);\n return {\n slotId: slot.slotId,\n index: slot.index,\n activityId: slot.activity.id,\n activityType: slot.activity.type,\n points,\n contentHash: contentHash(contentOf(slot.activity)),\n ...(slot.group !== undefined\n ? {\n group: {\n id: slot.group.id,\n ...(slot.group.title !== undefined ? { title: slot.group.title } : {}),\n stimulusHash: contentHash(slot.group.stimulus),\n },\n }\n : {}),\n ...(mediaBudgets !== undefined ? { mediaBudgets } : {}),\n };\n}\n\n/**\n * Freezes what an attempt is being served: the presented order, each slot's\n * identity and worth, and a fingerprint of the content behind it.\n *\n * Call this once, when the attempt starts, and store the result beside the\n * responses. Everything that decides the grade is then a historical fact\n * rather than a re-read of content that may since have changed — which is what\n * makes a re-grade, a remark or an appeal answerable.\n *\n * Ordering comes from `flattenSequence`, so a plan and a live render of the\n * same entries with the same seed agree slot for slot.\n *\n * @throws Error when a shuffle is requested without a seed, when a group is\n * empty, when two entries collide on a `slotKey`, or when `points`\n * returns a value that is not finite and non-negative.\n */\nexport function planAttempt<TItem extends { id: string; type: string }>(\n entries: readonly SequenceEntry<TItem>[],\n options: PlanAttemptOptions<TItem> = {},\n): AttemptPlan {\n const { seed, shuffleEntries, points } = options;\n const slots = flattenSequence(entries, {\n ...(shuffleEntries !== undefined ? { shuffleEntries } : {}),\n ...(seed !== undefined ? { seed } : {}),\n });\n\n assertNoSplitBudgets(slots);\n\n const planned = slots.map((slot) => planSlot(slot, points?.(slot) ?? 1));\n const totalPoints = planned.reduce((sum, slot) => sum + slot.points, 0);\n\n return {\n planVersion: '1.0',\n ...(seed !== undefined ? { seed } : {}),\n ...(shuffleEntries !== undefined ? { shuffleEntries } : {}),\n // The plan's own fingerprint covers the slots verbatim — identity, order,\n // points and content hashes — so one stored value answers \"is this still\n // the paper that was sat?\" and the per-slot hashes then say what moved.\n planHash: contentHash(planned),\n slots: planned,\n totalPoints,\n };\n}\n\n/**\n * Compares a stored plan with the content as it stands now, and reports every\n * way they have drifted apart.\n *\n * This is the question a remark or an appeal actually asks: *is the paper I am\n * looking at the paper this learner sat?* Ids alone cannot answer it, because\n * they survive an edit unchanged.\n *\n * Rebuild the comparison plan with the SAME options the stored one recorded —\n * its `seed`, its `shuffleEntries`, and the same `points` function — or the\n * differences you see will be your own:\n *\n * ```ts\n * const now = planAttempt(currentEntries, {\n * seed: stored.seed,\n * shuffleEntries: stored.shuffleEntries,\n * points: pointsFor, // omit it and every slot reweights to 1\n * });\n * const drift = verifyAttemptPlan(stored, now);\n * ```\n *\n * A drift is not automatically a problem — a fixed typo changes a hash without\n * changing what was asked. It is a fact somebody has to be able to see.\n */\nexport function verifyAttemptPlan(plan: AttemptPlan, current: AttemptPlan): AttemptPlanDrift {\n const before = new Map(plan.slots.map((slot) => [slot.slotId, slot]));\n const after = new Map(current.slots.map((slot) => [slot.slotId, slot]));\n\n const missingSlotIds = plan.slots.filter((s) => !after.has(s.slotId)).map((s) => s.slotId);\n const addedSlotIds = current.slots.filter((s) => !before.has(s.slotId)).map((s) => s.slotId);\n\n const changedSlotIds: string[] = [];\n const changedStimulusSlotIds: string[] = [];\n const changedPointsSlotIds: string[] = [];\n const reorderedSlotIds: string[] = [];\n for (const slot of plan.slots) {\n const now = after.get(slot.slotId);\n if (now === undefined) {\n continue;\n }\n // A swapped activity changes the content behind the slot, so it lands in\n // `changedSlotIds` through the fingerprint rather than needing its own arm.\n if (now.contentHash !== slot.contentHash) {\n changedSlotIds.push(slot.slotId);\n }\n if (now.group?.stimulusHash !== slot.group?.stimulusHash) {\n changedStimulusSlotIds.push(slot.slotId);\n }\n // A reweight moves the grade without touching a single question. Left out,\n // `matches` said the paper was unchanged while its `planHash` disagreed.\n if (now.points !== slot.points) {\n changedPointsSlotIds.push(slot.slotId);\n }\n if (now.index !== slot.index) {\n reorderedSlotIds.push(slot.slotId);\n }\n }\n\n return {\n matches:\n missingSlotIds.length === 0 &&\n addedSlotIds.length === 0 &&\n changedSlotIds.length === 0 &&\n changedStimulusSlotIds.length === 0 &&\n changedPointsSlotIds.length === 0 &&\n reorderedSlotIds.length === 0,\n missingSlotIds,\n addedSlotIds,\n changedSlotIds,\n changedStimulusSlotIds,\n changedPointsSlotIds,\n reorderedSlotIds,\n };\n}\n\n/** How {@link scoredItemsFromPlan} fills a slot that has no recorded outcome. */\nexport type MissingOutcomePolicy =\n /**\n * Default. `{ status: 'deferred', reason: 'no_response_recorded' }` — a\n * non-terminal state, so the composed result stays `provisional` and cannot\n * be recorded as a final pass or fail.\n */\n | 'deferred'\n /**\n * `{ status: 'scored', score: 0 }` — the learner left it blank on a paper\n * that IS complete. Choose this only when you know the attempt was\n * submitted; it is a real zero and makes the result final.\n */\n | 'zero'\n /** Build the outcome yourself, per slot. */\n | ((slot: AttemptPlanSlot) => ItemOutcome);\n\nfunction missingOutcome(slot: AttemptPlanSlot, policy: MissingOutcomePolicy): ItemOutcome {\n if (typeof policy === 'function') {\n return policy(slot);\n }\n if (policy === 'zero') {\n return { status: 'scored', score: 0, maxScore: 1, passed: false, feedback: null, details: [] };\n }\n return { status: 'deferred', reason: 'no_response_recorded', maxScore: 1 };\n}\n\n/**\n * Turns a plan plus whatever outcomes exist into the `ScoredItem[]`\n * `composeAssessmentScore` consumes.\n *\n * The plan is the source of the denominator, not the outcomes. A slot the\n * learner never reached still has to appear — otherwise it silently leaves the\n * denominator and the remaining questions quietly become worth more than the\n * paper says.\n *\n * **A missing outcome defaults to `deferred`, never `unscorable`.** The\n * distinction decides a grade: `unscorable` means \"a grade is never coming\",\n * so `composeAssessmentScore` drops the slot from the denominator AND lets the\n * result go `final` — which turned a three-question paper with one answer into\n * a final, passing 100%. `deferred` means \"not yet\", which holds the result\n * `provisional` so nothing can be recorded. Pass `'zero'` once you know the\n * attempt was submitted and the blanks are genuinely blanks.\n *\n * Pass outcomes keyed by `slotId`. Keys the plan does not know are ignored:\n * a plan is the authority on what the attempt contained.\n */\nexport function scoredItemsFromPlan(\n plan: AttemptPlan,\n outcomes: Readonly<Record<string, ItemOutcome>>,\n options: { missing?: MissingOutcomePolicy } = {},\n): ScoredItem[] {\n const policy = options.missing ?? 'deferred';\n return plan.slots.map((slot) => ({\n slotId: slot.slotId,\n activityId: slot.activityId,\n points: slot.points,\n // `Object.hasOwn`, not a bare lookup: slot ids come from authored\n // `slotKey`s, and a key of `constructor` or `toString` would otherwise\n // resolve through the prototype chain and hand a FUNCTION to the scorer\n // in place of an outcome.\n outcome: Object.hasOwn(outcomes, slot.slotId)\n ? (outcomes[slot.slotId] as ItemOutcome)\n : missingOutcome(slot, policy),\n }));\n}\n\n/** Convenience alias: the entry type a plan is built from. */\nexport type PlannableEntry = SequenceEntry<ActivityData>;\n","import { canonicalJson } from './content-hash.js';\nimport type { LearnerResponse } from './types/activity.js';\nimport type { AttemptPlan } from './types/attempt-plan.js';\nimport type { AttemptState, ResponseDiffEntry } from './types/attempt-state.js';\n\nexport type { AttemptState, ResponseDiffEntry } from './types/attempt-state.js';\n\n/** What {@link serializeAttemptState} is given about an attempt in progress. */\nexport interface AttemptProgress {\n /** Answers so far, keyed by `slotId`. */\n responses: Readonly<Record<string, LearnerResponse>>;\n /** Slots already submitted. Defaults to none. */\n submittedSlotIds?: readonly string[];\n /** Presented position the learner is on. Defaults to 0. */\n index?: number;\n /** ISO 8601 timestamp to stamp the snapshot with. The SDK does not read a clock. */\n savedAt?: string;\n}\n\n/**\n * A DEEP copy of the responses.\n *\n * A one-level spread is not enough: every `LearnerResponse` shape is itself an\n * object (`selectedOptionIds`, `answers`, `text`), so a spread hands back a new\n * map of the caller's SAME response objects. A consumer whose reducer updates\n * an answer in place — an Immer draft, a push onto a multi-select, or\n * `answers[blankId] = text`, which is the natural update for that shape — then\n * mutates every snapshot ever taken. The stored snapshot retroactively becomes\n * the new answer, `diffResponses` sees no change, and a delta autosave writes\n * nothing for an edit the learner really made.\n */\nfunction cloneResponses(\n responses: Readonly<Record<string, LearnerResponse>>,\n): Record<string, LearnerResponse> {\n // Responses are JSON by contract, so the fallback is lossless for them.\n return typeof structuredClone === 'function'\n ? structuredClone(responses as Record<string, LearnerResponse>)\n : (JSON.parse(JSON.stringify(responses)) as Record<string, LearnerResponse>);\n}\n\n/** Slot ids present in the object but unknown to the plan. */\nfunction unknownKeys(plan: AttemptPlan, keys: readonly string[]): string[] {\n const known = new Set(plan.slots.map((slot) => slot.slotId));\n return keys.filter((key) => !known.has(key));\n}\n\n/**\n * Captures an in-progress attempt as a storable snapshot, bound to its plan.\n *\n * Validated against the plan on the way in, not on the way out: a response\n * stored under a slot the paper does not contain is a bug at the moment it is\n * written, and finding it months later — when a learner tries to resume — is\n * finding it far too late.\n *\n * The SDK reads no clock: pass `savedAt` if you want the snapshot stamped, so\n * the function stays pure and its output stays reproducible in a test.\n *\n * @throws Error when a response or submitted slot is not in the plan, or when\n * `index` is not a position the plan actually has.\n */\nexport function serializeAttemptState(plan: AttemptPlan, progress: AttemptProgress): AttemptState {\n const responseKeys = Object.keys(progress.responses);\n const submittedSlotIds = [...(progress.submittedSlotIds ?? [])];\n\n const strayResponses = unknownKeys(plan, responseKeys);\n if (strayResponses.length > 0) {\n throw new Error(\n `serializeAttemptState: response recorded for slot(s) the plan does not contain: ${strayResponses.join(', ')}. ` +\n 'A response that belongs to no question cannot be scored and would be lost silently.',\n );\n }\n const straySubmitted = unknownKeys(plan, submittedSlotIds);\n if (straySubmitted.length > 0) {\n throw new Error(\n `serializeAttemptState: submitted slot(s) the plan does not contain: ${straySubmitted.join(', ')}.`,\n );\n }\n\n const index = progress.index ?? 0;\n // An out-of-range position would reopen the attempt on a question that is\n // not there — which the pager renders as an empty shell with no way forward.\n // An empty plan admits only 0: guarding with `slots.length > 0` skipped the\n // range check altogether there, so a zero-slot paper accepted any index and\n // the error message contradicted itself.\n const lastIndex = Math.max(0, plan.slots.length - 1);\n if (!Number.isInteger(index) || index < 0 || index > lastIndex) {\n throw new Error(\n `serializeAttemptState: index ${String(index)} is not a position in a ${plan.slots.length}-slot plan.`,\n );\n }\n\n return {\n stateVersion: '1.0',\n planHash: plan.planHash,\n // Copied DEEPLY, not aliased: a snapshot that keeps mutating with the\n // live attempt is not a snapshot. See cloneResponses.\n responses: cloneResponses(progress.responses),\n submittedSlotIds,\n index,\n ...(progress.savedAt !== undefined ? { savedAt: progress.savedAt } : {}),\n };\n}\n\n/**\n * Reopens a stored snapshot against a plan, refusing anything that does not\n * belong to it.\n *\n * The `planHash` check is the point. Slot ids are short and stable by design,\n * so a snapshot from a DIFFERENT paper — last term's midterm, a sibling\n * version, a copy-pasted attempt row — will happily line its answers up\n * against the wrong questions and look entirely plausible doing it. Comparing\n * the paper's fingerprint is what makes that impossible rather than unlikely.\n *\n * @throws Error when the snapshot belongs to a different plan, or references\n * slots the plan does not contain.\n */\nexport function restoreAttemptState(plan: AttemptPlan, state: AttemptState): AttemptState {\n if (state === null || typeof state !== 'object') {\n throw new Error('restoreAttemptState: the snapshot is not an object.');\n }\n // The one field added so a stored snapshot survives an envelope change was\n // the one field never read: an unrecognised version was accepted,\n // reinterpreted under this version's rules, and re-stamped '1.0' — which\n // also destroyed the evidence that it had ever been anything else.\n if (state.stateVersion !== '1.0') {\n throw new Error(\n `restoreAttemptState: unsupported stateVersion ${JSON.stringify(state.stateVersion)}. ` +\n 'This build understands \"1.0\"; a newer snapshot must be migrated before it is restored.',\n );\n }\n if (state.responses === null || typeof state.responses !== 'object') {\n throw new Error(\n 'restoreAttemptState: the snapshot carries no responses object (a NULL column, or a ' +\n 'partially written row).',\n );\n }\n if (state.planHash !== plan.planHash) {\n throw new Error(\n 'restoreAttemptState: this snapshot belongs to a different paper ' +\n `(snapshot ${state.planHash}, plan ${plan.planHash}). Restoring it would attach the ` +\n \"learner's answers to questions they never saw.\",\n );\n }\n // Re-validated rather than trusted: a snapshot is storage, and storage is\n // edited, migrated and hand-fixed.\n return serializeAttemptState(plan, {\n responses: state.responses,\n submittedSlotIds: state.submittedSlotIds,\n index: state.index,\n ...(state.savedAt !== undefined ? { savedAt: state.savedAt } : {}),\n });\n}\n\n/**\n * Reports how two snapshots' responses differ, slot by slot.\n *\n * Useful for an autosave that should only write what moved, and for an audit\n * trail that has to show what a learner changed between two saves — including\n * an answer they cleared, which a naive comparison of the later snapshot\n * alone cannot see.\n *\n * Entries come back sorted by `slotId`, so the output is stable regardless of\n * the order the two objects happened to be written in.\n */\nexport function diffResponses(\n before: Pick<AttemptState, 'responses'>,\n after: Pick<AttemptState, 'responses'>,\n): ResponseDiffEntry[] {\n const slotIds = [...new Set([...Object.keys(before.responses), ...Object.keys(after.responses)])];\n slotIds.sort();\n\n const entries: ResponseDiffEntry[] = [];\n for (const slotId of slotIds) {\n const had = Object.hasOwn(before.responses, slotId);\n const has = Object.hasOwn(after.responses, slotId);\n const from = before.responses[slotId];\n const to = after.responses[slotId];\n\n if (had && !has) {\n entries.push({ slotId, change: 'removed', ...(from !== undefined ? { before: from } : {}) });\n continue;\n }\n if (!had && has) {\n entries.push({ slotId, change: 'added', ...(to !== undefined ? { after: to } : {}) });\n continue;\n }\n // Structural comparison through the canonical form, so a response that\n // survived a JSON round-trip with its keys reordered does not read as a\n // change the learner never made.\n if (canonicalJson(from) !== canonicalJson(to)) {\n entries.push({\n slotId,\n change: 'changed',\n ...(from !== undefined ? { before: from } : {}),\n ...(to !== undefined ? { after: to } : {}),\n });\n }\n }\n return entries;\n}\n","import {\n GROUP_CAPTIONS_REVEAL_DICTATION,\n groupCaptionsRevealDictation,\n} from '../schemas/dictation.js';\nimport { ItemGroupSchema, validateItemGroup } from '../schemas/item-group.js';\nimport type { ActivityType } from '../types/activity.js';\nimport type { DraftContext, DraftIssue, DraftValidationResult } from '../types/authoring.js';\nimport type { ItemGroup } from '../types/item-group.js';\nimport { withValidationScope } from '../validation-scope.js';\nimport { validateDraft } from './index.js';\nimport {\n checkMedia,\n covers,\n type DraftFields,\n isMissingId,\n isRecord,\n issue,\n isUnset,\n isUnwritten,\n refusesEmpty,\n} from './issues.js';\n\n/**\n * A new, empty reading or listening testlet for an editor to start from.\n *\n * The stimulus starts as `text`, the only kind that needs no media file to be\n * a valid draft — an author who is writing a passage can begin typing, and one\n * who is building a listening item changes `kind` before uploading. `items`\n * starts empty, exactly as a new fill-in-the-blanks draft starts with no\n * blanks: the group is `incomplete` until somebody writes a question into it.\n *\n * @throws Error when `newId` returns an empty or repeated id.\n */\nexport function createItemGroupDraft(context: DraftContext): ItemGroup {\n const issued = new Set<string>();\n const newId = (): string => {\n const id: unknown = context.newId();\n if (typeof id !== 'string' || id === '') {\n throw new Error('createItemGroupDraft: newId() must return a non-empty string.');\n }\n if (issued.has(id)) {\n throw new Error(\n `createItemGroupDraft: newId() returned \"${id}\" twice. Ids within one draft must differ.`,\n );\n }\n issued.add(id);\n return id;\n };\n return {\n schemaVersion: '1.0',\n type: 'item-group',\n id: newId(),\n stimulus: { id: newId(), kind: 'text', body: '' },\n items: [],\n };\n}\n\n/**\n * Tells an unfinished testlet from a broken one — {@link validateDraft} for the\n * container that holds several questions around one passage or recording.\n *\n * It is a **separate entry point rather than a `'item-group'` type**, because\n * `validateDraft('item-group', …)` throws by design: `item-group` is reserved\n * in the registry precisely so it can never be registered as an activity, and\n * that guard is what keeps `isItemGroup` and `flattenSequence` able to trust\n * their own container. Widening `validateDraft` to accept it would have meant\n * weakening that.\n *\n * Each item is checked by `validateDraft` for its own type and its issues are\n * re-pathed under `items.N.…`, so an editor gets one list for the whole group\n * and every code in it is the code that type already documents. An item whose\n * type nobody registered is REPORTED, never thrown — an author fixing a\n * six-item group wants all six problems, not the first one that blew up.\n *\n * The group is `complete` only when the container passes, every item passes its\n * own schema, and every item is itself `complete`.\n */\nexport function validateItemGroupDraft(draft: unknown): DraftValidationResult<ItemGroup> {\n // Every item is checked as a draft and then again as part of the group: one\n // scope lets the expensive normalisation behind both run once.\n return withValidationScope(() => validateItemGroupDraftInScope(draft));\n}\n\nfunction validateItemGroupDraftInScope(draft: unknown): DraftValidationResult<ItemGroup> {\n const issues: DraftIssue[] = [];\n if (!isRecord(draft)) {\n issues.push(\n issue('ig_not_an_object', [], 'A group must be an object with a stimulus and its items.'),\n );\n return { status: 'invalid', issues };\n }\n\n issues.push(...checkGroupIdentity(draft));\n if (isRecord(draft.stimulus)) {\n issues.push(...checkStimulus(draft.stimulus));\n } else if (isUnset(draft.stimulus)) {\n issues.push(\n issue(\n 'ig_stimulus_required',\n ['stimulus'],\n 'Add the passage, recording or image the questions are about.',\n ),\n );\n }\n issues.push(...checkItems(draft));\n if (groupCaptionsRevealDictation(draft, (captionsUrl) => !isUnwritten(captionsUrl))) {\n issues.push(\n issue(\n 'dc_captions_not_allowed',\n ['stimulus', 'media', 'captionsUrl'],\n GROUP_CAPTIONS_REVEAL_DICTATION,\n ),\n );\n }\n\n // Every container failure the checks above did not already account for, added\n // as `invalid` — the same rule `validateDraft` follows, so a rule nobody\n // named still reaches the author instead of passing silently.\n const parsed = ItemGroupSchema.safeParse(draft, { reportInput: true });\n if (!parsed.success) {\n for (const schemaIssue of parsed.error.issues) {\n const path = schemaIssue.path.map(String);\n if (issues.some((known) => covers(known.path, path))) {\n continue;\n }\n if (path.length > 0 && refusesEmpty(draft, schemaIssue)) {\n issues.push(\n issue(\n 'null_not_allowed',\n path,\n 'This field cannot be null. Leave it out if it is optional, or give it a value.',\n ),\n );\n continue;\n }\n issues.push({\n path,\n message: schemaIssue.message,\n code: schemaIssue.code,\n severity: 'invalid',\n });\n }\n }\n\n const stored = validateItemGroup(draft);\n if (issues.length === 0 && stored.success) {\n return { status: 'complete', data: stored.data, issues };\n }\n if (issues.length === 0) {\n // The container and every item satisfy their own checks, yet the group is\n // not storable. Nothing here can name the cause, so hand over the\n // validator's own errors rather than claim the draft is finished.\n for (const error of stored.success ? [] : stored.errors) {\n issues.push({ ...error, severity: 'invalid' });\n }\n }\n const invalid = issues.some((found) => found.severity !== 'incomplete');\n return { status: invalid ? 'invalid' : 'incomplete', issues };\n}\n\n/** The group's own envelope. `title` is optional on a group, unlike an activity. */\nfunction checkGroupIdentity(draft: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n if (draft.schemaVersion !== '1.0') {\n issues.push(\n issue(\n 'schema_version_invalid',\n ['schemaVersion'],\n 'The draft must have schemaVersion \"1.0\". A draft from createItemGroupDraft has it.',\n ),\n );\n }\n if (draft.type !== 'item-group') {\n issues.push(issue('type_mismatch', ['type'], 'The draft\\'s type must be \"item-group\".'));\n }\n if (isMissingId(draft.id)) {\n issues.push(issue('id_required', ['id'], 'The group has no id.'));\n }\n if (!isUnset(draft.shuffle) && draft.shuffle !== 'none' && draft.shuffle !== 'within-group') {\n issues.push(\n issue(\n 'ig_shuffle_invalid',\n ['shuffle'],\n 'Shuffling is either \"none\" or \"within-group\". Leave it out to keep the authored order.',\n ),\n );\n }\n return issues;\n}\n\nconst KINDS = new Set(['text', 'audio', 'video', 'image', 'mixed']);\n/** Which media type each stimulus kind accepts — mirrors `StimulusSchema`'s refinement. */\nconst MEDIA_FOR_KIND: Record<string, readonly string[]> = {\n audio: ['audio'],\n video: ['video', 'embed'],\n image: ['image'],\n mixed: ['audio', 'video', 'image', 'embed'],\n};\n\n/**\n * The passage, recording or image. The split this makes is the one the whole\n * draft contract exists for: a kind nobody has chosen and a body nobody has\n * typed are `incomplete`, while a recording attached to an image stimulus is\n * `invalid` — writing more will not reconcile them.\n */\nfunction checkStimulus(stimulus: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n const at = (...rest: (string | number)[]) => ['stimulus', ...rest];\n\n if (isMissingId(stimulus.id)) {\n issues.push(issue('ig_stimulus_id_required', at('id'), 'The stimulus has no id.'));\n }\n\n const kind = stimulus.kind;\n if (isUnwritten(kind)) {\n issues.push(\n issue(\n 'ig_stimulus_kind_required',\n at('kind'),\n 'Choose what the questions are about: a text, a recording, a video, an image, or a mix.',\n ),\n );\n } else if (typeof kind !== 'string' || !KINDS.has(kind)) {\n // A value of another type is the schema's to refuse.\n if (typeof kind === 'string') {\n issues.push(\n issue(\n 'ig_stimulus_kind_invalid',\n at('kind'),\n `\"${kind}\" is not a stimulus kind. Use text, audio, video, image or mixed.`,\n ),\n );\n }\n // Only the kind-DEPENDENT rules are skipped. The media still has problems\n // of its own — a refused address, a missing description — and returning\n // here left every one of them to the schema, so an unrecognised kind made\n // zod's raw diagnostics appear beside ours.\n if (isRecord(stimulus.media)) {\n issues.push(...checkMedia(stimulus.media, at('media')));\n }\n return issues;\n }\n\n const hasBody = typeof stimulus.body === 'string' && stimulus.body.trim() !== '';\n // One rule, one issue, at `body` — where the schema reports both halves of\n // it. Written as two branches, a `text` stimulus carrying rich text and no\n // plain text reported the same path twice; and keying the second branch on\n // whether `bodyHtml` had CONTENT missed the empty string a cleared rich-text\n // editor leaves behind, which the schema still refuses.\n const htmlPresent = !isUnset(stimulus.bodyHtml);\n if (!hasBody && (kind === 'text' || kind === 'mixed' || htmlPresent)) {\n issues.push(\n issue(\n 'ig_stimulus_body_required',\n at('body'),\n isUnwritten(stimulus.bodyHtml)\n ? 'Write the passage.'\n : 'Write the passage as plain text too. The rich-text version is shown only where a sanitiser is supplied.',\n ),\n );\n }\n\n if (kind !== 'text' && isUnset(stimulus.media)) {\n issues.push(\n issue('ig_stimulus_media_required', at('media'), 'Add the recording, video or image.'),\n );\n } else if (isRecord(stimulus.media)) {\n const allowed = MEDIA_FOR_KIND[kind as string];\n const mediaType = stimulus.media.type;\n if (allowed !== undefined && typeof mediaType === 'string' && !allowed.includes(mediaType)) {\n issues.push(\n issue(\n 'ig_stimulus_media_kind',\n at('media', 'type'),\n `A \"${kind}\" stimulus cannot carry ${mediaType} media. Use ${allowed.join(' or ')}.`,\n ),\n );\n }\n issues.push(...checkMedia(stimulus.media, at('media')));\n }\n return issues;\n}\n\n/**\n * Every item, checked by `validateDraft` for its own type.\n *\n * Re-pathing rather than re-implementing is the point: a multiple-choice\n * question inside a testlet reports exactly the codes a standalone one does,\n * so a consumer's translation table covers both and a rule can never drift\n * between them.\n */\nfunction checkItems(draft: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n const items = isUnset(draft.items) ? [] : draft.items;\n if (!Array.isArray(items)) {\n return issues;\n }\n if (items.length === 0) {\n issues.push(\n issue('ig_items_required', ['items'], 'Add at least one question about this material.'),\n );\n return issues;\n }\n\n const seen = new Set<string>();\n const repeated = new Set<string>();\n for (const [index, item] of items.entries()) {\n if (!isRecord(item)) {\n continue;\n }\n const ordinal = index + 1;\n if (isMissingId(item.id)) {\n issues.push(\n issue('ig_item_id_required', ['items', index, 'id'], `Question ${ordinal} has no id.`),\n );\n } else if (typeof item.id === 'string') {\n if (seen.has(item.id)) {\n repeated.add(item.id);\n }\n seen.add(item.id);\n }\n\n if (item.type === 'item-group') {\n issues.push(\n issue(\n 'ig_item_nested_group',\n ['items', index, 'type'],\n 'Groups do not nest: every item must be an activity.',\n ),\n );\n continue;\n }\n if (isUnwritten(item.type)) {\n issues.push(\n issue(\n 'ig_item_type_required',\n ['items', index, 'type'],\n `Choose what kind of question ${ordinal} is.`,\n ),\n );\n continue;\n }\n if (typeof item.type !== 'string') {\n continue;\n }\n\n let result: DraftValidationResult<unknown>;\n try {\n result = validateDraft(item.type as ActivityType, item);\n } catch {\n // An unregistered type is reported, never thrown — the same choice\n // `validateItemGroup` makes, for the same reason.\n issues.push(\n issue(\n 'ig_item_type_unknown',\n ['items', index, 'type'],\n `\"${item.type}\" is not a registered activity type.`,\n ),\n );\n continue;\n }\n for (const found of result.issues) {\n issues.push({ ...found, path: ['items', String(index), ...found.path] });\n }\n }\n\n for (const id of repeated) {\n issues.push(\n issue('ig_item_id_duplicate', ['items'], `More than one question has the id \"${id}\".`),\n );\n }\n return issues;\n}\n","import { UnknownActivityTypeError } from '../errors.js';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ActivityDataMap, ActivityType } from '../types/activity.js';\nimport type { DraftContext, DraftIssue, DraftValidationResult } from '../types/authoring.js';\nimport { withValidationScope } from '../validation-scope.js';\nimport {\n coveredPathsOf,\n DRAFT_ISSUE_SEVERITY,\n type DraftIssueCode,\n isRecord,\n issue,\n pathKey,\n refusesEmpty,\n} from './issues.js';\n\n/**\n * Tells a draft that is not finished from a draft that is wrong.\n *\n * `validateActivity` answers \"may this be stored?\", and to that question an\n * empty new question and a broken one are the same answer: no. An editor needs\n * the difference — \"Add a title\" is a to-do, \"Only one option can be marked\n * correct\" is an error — so a freshly added question does not read as a\n * failure, disable a whole form, or blank a preview.\n *\n * - `complete` — the draft is a valid activity with nothing left to write.\n * `data` is exactly what `validateActivity` returns for it.\n * - `incomplete` — every problem is something not yet written.\n * - `invalid` — at least one problem is wrong in a way writing more cannot fix.\n *\n * It is stricter than `validateActivity`, never looser: `complete` requires the\n * activity's schema to pass, and a draft can fail here that the schema accepts\n * (a title that is only whitespace). Content stored by an older build can\n * therefore be valid and still not `complete`. `validateActivity` stays the\n * check at your write boundary.\n *\n * Issues come from the type's `authoring.checkDraft`, plus every schema failure\n * it did not already report at that path or inside it. (A failure at the root of\n * the draft counts as reported only by an issue at the root, since every path is\n * inside the root.) Such a failure is added as `invalid`: under the code\n * `null_not_allowed` when the schema refused a `null` there, or an `undefined`\n * entry in a list, and otherwise under the schema's own code and message. A type\n * with no `checkDraft` therefore reports every schema failure as `invalid`.\n *\n * The codes documented in `docs/authoring.md` are a contract, and each is\n * reported with its documented severity, whichever check reports it. A code\n * passed through from the schema is not a contract: the code and its English\n * message belong to the schema library, so give a code you do not recognise a\n * generic message of your own.\n *\n * @throws UnknownActivityTypeError when `type` has no registered descriptor —\n * including `'item-group'`, which is a container, not an activity type.\n */\nexport function validateDraft<T extends ActivityType>(\n type: T,\n draft: unknown,\n): DraftValidationResult<ActivityDataMap[T]> {\n // The type's checks and its schema read the same strings: one scope lets the\n // expensive normalisation behind both run once.\n return withValidationScope(() => validateDraftInScope(type, draft));\n}\n\nfunction validateDraftInScope<T extends ActivityType>(\n type: T,\n draft: unknown,\n): DraftValidationResult<ActivityDataMap[T]> {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(type));\n }\n\n const reported =\n isRecord(draft) && descriptor.authoring?.checkDraft !== undefined\n ? descriptor.authoring.checkDraft(draft).map(normalise)\n : [];\n const issues: DraftIssue[] = [...reported];\n\n // `reportInput` records on each issue the value its check was given, which is\n // how a refused `null` is told apart from a rule that merely points at one.\n const parsed = descriptor.schema.safeParse(draft, { reportInput: true });\n if (!parsed.success) {\n const covered = coveredPathsOf(reported);\n const reportedEmpty = new Set<string>();\n for (const schemaIssue of parsed.error.issues) {\n const path = schemaIssue.path.map(String);\n if (covered.has(pathKey(path))) {\n continue;\n }\n // `null` is how many editors and databases spell \"no value\". Where the\n // schema refuses one, name it under one documented code, for every type,\n // rather than hand over the schema library's own diagnostic.\n if (path.length > 0 && refusesEmpty(draft, schemaIssue)) {\n const key = JSON.stringify(path);\n if (!reportedEmpty.has(key)) {\n reportedEmpty.add(key);\n issues.push(\n issue(\n 'null_not_allowed',\n path,\n typeof schemaIssue.path.at(-1) === 'number'\n ? 'This entry has no value. Remove it, or fill it in.'\n : 'This field cannot be null. Leave it out if it is optional, or give it a value.',\n ),\n );\n }\n continue;\n }\n issues.push({\n path,\n message: schemaIssue.message,\n code: schemaIssue.code,\n severity: 'invalid',\n });\n }\n }\n\n if (parsed.success && issues.length === 0) {\n return { status: 'complete', data: parsed.data as ActivityDataMap[T], issues };\n }\n const invalid = issues.some((found) => found.severity !== 'incomplete');\n return { status: invalid ? 'invalid' : 'incomplete', issues };\n}\n\n/**\n * A new, empty draft of an activity type, for an editor to start from.\n *\n * Every required field is present and nothing is authored, so the draft comes\n * back from {@link validateDraft} as `incomplete`, and `validateActivity`\n * rejects it until someone writes it. The SDK invents no ids: `newId` is called\n * once per id the draft needs, and must return a different non-empty string each\n * time.\n *\n * ```ts\n * const draft = createDraft('multiple-choice', { newId: () => crypto.randomUUID() });\n * ```\n *\n * @throws UnknownActivityTypeError when `type` has no registered descriptor.\n * @throws Error when the type declares no `authoring.createDraft`, or when\n * `newId` returns an empty or repeated id.\n */\nexport function createDraft<T extends ActivityType>(\n type: T,\n context: DraftContext,\n): ActivityDataMap[T] {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(type));\n }\n const create = descriptor.authoring?.createDraft;\n if (create === undefined) {\n throw new Error(\n `Activity type \"${String(type)}\" declares no authoring.createDraft, so there is no empty draft to create. ` +\n 'Build the draft yourself; validateDraft works for every registered type.',\n );\n }\n const issued = new Set<string>();\n const newId = (): string => {\n const id: unknown = context.newId();\n if (typeof id !== 'string' || id === '') {\n throw new Error('createDraft: newId() must return a non-empty string.');\n }\n if (issued.has(id)) {\n throw new Error(\n `createDraft: newId() returned \"${id}\" twice. Ids within one draft must differ — two options sharing an id cannot be scored apart.`,\n );\n }\n issued.add(id);\n return id;\n };\n return create({ newId }) as ActivityDataMap[T];\n}\n\n/**\n * A check's issue as `validateDraft` reports it.\n *\n * A documented code carries its documented severity, whichever check reports\n * it. Any other code keeps the check's severity, and one that is not\n * `'incomplete'` — misspelled, or missing — is reported as `invalid`, so the\n * mistake fails closed. Path segments become strings, as the schema's are, so a\n * list index given as a number still covers the schema's failure there.\n */\nfunction normalise(found: DraftIssue): DraftIssue {\n const documented = Object.hasOwn(DRAFT_ISSUE_SEVERITY, found.code)\n ? DRAFT_ISSUE_SEVERITY[found.code as DraftIssueCode]\n : undefined;\n return {\n ...found,\n path: found.path.map(String),\n severity: documented ?? (found.severity === 'incomplete' ? 'incomplete' : 'invalid'),\n };\n}\n\nexport { createItemGroupDraft, validateItemGroupDraft } from './item-group.js';\n","import { ActivitySchemaError, UnknownActivityTypeError } from './errors.js';\nimport { MEDIA_FIELD_POLICY } from './registry/builtins.js';\nimport { getActivityTypeDescriptor } from './registry/index.js';\nimport type { FieldPolicy, Sensitivity } from './registry/registry.js';\nimport { RedactedItemGroupSchema } from './schemas/item-group.js';\nimport type { ItemGroup } from './types/item-group.js';\n\n/**\n * A learner-safe projection of activity data produced by {@link redact}:\n * the activity's public fields plus the `redacted: true` marker. Renderable\n * and validatable (each built-in type registers a strict redacted schema),\n * but stripped of the answer key, scoring rules, authored feedback, and\n * author-only assets.\n */\nexport interface RedactedActivityData {\n redacted: true;\n schemaVersion: string;\n type: string;\n id: string;\n title: string;\n [key: string]: unknown;\n}\n\n/** Options for {@link redact}. */\nexport interface RedactOptions {\n /**\n * Which sensitivity tiers to keep beyond `public`:\n * - `'none'` (default) — public fields only; the output satisfies the\n * type's strict redacted schema and `assertRedacted`.\n * - `'after-submit'` — public + answer-key fields (for post-submission\n * review renders). `author-only` fields and unclassified fields are\n * STILL removed; the output will NOT pass `assertRedacted`.\n */\n reveal?: 'none' | 'after-submit';\n /**\n * Per-call sensitivity overrides, merged over the type's registered\n * `fieldPolicy` (top-level keys replace; nested objects merge one level).\n *\n * Sensitivity is partly a PEDAGOGICAL decision, not purely a security one —\n * whether a rubric or a hint is learner-visible differs legitimately between\n * deployments — and the SDK must not freeze that choice. Use this to tighten\n * a field the SDK ships as `public`:\n *\n * ```ts\n * redact(essay, { policy: { rubric: 'author-only' } });\n * ```\n *\n * Overrides can only be applied to fields; they cannot re-open a field the\n * caller has not classified, because unclassified still means removed.\n * Note that tightening below what the type's `redactedSchema` requires is\n * allowed — the schema check only rejects payloads that reveal MORE than\n * the learner-safe shape.\n */\n policy?: FieldPolicy;\n}\n\n/** Merges per-call overrides over a registered policy, one level deep. */\nfunction mergePolicy(base: FieldPolicy, overrides: FieldPolicy | undefined): FieldPolicy {\n if (overrides === undefined) {\n return base;\n }\n const merged: Record<string, Sensitivity | FieldPolicy> = { ...base };\n for (const [key, override] of Object.entries(overrides)) {\n const current = merged[key];\n merged[key] =\n typeof override === 'object' && typeof current === 'object'\n ? { ...current, ...override }\n : override;\n }\n return merged;\n}\n\nfunction isSensitivity(value: Sensitivity | FieldPolicy): value is Sensitivity {\n return typeof value === 'string';\n}\n\nfunction keepField(sensitivity: Sensitivity, reveal: 'none' | 'after-submit'): boolean {\n if (sensitivity === 'public') {\n return true;\n }\n return sensitivity === 'answer-key' && reveal === 'after-submit';\n}\n\n/** An object projection that kept no fields at all. Arrays are never dropped. */\nfunction isEmptyObject(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Object.keys(value).length === 0\n );\n}\n\nfunction redactValue(\n value: unknown,\n policy: FieldPolicy,\n reveal: 'none' | 'after-submit',\n): unknown {\n if (Array.isArray(value)) {\n return value.map((element) => redactValue(element, policy, reveal));\n }\n if (value === null || typeof value !== 'object') {\n // A nested FieldPolicy cannot classify a primitive's sub-fields; the\n // policy author classified an object shape that is not there. Fail\n // closed: drop it (handled by the caller returning undefined).\n return undefined;\n }\n\n const source = value as Record<string, unknown>;\n const output: Record<string, unknown> = {};\n for (const [key, fieldValue] of Object.entries(source)) {\n if (fieldValue === undefined) {\n continue;\n }\n const classification = policy[key];\n if (classification === undefined) {\n // Fail closed: unclassified fields are never emitted, at any reveal\n // level. Adding a field without classifying it hides it — never leaks it.\n continue;\n }\n if (isSensitivity(classification)) {\n if (keepField(classification, reveal)) {\n output[key] = fieldValue;\n }\n continue;\n }\n const nested = redactValue(fieldValue, classification, reveal);\n // A nested projection that emitted nothing is omitted rather than emitted\n // as `{}`. \"Nothing survived redaction\" and \"the field was absent\" are the\n // same thing to a learner — and without this, giving an all-`answer-key`\n // object a nested policy would turn its absence under `reveal: 'none'`\n // into an empty object, changing every existing projection.\n if (nested !== undefined && !isEmptyObject(nested)) {\n output[key] = nested;\n }\n }\n return output;\n}\n\n/**\n * Produces the learner-safe projection of activity data (R7), driven by the\n * `fieldPolicy` registered for `data.type`. Fail-closed and exhaustive by\n * construction: a field the policy does not classify is removed — including\n * unknown passthrough fields — so a NEW field added by a future SDK or a\n * consumer sidecar can never leak through an out-of-date redactor.\n *\n * With the default `reveal: 'none'`, the output validates against the type's\n * strict redacted schema (verified here; an invalid projection throws\n * {@link ActivitySchemaError} rather than shipping an unproven payload).\n *\n * @throws UnknownActivityTypeError when `data.type` is not registered.\n * @throws Error when the registered descriptor declares no `fieldPolicy`\n * (redaction cannot guess sensitivities).\n */\nexport function redact<T extends { type: string }>(\n data: T,\n options: RedactOptions = {},\n): RedactedActivityData {\n const reveal = options.reveal ?? 'none';\n const descriptor = getActivityTypeDescriptor(data.type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(data.type));\n }\n if (descriptor.fieldPolicy === undefined) {\n throw new Error(\n `Activity type \"${descriptor.type}\" has no fieldPolicy; redact() cannot run fail-closed redaction without one.`,\n );\n }\n\n const effectivePolicy = mergePolicy(descriptor.fieldPolicy, options.policy);\n const projected = redactValue(data, effectivePolicy, reveal) as Record<string, unknown>;\n const result = { ...projected, redacted: true as const } as RedactedActivityData;\n\n if (reveal === 'none' && descriptor.redactedSchema !== undefined) {\n const parsed = descriptor.redactedSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe redacted projection: it carries the\n * `redacted: true` marker and, when its type registers a strict redacted\n * schema, validates against it (proving the absence of answer-key fields).\n * Use this at the server boundary before sending activity data to a client\n * that must not hold the key.\n */\nexport function assertRedacted(data: unknown): asserts data is RedactedActivityData {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('unknown', [\n { path: [], message: 'Redacted activity data must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError(String(candidate.type ?? 'unknown'), [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redact() projection.',\n code: 'custom',\n },\n ]);\n }\n const type = typeof candidate.type === 'string' ? candidate.type : '';\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(type);\n }\n if (descriptor.redactedSchema === undefined) {\n // Fail closed: without a registered redacted schema there is no way to\n // PROVE the absence of answer-key fields, and a marker alone proves\n // nothing (any object can carry `redacted: true`).\n throw new ActivitySchemaError(descriptor.type, [\n {\n path: [],\n message: `Activity type \"${descriptor.type}\" registers no redactedSchema; assertRedacted cannot prove this payload is learner-safe.`,\n code: 'custom',\n },\n ]);\n }\n const parsed = descriptor.redactedSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n}\n\n/**\n * Sensitivity of a stimulus. Everything is learner-visible — that is what a\n * stimulus IS — except the author transcript. Fail-closed like every other\n * policy: a field added to `Stimulus` without a classification here is\n * dropped, never leaked.\n */\nconst STIMULUS_FIELD_POLICY: FieldPolicy = {\n id: 'public',\n kind: 'public',\n title: 'public',\n body: 'public',\n bodyHtml: 'public',\n media: MEDIA_FIELD_POLICY,\n locale: 'public',\n attribution: 'public',\n transcript: 'author-only',\n};\n\n/** The group container's own fields. `items` is handled separately, per item type. */\nconst ITEM_GROUP_FIELD_POLICY: FieldPolicy = {\n schemaVersion: 'public',\n type: 'public',\n id: 'public',\n title: 'public',\n // See the note on the built-in activity policies: a slot key is identity,\n // and identity has to cross the redaction boundary intact.\n slotKey: 'public',\n shuffle: 'public',\n stimulus: STIMULUS_FIELD_POLICY,\n};\n\n/** A learner-safe item group: the container with its marker, holding `redact()` projections. */\nexport type RedactedItemGroup = ItemGroup<RedactedActivityData> & { redacted: true };\n\n/**\n * Produces the learner-safe projection of an item group: the container and\n * stimulus under their own fail-closed policy (the author transcript goes;\n * the passage, media and attribution stay — the learner is meant to see\n * them), and every item through {@link redact} with the same `options`, so\n * a per-call `policy` tightens each item exactly as it would alone.\n *\n * With the default `reveal: 'none'` the container is verified against the\n * strict redacted schema; each item was already verified by `redact`.\n */\nexport function redactItemGroup<TItem extends { type: string }>(\n group: ItemGroup<TItem>,\n options: RedactOptions = {},\n): RedactedItemGroup {\n const reveal = options.reveal ?? 'none';\n const { items, ...container } = group;\n const projected = redactValue(container, ITEM_GROUP_FIELD_POLICY, reveal) as Record<\n string,\n unknown\n >;\n const result = {\n ...projected,\n items: items.map((item) => redact(item, options)),\n redacted: true as const,\n } as RedactedItemGroup;\n\n if (reveal === 'none') {\n const parsed = RedactedItemGroupSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe item group: it carries the marker,\n * its container and stimulus satisfy the strict redacted schema (so no\n * transcript, no unclassified field), and EVERY item passes\n * {@link assertRedacted} against its own type's redacted schema. Item\n * failures are reported at `items.<index>.…`. Use it at the server boundary\n * before sending a group to a client that must not hold the key.\n */\nexport function assertRedactedItemGroup(data: unknown): asserts data is RedactedItemGroup {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('item-group', [\n { path: [], message: 'Redacted item group must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError('item-group', [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redactItemGroup() projection.',\n code: 'custom',\n },\n ]);\n }\n const parsed = RedactedItemGroupSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n parsed.data.items.forEach((item, index) => {\n try {\n assertRedacted(item);\n } catch (error) {\n if (error instanceof ActivitySchemaError) {\n throw new ActivitySchemaError(\n 'item-group',\n error.errors.map((issue) => ({\n ...issue,\n path: ['items', String(index), ...issue.path],\n })),\n );\n }\n throw error;\n }\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/index.cjs","../src/content-hash.ts","../src/shuffle.ts","../src/item-group.ts","../src/media-budget.ts","../src/attempt-plan.ts","../src/attempt-state.ts","../src/authoring/item-group.ts","../src/authoring/index.ts","../src/redact.ts"],"names":["issue"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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AACR,IAAA;AACL,MAAA;AACE,QAAA;AACS,QAAA;AACG,QAAA;AAGd,MAAA;AACF,IAAA;AACF,EAAA;AAEa,EAAA;AACJ,IAAA;AACC,MAAA;AACR,IAAA;AACS,EAAA;AACO,IAAA;AACV,IAAA;AACU,IAAA;AACP,MAAA;AACL,QAAA;AACE,UAAA;AACG,UAAA;AACO,UAAA;AACZ,QAAA;AACF,MAAA;AACF,IAAA;AACe,IAAA;AACjB,EAAA;AACO,EAAA;AACT;AAUoB;AACY,EAAA;AAChB,EAAA;AACH,EAAA;AACF,IAAA;AACT,EAAA;AACU,EAAA;AACD,IAAA;AACC,MAAA;AACR,IAAA;AACO,IAAA;AACT,EAAA;AAEa,EAAA;AACI,EAAA;AACL,EAAA;AACI,IAAA;AACZ,MAAA;AACF,IAAA;AACgB,IAAA;AACA,IAAA;AACP,MAAA;AACC,QAAA;AACR,MAAA;AACS,IAAA;AACI,MAAA;AACF,QAAA;AACX,MAAA;AACc,MAAA;AAChB,IAAA;AAES,IAAA;AACA,MAAA;AACL,QAAA;AACE,UAAA;AACU,UAAA;AACV,UAAA;AACF,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACgB,IAAA;AACP,MAAA;AACL,QAAA;AACE,UAAA;AACU,UAAA;AACV,UAAA;AACF,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACgB,IAAA;AACd,MAAA;AACF,IAAA;AAEI,IAAA;AACA,IAAA;AACO,MAAA;AACK,IAAA;AASR,MAAA;AACE,QAAA;AACR,MAAA;AACO,MAAA;AACL,QAAA;AACE,UAAA;AACU,UAAA;AACD,UAAA;AACX,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACW,IAAA;AACK,MAAA;AAChB,IAAA;AACF,EAAA;AAEiB,EAAA;AACR,IAAA;AACC,MAAA;AACR,IAAA;AACF,EAAA;AACO,EAAA;AACT;APifoB;AACA;AQj0BJ;AAMP,EAAA;AACT;AAES;AAID,EAAA;AACF,EAAA;AACQ,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AEe,EAAA;AACE,IAAA;AACH,IAAA;AACA,MAAA;AACR,QAAA;AACO,QAAA;AACCA,UAAAA;AACGA,UAAAA;AACHA,UAAAA;AACN,QAAA;AACJ,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAUgB;AACH,EAAA;AACC,IAAA;AACI,MAAA;AACb,IAAA;AACH,EAAA;AACkB,EAAA;AACJ,EAAA;AACF,IAAA;AACR,MAAA;AACS,QAAA;AACE,QAAA;AACH,QAAA;AACR,MAAA;AACD,IAAA;AACH,EAAA;AACe,EAAA;AACH,EAAA;AACA,IAAA;AACR,MAAA;AACa,MAAA;AACLA,QAAAA;AACGA,QAAAA;AACHA,QAAAA;AACN,MAAA;AACJ,IAAA;AACF,EAAA;AACkB,EAAA;AACZ,IAAA;AACF,MAAA;AACc,IAAA;AACV,MAAA;AACQ,QAAA;AACR,UAAA;AACM,UAAA;AACDA,YAAAA;AACI,YAAA;AACP,UAAA;AACJ,QAAA;AACF,MAAA;AACM,MAAA;AACR,IAAA;AACD,EAAA;AACH;AT8yBoB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/index.cjs","sourcesContent":[null,"/**\n * Content fingerprinting — \"is this the same content the learner was served?\"\n *\n * A recorded attempt outlives the content it was taken against. Papers get\n * corrected, a typo is fixed, an option is reworded — and six months later a\n * remark, an appeal, or a per-item analysis is run against content that is no\n * longer what the learner saw. Nothing warns anybody, because the ids all still\n * match. A fingerprint stored with the attempt turns that silent drift into a\n * question somebody can answer.\n */\n\n/**\n * Deterministic JSON: object keys sorted, arrays left in order, `undefined`\n * omitted from objects (matching `JSON.stringify`) and rendered as `null`\n * inside arrays.\n *\n * Key order is the whole point. Two objects that differ only in the order\n * their keys happened to be written are the SAME content, and a fingerprint\n * that disagreed would raise a false alarm every time a payload made a\n * round-trip through a different serializer.\n */\nexport function canonicalJson(value: unknown, seen: Set<object> = new Set()): string {\n if (value === null) {\n return 'null';\n }\n if (typeof value === 'number') {\n // JSON.stringify renders every non-finite number as `null`, which would\n // fingerprint NaN, Infinity and -Infinity identically — and identically to\n // a real null. Content carrying one of those is already broken; it must at\n // least be distinguishable.\n return Number.isFinite(value) ? JSON.stringify(value === 0 ? 0 : value) : `\"#${String(value)}\"`;\n }\n if (typeof value === 'string' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n return `\"#${value.toString()}n\"`;\n }\n if (typeof value === 'object') {\n // A cycle would recurse until the stack gave out, and a stack overflow\n // while fingerprinting an exam is a far worse failure than being told the\n // content is not serialisable. Content is JSON, so this should never fire —\n // but \"should never\" is not a guard.\n if (seen.has(value)) {\n throw new Error(\n 'canonicalJson: the value contains a circular reference and cannot be fingerprinted.',\n );\n }\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return `[${value.map((element) => (element === undefined ? 'null' : canonicalJson(element, seen))).join(',')}]`;\n }\n const source = value as Record<string, unknown>;\n const parts: string[] = [];\n for (const key of Object.keys(source).sort()) {\n const entry = source[key];\n if (entry === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(key)}:${canonicalJson(entry, seen)}`);\n }\n return `{${parts.join(',')}}`;\n } finally {\n // Released on the way out, so a value legitimately appearing twice in\n // SIBLING positions is not mistaken for a cycle.\n seen.delete(value);\n }\n }\n // Functions, symbols and undefined have no place in content.\n return 'null';\n}\n\nconst FNV_OFFSET = 14695981039346656037n;\nconst FNV_PRIME = 1099511628211n;\nconst MASK64 = (1n << 64n) - 1n;\n\n/**\n * FNV-1a over the UTF-8 bytes of `input`, as 16 lowercase hex digits.\n *\n * **This is a change-detection fingerprint, not a tamper-evident signature.**\n * It is deterministic across runtimes and dependency-free, which is what makes\n * it usable in a stored grade record — but an adversary who can edit content\n * can also, with effort, preserve the fingerprint. If you need the stronger\n * property, sign the plan with a key the content author does not hold; this\n * exists to catch honest edits, which is what actually happens.\n */\nexport function fingerprint(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let hash = FNV_OFFSET;\n for (const byte of bytes) {\n hash = ((hash ^ BigInt(byte)) * FNV_PRIME) & MASK64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n\n/**\n * Fingerprints any JSON-serialisable value through {@link canonicalJson}, so\n * the result depends on the content and not on how it was written.\n */\nexport function contentHash(value: unknown): string {\n return fingerprint(canonicalJson(value));\n}\n","/**\n * Seeded, deterministic shuffling — the ONE algorithm every presentation-order\n * decision in the SDK goes through: option order in a multiple-choice item,\n * item order inside an item group, entry order in a sequence. A server and a\n * client holding the same seed derive the same order, and an order recorded\n * against an attempt can be rebuilt later from nothing but its seed.\n *\n * STABILITY: the hash and the generator are part of the wire contract. A\n * stored attempt may hold only a seed and rely on this function to reproduce\n * the order it presented; changing either would silently re-order every\n * recorded attempt. Any change here is a package major, and the pinned\n * permutation test exists so an accidental one fails loudly.\n */\n\n/** FNV-1a hash of a string → unsigned 32-bit integer. */\nexport function hashSeed(input: string): number {\n let h = 2166136261 >>> 0;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 16777619) >>> 0;\n }\n return h;\n}\n\n/**\n * Which draw the Fisher–Yates step uses.\n *\n * - `1` — the original. Takes the index from the LCG's LOW bits (`s % (i+1)`).\n * - `2` — takes it from the HIGH bits. Same LCG, same seed, different draw.\n *\n * The difference is not cosmetic. In a linear congruential generator with a\n * power-of-two modulus, the low bits have drastically short periods: bit 0\n * alternates, bit 1 has period 4, and so on. `% (i+1)` reads exactly those\n * bits, so consecutive draws are correlated and most permutations become\n * unreachable FOR EVERY SEED THAT WILL EVER EXIST:\n *\n * | items | permutations | reachable under v1 | under v2 |\n * | ----- | ------------ | ------------------ | -------- |\n * | 4 | 24 | 12 | 24 |\n * | 5 | 120 | 60 | 120 |\n * | 6 | 720 | 180 | 720 |\n *\n * It also biases WHERE an option lands. On a four-option item under v1 the\n * last authored option takes the first presented position 8.3% of the time\n * and the second position 41.7%, against 25% each — a systematic advantage to\n * anyone who notices. For a summative exam that is a fairness defect, not a\n * curiosity.\n *\n * v1 remains the DEFAULT regardless, because these permutations are a wire\n * contract: an attempt may be stored with nothing but its seed, and a review\n * render of that attempt has to reproduce the order the learner actually saw.\n * Switching the default would silently re-order every recorded attempt, so it\n * is a package major — scheduled, not smuggled in. Choose v2 for new content\n * where no attempt has been recorded yet.\n */\nexport type ShuffleVersion = 1 | 2;\n\n/** Options for {@link seededShuffle}. */\nexport interface SeededShuffleOptions {\n /** Draw algorithm. Defaults to `1` — see {@link ShuffleVersion}. */\n version?: ShuffleVersion;\n}\n\n/** LCG-driven Fisher–Yates over a 32-bit seed; returns a permutation (no loss, no duplicate). */\nfunction shuffleWithSeed<T>(items: readonly T[], seed: number, version: ShuffleVersion): T[] {\n const out = [...items];\n let s = seed >>> 0 || 1;\n for (let i = out.length - 1; i > 0; i -= 1) {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n // v1 reads the low bits; v2 scales the whole 32-bit word, which uses the\n // high bits and reaches every permutation.\n const j = version === 2 ? Math.floor((s / 4294967296) * (i + 1)) : s % (i + 1);\n [out[i], out[j]] = [out[j] as T, out[i] as T];\n }\n return out;\n}\n\n/**\n * Returns a new array holding a permutation of `items` determined entirely by\n * `seed` (and the chosen {@link ShuffleVersion}): same inputs, same order —\n * across processes, runtimes and releases. The input is never mutated.\n *\n * Compose the seed from the attempt identity AND the thing being shuffled\n * (`${attemptId}:${itemId}`), so two shuffles in one attempt do not share an\n * order.\n */\nexport function seededShuffle<T>(\n items: readonly T[],\n seed: string,\n options: SeededShuffleOptions = {},\n): T[] {\n return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);\n}\n","import { seededShuffle } from './shuffle.js';\nimport type { ItemGroup, SequenceEntry, SequenceSlot } from './types/item-group.js';\n\n/** Narrows a sequence entry to an item group. */\nexport function isItemGroup<TItem extends { type: string }>(\n entry: SequenceEntry<TItem>,\n): entry is ItemGroup<TItem> {\n return entry.type === 'item-group';\n}\n\n/**\n * An entry's declared `slotKey`, if it has one. Read structurally rather than\n * from the type, because a plain activity may carry one too — `slotKey` is a\n * property of an item's PLACE in a paper, so any entry can declare it without\n * every activity schema having to know about assessment assembly.\n *\n * A key containing `.` is rejected: `.` separates a group from its item in a\n * slot id, so `\"a.b\"` as a group key would be indistinguishable from item `b`\n * of group `a`.\n */\nfunction keyOf(entry: unknown): string | undefined {\n const key = (entry as { slotKey?: unknown }).slotKey;\n if (key === undefined) {\n return undefined;\n }\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `flattenSequence: slotKey must be a non-empty string, received ${String(key)}.`,\n );\n }\n if (key.includes('.')) {\n throw new Error(\n `flattenSequence: slotKey \"${key}\" contains a \".\" , which separates a group from its item ` +\n 'in a slot id. Choose a key without it, or the two become indistinguishable.',\n );\n }\n return key;\n}\n\n/** Options for {@link flattenSequence}. */\nexport interface FlattenSequenceOptions {\n /**\n * Shuffle the top-level entries. A group moves as ONE block — its items are\n * never interleaved with other entries — which is the reason a group exists\n * as a container rather than as a flag on each item.\n */\n shuffleEntries?: boolean;\n /**\n * Seed for every shuffle in this call: the entries, and each group whose\n * `shuffle` is `within-group`. REQUIRED whenever anything shuffles. The SDK\n * never invents one, because the server that stores an attempt and the\n * client that renders it must derive the SAME order, and only a shared seed\n * makes that true. The attempt id is the natural choice.\n */\n seed?: string;\n}\n\n/**\n * Turns a sequence definition — loose activities and item groups, in authored\n * order — into the ordered list of slots to present. Pure and deterministic:\n * call it on the server to record an attempt's order, and on the client to\n * render it, and the two agree.\n *\n * Shuffling is opt-in and seeded. Groups are shuffle-atomic: with\n * `shuffleEntries` a group changes position but stays one contiguous block,\n * and only a group that declares `shuffle: 'within-group'` has its items\n * reordered. Every slot carries a `slotId` derived from the authored\n * position, so identities survive shuffling.\n *\n * @throws Error when a shuffle is requested without a `seed`.\n */\nexport function flattenSequence<TItem extends { id: string; type: string }>(\n entries: readonly SequenceEntry<TItem>[],\n options: FlattenSequenceOptions = {},\n): SequenceSlot<TItem>[] {\n const shuffleEntries = options.shuffleEntries === true;\n const needsSeed =\n shuffleEntries ||\n entries.some((entry) => isItemGroup(entry) && entry.shuffle === 'within-group');\n if (needsSeed && options.seed === undefined) {\n throw new Error(\n 'flattenSequence: a seed is required when shuffling (shuffleEntries, or a group with ' +\n 'shuffle: \"within-group\"). Pass the attempt id so the server and the client derive the same order.',\n );\n }\n const seed = options.seed ?? '';\n\n // Carry the AUTHORED index through the shuffle: slot identity comes from\n // where an entry was written, never from where it happens to be shown.\n const authored = entries.map((entry, entryIndex) => ({ entry, entryIndex }));\n const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`) : authored;\n\n const slots: SequenceSlot<TItem>[] = [];\n for (const { entry, entryIndex } of ordered) {\n // An authored `slotKey` wins over the positional path. A positional id is\n // only valid against ONE version of the entries array; a declared key\n // survives insertion, deletion and re-ordering, which is what makes a\n // stored slot id safe to re-grade against later.\n const entryKey = keyOf(entry) ?? String(entryIndex);\n if (!isItemGroup(entry)) {\n slots.push({ slotId: entryKey, index: slots.length, activity: entry });\n continue;\n }\n // An empty group contributes no slots, so it would DISAPPEAR — stimulus,\n // questions and all — from a sequence that still looks well-formed. A\n // listening section filtered to nothing upstream would leave an 18-slot\n // paper presented as 12 slots, and `composeAssessmentScore` would then\n // report a `final` grade over the survivors with nothing pending. The\n // type already declares `items` non-empty; this makes that enforceable at\n // the point where the omission would otherwise become invisible.\n if (entry.items.length === 0) {\n throw new Error(\n `flattenSequence: item group \"${entry.id}\" has no items. An empty group would silently ` +\n 'remove its stimulus and its questions from the presented sequence.',\n );\n }\n const items = entry.items.map((item, itemIndex) => ({ item, itemIndex }));\n const presented =\n entry.shuffle === 'within-group' ? seededShuffle(items, `${seed}:group:${entry.id}`) : items;\n const size = presented.length;\n presented.forEach(({ item, itemIndex }, position) => {\n slots.push({\n slotId: `${entryKey}.${keyOf(item) ?? String(itemIndex)}`,\n index: slots.length,\n activity: item,\n group: {\n id: entry.id,\n ...(entry.title !== undefined ? { title: entry.title } : {}),\n stimulus: entry.stimulus,\n position,\n size,\n },\n });\n });\n }\n\n // Positional ids are unique by construction; authored keys are not. Two\n // entries sharing a key would collapse into one identity, so every response\n // stored against it would overwrite the other's — and `composeAssessmentScore`\n // would score one question twice and the other never.\n const seenSlotIds = new Set<string>();\n // ENTRY keys are checked separately, because a loose entry keyed \"reading\"\n // and a group keyed \"reading\" produce slot ids \"reading\" and \"reading.0\"\n // that never collide — while everything reading the entry prefix (the\n // pager's stimulus grouping, for one) treats them as the same entry, and\n // shows the group's passage above the unrelated loose question. Positional\n // ids could not express this: an index is a loose item or a group, never\n // both.\n const seenEntryKeys = new Set<string>();\n for (const slot of slots) {\n if (seenSlotIds.has(slot.slotId)) {\n throw new Error(\n `flattenSequence: duplicate slot id \"${slot.slotId}\". Two entries declare the same ` +\n 'slotKey, so responses stored against them could not be told apart.',\n );\n }\n seenSlotIds.add(slot.slotId);\n }\n for (const { entry, entryIndex } of ordered) {\n const entryKey = keyOf(entry) ?? String(entryIndex);\n if (seenEntryKeys.has(entryKey)) {\n throw new Error(\n `flattenSequence: duplicate entry key \"${entryKey}\". A loose activity and an item group ` +\n 'cannot share a slotKey — their slot ids would not collide, but everything that reads ' +\n 'the entry they belong to would treat them as one entry.',\n );\n }\n seenEntryKeys.add(entryKey);\n }\n return slots;\n}\n","import type { ActivityMedia, NativeControlHint } from './types/activity.js';\nimport type { AttemptPlan } from './types/attempt-plan.js';\nimport type { MediaPlayLedger, MediaPlayLedgerEntry } from './types/media-budget.js';\n\nexport type {\n MediaPlayClaim,\n MediaPlayGrant,\n MediaPlayLedger,\n MediaPlayLedgerEntry,\n} from './types/media-budget.js';\n\n/**\n * The authored-entry prefix of a slot id: `\"3\"` for both `\"3\"` and `\"3.1\"`.\n *\n * Safe because every slot id in a plan is produced by `flattenSequence`, and\n * `keyOf` rejects a `.` in both an entry key and an item key — so the first\n * `.` is always the group/item separator.\n */\nexport function entryKeyOf(slotId: string): string {\n const dot = slotId.indexOf('.');\n return dot === -1 ? slotId : slotId.slice(0, dot);\n}\n\n/** Budget key for an activity's OWN `data.media`. One budget per slot. */\nexport function slotMediaKey(slotId: string): string {\n return `slot:${slotId}`;\n}\n\n/**\n * Budget key for an item group's `stimulus.media`.\n *\n * Keyed by the ENTRY, not the slot: one recording serves every question in the\n * group, so `\"3.0\"`…`\"3.5\"` share one budget. Keying by `slotId` would hand a\n * six-question `maxPlays: 2` listening group twelve plays; keying by\n * `stimulus.id` would collide across papers, which is the thing slot keys and\n * `planHash` exist to prevent.\n */\nexport function stimulusMediaKey(slotId: string): string {\n return `stimulus:${entryKeyOf(slotId)}`;\n}\n\n/** A playback policy with every default resolved. One derivation, used everywhere. */\nexport interface ResolvedPlaybackPolicy {\n controls: 'native' | 'minimal';\n /** `null` when the recording is unbudgeted. */\n maxPlays: number | null;\n seek: 'allow' | 'none';\n rate: 'allow' | 'fixed';\n nativeControlHints: readonly NativeControlHint[];\n}\n\n/**\n * Resolves the defaults once, so the schema refinements, the plan and the\n * renderer cannot drift apart about what a policy means.\n *\n * Absent `playback` resolves to exactly the SDK's pre-0.8.0 behaviour:\n * `controls: 'native'`, no budget, free seeking, free speed, no hints.\n */\nexport function resolvePlaybackPolicy(media: ActivityMedia): ResolvedPlaybackPolicy {\n const p = media.playback;\n const budgeted = typeof p?.maxPlays === 'number';\n const seek = p?.seek ?? (budgeted ? 'none' : 'allow');\n const rate = p?.rate ?? 'allow';\n const controls =\n p?.controls ?? (budgeted || seek === 'none' || rate === 'fixed' ? 'minimal' : 'native');\n return {\n controls,\n maxPlays: budgeted ? (p?.maxPlays as number) : null,\n seek,\n rate,\n nativeControlHints: p?.nativeControlHints ?? [],\n };\n}\n\n/**\n * Every budgeted recording a plan contains: budget key → the `maxPlays` that\n * was frozen when the attempt was planned.\n *\n * Use it to build the storage rows an attempt needs, and to check a stored\n * ledger against the paper it claims to belong to.\n */\nexport function planMediaBudgets(plan: AttemptPlan): Record<string, number> {\n const out: Record<string, number> = {};\n for (const slot of plan.slots) {\n for (const budget of slot.mediaBudgets ?? []) {\n out[budget.key] = budget.maxPlays;\n }\n }\n return out;\n}\n\nfunction assertEntry(key: string, entry: MediaPlayLedgerEntry): void {\n if (\n entry === null ||\n typeof entry !== 'object' ||\n !Number.isInteger(entry.plays) ||\n entry.plays < 0\n ) {\n throw new Error(\n `serializeMediaPlayLedger: play count for ${JSON.stringify(key)} is ` +\n `${JSON.stringify((entry as MediaPlayLedgerEntry | null)?.plays)}. A count must be a ` +\n 'non-negative integer; Number(a NULL column) is the usual cause.',\n );\n }\n if (entry.at !== undefined && (!Number.isFinite(entry.at) || entry.at < 0)) {\n throw new Error(\n `serializeMediaPlayLedger: position for ${JSON.stringify(key)} is ` +\n `${JSON.stringify(entry.at)}. A position must be a finite number of seconds >= 0.`,\n );\n }\n}\n\n/**\n * Validates a set of spent-play counts against the plan that budgeted them,\n * and stamps the envelope.\n *\n * Validates on the way **in**: a play recorded against a recording the paper\n * does not budget is a bug at the moment it is written, and discovering it\n * when a learner tries to resume is discovering it far too late.\n *\n * @throws Error when a key is not budgeted by the plan, or a count is not a\n * non-negative integer, or a position is not a finite number.\n */\nexport function serializeMediaPlayLedger(\n plan: AttemptPlan,\n entries: Readonly<Record<string, MediaPlayLedgerEntry>>,\n options: { savedAt?: string } = {},\n): MediaPlayLedger {\n if (entries === null || typeof entries !== 'object') {\n throw new Error('serializeMediaPlayLedger: entries must be an object keyed by media key.');\n }\n const budgets = planMediaBudgets(plan);\n const out: Record<string, MediaPlayLedgerEntry> = {};\n\n for (const key of Object.keys(entries)) {\n if (!Object.hasOwn(budgets, key)) {\n throw new Error(\n `serializeMediaPlayLedger: media play recorded against a recording the plan does not ` +\n `budget: ${JSON.stringify(key)}. Keys come from slotMediaKey() / stimulusMediaKey(); a ` +\n 'key that belongs to no budgeted media means the client and the plan disagree about ' +\n 'which paper this is.',\n );\n }\n const entry = entries[key] as MediaPlayLedgerEntry;\n assertEntry(key, entry);\n out[key] = { plays: entry.plays, ...(entry.at !== undefined ? { at: entry.at } : {}) };\n }\n\n return {\n ledgerVersion: '1.0',\n planHash: plan.planHash,\n entries: out,\n ...(options.savedAt !== undefined ? { savedAt: options.savedAt } : {}),\n };\n}\n\n/**\n * Reopens a stored ledger against the paper it was spent on.\n *\n * Refuses a ledger from a different paper for the same reason\n * `restoreAttemptState` does: budget keys are short and repeat across papers\n * (`slot:0`, `stimulus:1`), so a ledger from last term's midterm would hold a\n * learner to a budget from an exam they never sat, and look entirely plausible\n * doing it.\n *\n * @throws Error on an unrecognised `ledgerVersion`, a `planHash` mismatch, or\n * anything `serializeMediaPlayLedger` refuses.\n */\nexport function restoreMediaPlayLedger(\n plan: AttemptPlan,\n stored: MediaPlayLedger,\n): MediaPlayLedger {\n if (stored === null || typeof stored !== 'object') {\n throw new Error('restoreMediaPlayLedger: the stored ledger is not an object.');\n }\n if (stored.ledgerVersion !== '1.0') {\n throw new Error(\n `restoreMediaPlayLedger: unsupported ledgerVersion ${JSON.stringify(stored.ledgerVersion)}. ` +\n 'This build understands \"1.0\"; a newer ledger must be migrated before it is restored.',\n );\n }\n if (stored.entries === null || typeof stored.entries !== 'object') {\n throw new Error(\n 'restoreMediaPlayLedger: the ledger carries no entries object (a NULL column, or a ' +\n 'partially written row).',\n );\n }\n if (stored.planHash !== plan.planHash) {\n throw new Error(\n 'restoreMediaPlayLedger: this ledger belongs to a different paper ' +\n `(ledger ${stored.planHash}, plan ${plan.planHash}). Restoring it would hold the learner ` +\n 'to a play budget from an exam they never sat.',\n );\n }\n return serializeMediaPlayLedger(plan, stored.entries, {\n ...(stored.savedAt !== undefined ? { savedAt: stored.savedAt } : {}),\n });\n}\n","import { contentHash } from './content-hash.js';\nimport { flattenSequence } from './item-group.js';\nimport { resolvePlaybackPolicy, slotMediaKey, stimulusMediaKey } from './media-budget.js';\nimport type { ScoredItem } from './scoring/compose.js';\nimport type { ActivityData, ActivityMedia, ItemOutcome } from './types/activity.js';\nimport type {\n AttemptPlan,\n AttemptPlanDrift,\n AttemptPlanSlot,\n MediaBudgetRef,\n} from './types/attempt-plan.js';\nimport type { SequenceEntry, SequenceSlot } from './types/item-group.js';\n\nexport type {\n AttemptPlan,\n AttemptPlanDrift,\n AttemptPlanSlot,\n MediaBudgetRef,\n} from './types/attempt-plan.js';\n\n/** Options for {@link planAttempt}. */\nexport interface PlanAttemptOptions<TItem> {\n /** Shuffle the top-level entries. A group moves as one block. */\n shuffleEntries?: boolean;\n /**\n * Seed for every shuffle in this attempt. Required whenever anything\n * shuffles — the attempt has to be reproducible, which is the entire point\n * of writing a plan down. Use the attempt id.\n */\n seed?: string;\n /**\n * What each slot is worth. Defaults to 1 for every slot.\n *\n * Points are resolved HERE, not read from content, because they belong to\n * the paper rather than the item: the same question is worth 1 in a practice\n * quiz and 3 in a final. Whatever this returns is frozen into the plan and\n * is what `composeAssessmentScore` will weight by.\n *\n * @throws Error when it returns a value that is not a finite, non-negative\n * number — a slot worth `NaN` points would poison the whole total.\n */\n points?: (slot: SequenceSlot<TItem>) => number;\n}\n\n/**\n * The activity as CONTENT, with its slot key removed.\n *\n * `slotKey` rides on the same object but is identity, not content — the whole\n * point of the design. Including it in the fingerprint meant that annotating\n * an existing entry with the key that pins its identity reported as\n * \"this question was edited\", which is precisely backwards.\n */\nfunction contentOf(activity: object): object {\n if (!Object.hasOwn(activity, 'slotKey')) {\n return activity;\n }\n const { slotKey: _slotKey, ...content } = activity as { slotKey?: unknown };\n return content;\n}\n\n/**\n * The budgeted recordings a slot presents: its own media, and its group's\n * stimulus. Returns `undefined` — not `[]` — when nothing is budgeted, so the\n * conditional spread below leaves the serialized slot byte-identical to what\n * every pre-0.8.0 paper produced.\n */\nfunction mediaBudgetsOf<TItem extends { id: string; type: string }>(\n slot: SequenceSlot<TItem>,\n): MediaBudgetRef[] | undefined {\n const budgets: MediaBudgetRef[] = [];\n // Read structurally: `media` is a shared optional field, not part of the\n // `{ id, type }` bound this function is generic over.\n const own = (slot.activity as { media?: ActivityMedia }).media;\n if (own !== undefined) {\n const maxPlays = resolvePlaybackPolicy(own).maxPlays;\n if (maxPlays !== null) {\n budgets.push({ key: slotMediaKey(slot.slotId), maxPlays });\n }\n }\n const stimulusMedia = slot.group?.stimulus.media;\n if (stimulusMedia !== undefined) {\n const maxPlays = resolvePlaybackPolicy(stimulusMedia).maxPlays;\n if (maxPlays !== null) {\n budgets.push({ key: stimulusMediaKey(slot.slotId), maxPlays });\n }\n }\n return budgets.length > 0 ? budgets : undefined;\n}\n\n/**\n * Refuses a paper in which one recording is budgeted under several keys.\n *\n * Six questions that each carry the same `/audio/part2.mp3` with `maxPlays: 2`\n * are six budgets, so the learner gets twelve plays of one recording while the\n * paper says two. The fix is authoring, not arithmetic: questions that share a\n * recording belong in an item group, whose stimulus is one recording with one\n * budget.\n */\nfunction assertNoSplitBudgets<TItem extends { id: string; type: string }>(\n slots: readonly SequenceSlot<TItem>[],\n): void {\n const keysByUrl = new Map<string, string[]>();\n for (const slot of slots) {\n const own = (slot.activity as { media?: ActivityMedia }).media;\n if (own === undefined || resolvePlaybackPolicy(own).maxPlays === null) {\n continue;\n }\n const keys = keysByUrl.get(own.url) ?? [];\n keys.push(slotMediaKey(slot.slotId));\n keysByUrl.set(own.url, keys);\n }\n for (const [url, keys] of keysByUrl) {\n if (keys.length > 1) {\n throw new Error(\n `planAttempt: media ${JSON.stringify(url)} is budgeted under ${keys.length} separate ` +\n `keys (${keys.join(', ')}), so one recording grants ${keys.length} × maxPlays. Put the ` +\n \"questions that share a recording in an item group — a group's stimulus is one \" +\n 'recording with one budget.',\n );\n }\n }\n}\n\nfunction planSlot<TItem extends { id: string; type: string }>(\n slot: SequenceSlot<TItem>,\n points: number,\n): AttemptPlanSlot {\n if (!Number.isFinite(points) || points < 0) {\n throw new Error(\n `planAttempt: slot \"${slot.slotId}\" resolved to ${String(points)} points. Points must be a ` +\n 'finite, non-negative number, or the paper has no defensible total.',\n );\n }\n const mediaBudgets = mediaBudgetsOf(slot);\n return {\n slotId: slot.slotId,\n index: slot.index,\n activityId: slot.activity.id,\n activityType: slot.activity.type,\n points,\n contentHash: contentHash(contentOf(slot.activity)),\n ...(slot.group !== undefined\n ? {\n group: {\n id: slot.group.id,\n ...(slot.group.title !== undefined ? { title: slot.group.title } : {}),\n stimulusHash: contentHash(slot.group.stimulus),\n },\n }\n : {}),\n ...(mediaBudgets !== undefined ? { mediaBudgets } : {}),\n };\n}\n\n/**\n * Freezes what an attempt is being served: the presented order, each slot's\n * identity and worth, and a fingerprint of the content behind it.\n *\n * Call this once, when the attempt starts, and store the result beside the\n * responses. Everything that decides the grade is then a historical fact\n * rather than a re-read of content that may since have changed — which is what\n * makes a re-grade, a remark or an appeal answerable.\n *\n * Ordering comes from `flattenSequence`, so a plan and a live render of the\n * same entries with the same seed agree slot for slot.\n *\n * @throws Error when a shuffle is requested without a seed, when a group is\n * empty, when two entries collide on a `slotKey`, or when `points`\n * returns a value that is not finite and non-negative.\n */\nexport function planAttempt<TItem extends { id: string; type: string }>(\n entries: readonly SequenceEntry<TItem>[],\n options: PlanAttemptOptions<TItem> = {},\n): AttemptPlan {\n const { seed, shuffleEntries, points } = options;\n const slots = flattenSequence(entries, {\n ...(shuffleEntries !== undefined ? { shuffleEntries } : {}),\n ...(seed !== undefined ? { seed } : {}),\n });\n\n assertNoSplitBudgets(slots);\n\n const planned = slots.map((slot) => planSlot(slot, points?.(slot) ?? 1));\n const totalPoints = planned.reduce((sum, slot) => sum + slot.points, 0);\n\n return {\n planVersion: '1.0',\n ...(seed !== undefined ? { seed } : {}),\n ...(shuffleEntries !== undefined ? { shuffleEntries } : {}),\n // The plan's own fingerprint covers the slots verbatim — identity, order,\n // points and content hashes — so one stored value answers \"is this still\n // the paper that was sat?\" and the per-slot hashes then say what moved.\n planHash: contentHash(planned),\n slots: planned,\n totalPoints,\n };\n}\n\n/**\n * Compares a stored plan with the content as it stands now, and reports every\n * way they have drifted apart.\n *\n * This is the question a remark or an appeal actually asks: *is the paper I am\n * looking at the paper this learner sat?* Ids alone cannot answer it, because\n * they survive an edit unchanged.\n *\n * Rebuild the comparison plan with the SAME options the stored one recorded —\n * its `seed`, its `shuffleEntries`, and the same `points` function — or the\n * differences you see will be your own:\n *\n * ```ts\n * const now = planAttempt(currentEntries, {\n * seed: stored.seed,\n * shuffleEntries: stored.shuffleEntries,\n * points: pointsFor, // omit it and every slot reweights to 1\n * });\n * const drift = verifyAttemptPlan(stored, now);\n * ```\n *\n * A drift is not automatically a problem — a fixed typo changes a hash without\n * changing what was asked. It is a fact somebody has to be able to see.\n */\nexport function verifyAttemptPlan(plan: AttemptPlan, current: AttemptPlan): AttemptPlanDrift {\n const before = new Map(plan.slots.map((slot) => [slot.slotId, slot]));\n const after = new Map(current.slots.map((slot) => [slot.slotId, slot]));\n\n const missingSlotIds = plan.slots.filter((s) => !after.has(s.slotId)).map((s) => s.slotId);\n const addedSlotIds = current.slots.filter((s) => !before.has(s.slotId)).map((s) => s.slotId);\n\n const changedSlotIds: string[] = [];\n const changedStimulusSlotIds: string[] = [];\n const changedPointsSlotIds: string[] = [];\n const reorderedSlotIds: string[] = [];\n for (const slot of plan.slots) {\n const now = after.get(slot.slotId);\n if (now === undefined) {\n continue;\n }\n // A swapped activity changes the content behind the slot, so it lands in\n // `changedSlotIds` through the fingerprint rather than needing its own arm.\n if (now.contentHash !== slot.contentHash) {\n changedSlotIds.push(slot.slotId);\n }\n if (now.group?.stimulusHash !== slot.group?.stimulusHash) {\n changedStimulusSlotIds.push(slot.slotId);\n }\n // A reweight moves the grade without touching a single question. Left out,\n // `matches` said the paper was unchanged while its `planHash` disagreed.\n if (now.points !== slot.points) {\n changedPointsSlotIds.push(slot.slotId);\n }\n if (now.index !== slot.index) {\n reorderedSlotIds.push(slot.slotId);\n }\n }\n\n return {\n matches:\n missingSlotIds.length === 0 &&\n addedSlotIds.length === 0 &&\n changedSlotIds.length === 0 &&\n changedStimulusSlotIds.length === 0 &&\n changedPointsSlotIds.length === 0 &&\n reorderedSlotIds.length === 0,\n missingSlotIds,\n addedSlotIds,\n changedSlotIds,\n changedStimulusSlotIds,\n changedPointsSlotIds,\n reorderedSlotIds,\n };\n}\n\n/** How {@link scoredItemsFromPlan} fills a slot that has no recorded outcome. */\nexport type MissingOutcomePolicy =\n /**\n * Default. `{ status: 'deferred', reason: 'no_response_recorded' }` — a\n * non-terminal state, so the composed result stays `provisional` and cannot\n * be recorded as a final pass or fail.\n */\n | 'deferred'\n /**\n * `{ status: 'scored', score: 0 }` — the learner left it blank on a paper\n * that IS complete. Choose this only when you know the attempt was\n * submitted; it is a real zero and makes the result final.\n */\n | 'zero'\n /** Build the outcome yourself, per slot. */\n | ((slot: AttemptPlanSlot) => ItemOutcome);\n\nfunction missingOutcome(slot: AttemptPlanSlot, policy: MissingOutcomePolicy): ItemOutcome {\n if (typeof policy === 'function') {\n return policy(slot);\n }\n if (policy === 'zero') {\n return { status: 'scored', score: 0, maxScore: 1, passed: false, feedback: null, details: [] };\n }\n return { status: 'deferred', reason: 'no_response_recorded', maxScore: 1 };\n}\n\n/**\n * Turns a plan plus whatever outcomes exist into the `ScoredItem[]`\n * `composeAssessmentScore` consumes.\n *\n * The plan is the source of the denominator, not the outcomes. A slot the\n * learner never reached still has to appear — otherwise it silently leaves the\n * denominator and the remaining questions quietly become worth more than the\n * paper says.\n *\n * **A missing outcome defaults to `deferred`, never `unscorable`.** The\n * distinction decides a grade: `unscorable` means \"a grade is never coming\",\n * so `composeAssessmentScore` drops the slot from the denominator AND lets the\n * result go `final` — which turned a three-question paper with one answer into\n * a final, passing 100%. `deferred` means \"not yet\", which holds the result\n * `provisional` so nothing can be recorded. Pass `'zero'` once you know the\n * attempt was submitted and the blanks are genuinely blanks.\n *\n * Pass outcomes keyed by `slotId`. Keys the plan does not know are ignored:\n * a plan is the authority on what the attempt contained.\n */\nexport function scoredItemsFromPlan(\n plan: AttemptPlan,\n outcomes: Readonly<Record<string, ItemOutcome>>,\n options: { missing?: MissingOutcomePolicy } = {},\n): ScoredItem[] {\n const policy = options.missing ?? 'deferred';\n return plan.slots.map((slot) => ({\n slotId: slot.slotId,\n activityId: slot.activityId,\n points: slot.points,\n // `Object.hasOwn`, not a bare lookup: slot ids come from authored\n // `slotKey`s, and a key of `constructor` or `toString` would otherwise\n // resolve through the prototype chain and hand a FUNCTION to the scorer\n // in place of an outcome.\n outcome: Object.hasOwn(outcomes, slot.slotId)\n ? (outcomes[slot.slotId] as ItemOutcome)\n : missingOutcome(slot, policy),\n }));\n}\n\n/** Convenience alias: the entry type a plan is built from. */\nexport type PlannableEntry = SequenceEntry<ActivityData>;\n","import { canonicalJson } from './content-hash.js';\nimport type { LearnerResponse } from './types/activity.js';\nimport type { AttemptPlan } from './types/attempt-plan.js';\nimport type { AttemptState, ResponseDiffEntry } from './types/attempt-state.js';\n\nexport type { AttemptState, ResponseDiffEntry } from './types/attempt-state.js';\n\n/** What {@link serializeAttemptState} is given about an attempt in progress. */\nexport interface AttemptProgress {\n /** Answers so far, keyed by `slotId`. */\n responses: Readonly<Record<string, LearnerResponse>>;\n /** Slots already submitted. Defaults to none. */\n submittedSlotIds?: readonly string[];\n /** Presented position the learner is on. Defaults to 0. */\n index?: number;\n /** ISO 8601 timestamp to stamp the snapshot with. The SDK does not read a clock. */\n savedAt?: string;\n}\n\n/**\n * A DEEP copy of the responses.\n *\n * A one-level spread is not enough: every `LearnerResponse` shape is itself an\n * object (`selectedOptionIds`, `answers`, `text`), so a spread hands back a new\n * map of the caller's SAME response objects. A consumer whose reducer updates\n * an answer in place — an Immer draft, a push onto a multi-select, or\n * `answers[blankId] = text`, which is the natural update for that shape — then\n * mutates every snapshot ever taken. The stored snapshot retroactively becomes\n * the new answer, `diffResponses` sees no change, and a delta autosave writes\n * nothing for an edit the learner really made.\n */\nfunction cloneResponses(\n responses: Readonly<Record<string, LearnerResponse>>,\n): Record<string, LearnerResponse> {\n // Responses are JSON by contract, so the fallback is lossless for them.\n return typeof structuredClone === 'function'\n ? structuredClone(responses as Record<string, LearnerResponse>)\n : (JSON.parse(JSON.stringify(responses)) as Record<string, LearnerResponse>);\n}\n\n/** Slot ids present in the object but unknown to the plan. */\nfunction unknownKeys(plan: AttemptPlan, keys: readonly string[]): string[] {\n const known = new Set(plan.slots.map((slot) => slot.slotId));\n return keys.filter((key) => !known.has(key));\n}\n\n/**\n * Captures an in-progress attempt as a storable snapshot, bound to its plan.\n *\n * Validated against the plan on the way in, not on the way out: a response\n * stored under a slot the paper does not contain is a bug at the moment it is\n * written, and finding it months later — when a learner tries to resume — is\n * finding it far too late.\n *\n * The SDK reads no clock: pass `savedAt` if you want the snapshot stamped, so\n * the function stays pure and its output stays reproducible in a test.\n *\n * @throws Error when a response or submitted slot is not in the plan, or when\n * `index` is not a position the plan actually has.\n */\nexport function serializeAttemptState(plan: AttemptPlan, progress: AttemptProgress): AttemptState {\n const responseKeys = Object.keys(progress.responses);\n const submittedSlotIds = [...(progress.submittedSlotIds ?? [])];\n\n const strayResponses = unknownKeys(plan, responseKeys);\n if (strayResponses.length > 0) {\n throw new Error(\n `serializeAttemptState: response recorded for slot(s) the plan does not contain: ${strayResponses.join(', ')}. ` +\n 'A response that belongs to no question cannot be scored and would be lost silently.',\n );\n }\n const straySubmitted = unknownKeys(plan, submittedSlotIds);\n if (straySubmitted.length > 0) {\n throw new Error(\n `serializeAttemptState: submitted slot(s) the plan does not contain: ${straySubmitted.join(', ')}.`,\n );\n }\n\n const index = progress.index ?? 0;\n // An out-of-range position would reopen the attempt on a question that is\n // not there — which the pager renders as an empty shell with no way forward.\n // An empty plan admits only 0: guarding with `slots.length > 0` skipped the\n // range check altogether there, so a zero-slot paper accepted any index and\n // the error message contradicted itself.\n const lastIndex = Math.max(0, plan.slots.length - 1);\n if (!Number.isInteger(index) || index < 0 || index > lastIndex) {\n throw new Error(\n `serializeAttemptState: index ${String(index)} is not a position in a ${plan.slots.length}-slot plan.`,\n );\n }\n\n return {\n stateVersion: '1.0',\n planHash: plan.planHash,\n // Copied DEEPLY, not aliased: a snapshot that keeps mutating with the\n // live attempt is not a snapshot. See cloneResponses.\n responses: cloneResponses(progress.responses),\n submittedSlotIds,\n index,\n ...(progress.savedAt !== undefined ? { savedAt: progress.savedAt } : {}),\n };\n}\n\n/**\n * Reopens a stored snapshot against a plan, refusing anything that does not\n * belong to it.\n *\n * The `planHash` check is the point. Slot ids are short and stable by design,\n * so a snapshot from a DIFFERENT paper — last term's midterm, a sibling\n * version, a copy-pasted attempt row — will happily line its answers up\n * against the wrong questions and look entirely plausible doing it. Comparing\n * the paper's fingerprint is what makes that impossible rather than unlikely.\n *\n * @throws Error when the snapshot belongs to a different plan, or references\n * slots the plan does not contain.\n */\nexport function restoreAttemptState(plan: AttemptPlan, state: AttemptState): AttemptState {\n if (state === null || typeof state !== 'object') {\n throw new Error('restoreAttemptState: the snapshot is not an object.');\n }\n // The one field added so a stored snapshot survives an envelope change was\n // the one field never read: an unrecognised version was accepted,\n // reinterpreted under this version's rules, and re-stamped '1.0' — which\n // also destroyed the evidence that it had ever been anything else.\n if (state.stateVersion !== '1.0') {\n throw new Error(\n `restoreAttemptState: unsupported stateVersion ${JSON.stringify(state.stateVersion)}. ` +\n 'This build understands \"1.0\"; a newer snapshot must be migrated before it is restored.',\n );\n }\n if (state.responses === null || typeof state.responses !== 'object') {\n throw new Error(\n 'restoreAttemptState: the snapshot carries no responses object (a NULL column, or a ' +\n 'partially written row).',\n );\n }\n if (state.planHash !== plan.planHash) {\n throw new Error(\n 'restoreAttemptState: this snapshot belongs to a different paper ' +\n `(snapshot ${state.planHash}, plan ${plan.planHash}). Restoring it would attach the ` +\n \"learner's answers to questions they never saw.\",\n );\n }\n // Re-validated rather than trusted: a snapshot is storage, and storage is\n // edited, migrated and hand-fixed.\n return serializeAttemptState(plan, {\n responses: state.responses,\n submittedSlotIds: state.submittedSlotIds,\n index: state.index,\n ...(state.savedAt !== undefined ? { savedAt: state.savedAt } : {}),\n });\n}\n\n/**\n * Reports how two snapshots' responses differ, slot by slot.\n *\n * Useful for an autosave that should only write what moved, and for an audit\n * trail that has to show what a learner changed between two saves — including\n * an answer they cleared, which a naive comparison of the later snapshot\n * alone cannot see.\n *\n * Entries come back sorted by `slotId`, so the output is stable regardless of\n * the order the two objects happened to be written in.\n */\nexport function diffResponses(\n before: Pick<AttemptState, 'responses'>,\n after: Pick<AttemptState, 'responses'>,\n): ResponseDiffEntry[] {\n const slotIds = [...new Set([...Object.keys(before.responses), ...Object.keys(after.responses)])];\n slotIds.sort();\n\n const entries: ResponseDiffEntry[] = [];\n for (const slotId of slotIds) {\n const had = Object.hasOwn(before.responses, slotId);\n const has = Object.hasOwn(after.responses, slotId);\n const from = before.responses[slotId];\n const to = after.responses[slotId];\n\n if (had && !has) {\n entries.push({ slotId, change: 'removed', ...(from !== undefined ? { before: from } : {}) });\n continue;\n }\n if (!had && has) {\n entries.push({ slotId, change: 'added', ...(to !== undefined ? { after: to } : {}) });\n continue;\n }\n // Structural comparison through the canonical form, so a response that\n // survived a JSON round-trip with its keys reordered does not read as a\n // change the learner never made.\n if (canonicalJson(from) !== canonicalJson(to)) {\n entries.push({\n slotId,\n change: 'changed',\n ...(from !== undefined ? { before: from } : {}),\n ...(to !== undefined ? { after: to } : {}),\n });\n }\n }\n return entries;\n}\n","import { UnknownActivityTypeError } from '../errors.js';\nimport {\n GROUP_CAPTIONS_REVEAL_DICTATION,\n groupCaptionsRevealDictation,\n} from '../schemas/dictation.js';\nimport { ItemGroupSchema, validateItemGroup } from '../schemas/item-group.js';\nimport type { ActivityType } from '../types/activity.js';\nimport type { DraftContext, DraftIssue, DraftValidationResult } from '../types/authoring.js';\nimport type { ItemGroup } from '../types/item-group.js';\nimport { withValidationScope } from '../validation-scope.js';\nimport { validateDraft } from './index.js';\nimport {\n checkMedia,\n covers,\n type DraftFields,\n isMissingId,\n isRecord,\n issue,\n isUnset,\n isUnwritten,\n refusesEmpty,\n} from './issues.js';\n\n/**\n * A new, empty reading or listening testlet for an editor to start from.\n *\n * The stimulus starts as `text`, the only kind that needs no media file to be\n * a valid draft — an author who is writing a passage can begin typing, and one\n * who is building a listening item changes `kind` before uploading. `items`\n * starts empty, exactly as a new fill-in-the-blanks draft starts with no\n * blanks: the group is `incomplete` until somebody writes a question into it.\n *\n * @throws Error when `newId` returns an empty or repeated id.\n */\nexport function createItemGroupDraft(context: DraftContext): ItemGroup {\n const issued = new Set<string>();\n const newId = (): string => {\n const id: unknown = context.newId();\n if (typeof id !== 'string' || id === '') {\n throw new Error('createItemGroupDraft: newId() must return a non-empty string.');\n }\n if (issued.has(id)) {\n throw new Error(\n `createItemGroupDraft: newId() returned \"${id}\" twice. Ids within one draft must differ.`,\n );\n }\n issued.add(id);\n return id;\n };\n return {\n schemaVersion: '1.0',\n type: 'item-group',\n id: newId(),\n stimulus: { id: newId(), kind: 'text', body: '' },\n items: [],\n };\n}\n\n/**\n * Tells an unfinished testlet from a broken one — {@link validateDraft} for the\n * container that holds several questions around one passage or recording.\n *\n * It is a **separate entry point rather than a `'item-group'` type**, because\n * `validateDraft('item-group', …)` throws by design: `item-group` is reserved\n * in the registry precisely so it can never be registered as an activity, and\n * that guard is what keeps `isItemGroup` and `flattenSequence` able to trust\n * their own container. Widening `validateDraft` to accept it would have meant\n * weakening that.\n *\n * Each item is checked by `validateDraft` for its own type and its issues are\n * re-pathed under `items.N.…`, so an editor gets one list for the whole group\n * and every code in it is the code that type already documents. An item whose\n * type nobody registered is REPORTED, never thrown — an author fixing a\n * six-item group wants all six problems, not the first one that blew up.\n *\n * The group is `complete` only when the container passes, every item passes its\n * own schema, and every item is itself `complete`.\n *\n * @throws the error a registered item type's `checkDraft` or schema throws, as\n * `validateDraft` does for that item on its own. Only an unregistered type is\n * turned into an issue: a fault in a type's own code is not a problem with the\n * draft, and reporting it as an unknown type would hide it.\n */\nexport function validateItemGroupDraft(draft: unknown): DraftValidationResult<ItemGroup> {\n // Every item is checked as a draft and then again as part of the group: one\n // scope lets the expensive normalisation behind both run once.\n return withValidationScope(() => validateItemGroupDraftInScope(draft));\n}\n\nfunction validateItemGroupDraftInScope(draft: unknown): DraftValidationResult<ItemGroup> {\n const issues: DraftIssue[] = [];\n if (!isRecord(draft)) {\n issues.push(\n issue('ig_not_an_object', [], 'A group must be an object with a stimulus and its items.'),\n );\n return { status: 'invalid', issues };\n }\n\n issues.push(...checkGroupIdentity(draft));\n if (isRecord(draft.stimulus)) {\n issues.push(...checkStimulus(draft.stimulus));\n } else if (isUnset(draft.stimulus)) {\n issues.push(\n issue(\n 'ig_stimulus_required',\n ['stimulus'],\n 'Add the passage, recording or image the questions are about.',\n ),\n );\n }\n issues.push(...checkItems(draft));\n if (groupCaptionsRevealDictation(draft, (captionsUrl) => !isUnwritten(captionsUrl))) {\n issues.push(\n issue(\n 'dc_captions_not_allowed',\n ['stimulus', 'media', 'captionsUrl'],\n GROUP_CAPTIONS_REVEAL_DICTATION,\n ),\n );\n }\n\n // Every container failure the checks above did not already account for, added\n // as `invalid` — the same rule `validateDraft` follows, so a rule nobody\n // named still reaches the author instead of passing silently.\n const parsed = ItemGroupSchema.safeParse(draft, { reportInput: true });\n if (!parsed.success) {\n for (const schemaIssue of parsed.error.issues) {\n const path = schemaIssue.path.map(String);\n if (issues.some((known) => covers(known.path, path))) {\n continue;\n }\n if (path.length > 0 && refusesEmpty(draft, schemaIssue)) {\n issues.push(\n issue(\n 'null_not_allowed',\n path,\n 'This field cannot be null. Leave it out if it is optional, or give it a value.',\n ),\n );\n continue;\n }\n issues.push({\n path,\n message: schemaIssue.message,\n code: schemaIssue.code,\n severity: 'invalid',\n });\n }\n }\n\n const stored = validateItemGroup(draft);\n if (issues.length === 0 && stored.success) {\n return { status: 'complete', data: stored.data, issues };\n }\n if (issues.length === 0) {\n // The container and every item satisfy their own checks, yet the group is\n // not storable. Nothing here can name the cause, so hand over the\n // validator's own errors rather than claim the draft is finished.\n for (const error of stored.success ? [] : stored.errors) {\n issues.push({ ...error, severity: 'invalid' });\n }\n }\n const invalid = issues.some((found) => found.severity !== 'incomplete');\n return { status: invalid ? 'invalid' : 'incomplete', issues };\n}\n\n/** The group's own envelope. `title` is optional on a group, unlike an activity. */\nfunction checkGroupIdentity(draft: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n if (draft.schemaVersion !== '1.0') {\n issues.push(\n issue(\n 'schema_version_invalid',\n ['schemaVersion'],\n 'The draft must have schemaVersion \"1.0\". A draft from createItemGroupDraft has it.',\n ),\n );\n }\n if (draft.type !== 'item-group') {\n issues.push(issue('type_mismatch', ['type'], 'The draft\\'s type must be \"item-group\".'));\n }\n if (isMissingId(draft.id)) {\n issues.push(issue('id_required', ['id'], 'The group has no id.'));\n }\n if (!isUnset(draft.shuffle) && draft.shuffle !== 'none' && draft.shuffle !== 'within-group') {\n issues.push(\n issue(\n 'ig_shuffle_invalid',\n ['shuffle'],\n 'Shuffling is either \"none\" or \"within-group\". Leave it out to keep the authored order.',\n ),\n );\n }\n return issues;\n}\n\nconst KINDS = new Set(['text', 'audio', 'video', 'image', 'mixed']);\n/** Which media type each stimulus kind accepts — mirrors `StimulusSchema`'s refinement. */\nconst MEDIA_FOR_KIND: Record<string, readonly string[]> = {\n audio: ['audio'],\n video: ['video', 'embed'],\n image: ['image'],\n mixed: ['audio', 'video', 'image', 'embed'],\n};\n\n/**\n * The passage, recording or image. The split this makes is the one the whole\n * draft contract exists for: a kind nobody has chosen and a body nobody has\n * typed are `incomplete`, while a recording attached to an image stimulus is\n * `invalid` — writing more will not reconcile them.\n */\nfunction checkStimulus(stimulus: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n const at = (...rest: (string | number)[]) => ['stimulus', ...rest];\n\n if (isMissingId(stimulus.id)) {\n issues.push(issue('ig_stimulus_id_required', at('id'), 'The stimulus has no id.'));\n }\n\n const kind = stimulus.kind;\n if (isUnwritten(kind)) {\n issues.push(\n issue(\n 'ig_stimulus_kind_required',\n at('kind'),\n 'Choose what the questions are about: a text, a recording, a video, an image, or a mix.',\n ),\n );\n } else if (typeof kind !== 'string' || !KINDS.has(kind)) {\n // A value of another type is the schema's to refuse.\n if (typeof kind === 'string') {\n issues.push(\n issue(\n 'ig_stimulus_kind_invalid',\n at('kind'),\n `\"${kind}\" is not a stimulus kind. Use text, audio, video, image or mixed.`,\n ),\n );\n }\n // Only the kind-DEPENDENT rules are skipped. The media still has problems\n // of its own — a refused address, a missing description — and returning\n // here left every one of them to the schema, so an unrecognised kind made\n // zod's raw diagnostics appear beside ours.\n if (isRecord(stimulus.media)) {\n issues.push(...checkMedia(stimulus.media, at('media')));\n }\n return issues;\n }\n\n const hasBody = typeof stimulus.body === 'string' && stimulus.body.trim() !== '';\n // One rule, one issue, at `body` — where the schema reports both halves of\n // it. Written as two branches, a `text` stimulus carrying rich text and no\n // plain text reported the same path twice; and keying the second branch on\n // whether `bodyHtml` had CONTENT missed the empty string a cleared rich-text\n // editor leaves behind, which the schema still refuses.\n const htmlPresent = !isUnset(stimulus.bodyHtml);\n if (!hasBody && (kind === 'text' || kind === 'mixed' || htmlPresent)) {\n issues.push(\n issue(\n 'ig_stimulus_body_required',\n at('body'),\n isUnwritten(stimulus.bodyHtml)\n ? 'Write the passage.'\n : 'Write the passage as plain text too. The rich-text version is shown only where a sanitiser is supplied.',\n ),\n );\n }\n\n if (kind !== 'text' && isUnset(stimulus.media)) {\n issues.push(\n issue('ig_stimulus_media_required', at('media'), 'Add the recording, video or image.'),\n );\n } else if (isRecord(stimulus.media)) {\n const allowed = MEDIA_FOR_KIND[kind as string];\n const mediaType = stimulus.media.type;\n if (allowed !== undefined && typeof mediaType === 'string' && !allowed.includes(mediaType)) {\n issues.push(\n issue(\n 'ig_stimulus_media_kind',\n at('media', 'type'),\n `A \"${kind}\" stimulus cannot carry ${mediaType} media. Use ${allowed.join(' or ')}.`,\n ),\n );\n }\n issues.push(...checkMedia(stimulus.media, at('media')));\n }\n return issues;\n}\n\n/**\n * Every item, checked by `validateDraft` for its own type.\n *\n * Re-pathing rather than re-implementing is the point: a multiple-choice\n * question inside a testlet reports exactly the codes a standalone one does,\n * so a consumer's translation table covers both and a rule can never drift\n * between them.\n */\nfunction checkItems(draft: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n const items = isUnset(draft.items) ? [] : draft.items;\n if (!Array.isArray(items)) {\n return issues;\n }\n if (items.length === 0) {\n issues.push(\n issue('ig_items_required', ['items'], 'Add at least one question about this material.'),\n );\n return issues;\n }\n\n const seen = new Set<string>();\n const repeated = new Set<string>();\n for (const [index, item] of items.entries()) {\n if (!isRecord(item)) {\n continue;\n }\n const ordinal = index + 1;\n if (isMissingId(item.id)) {\n issues.push(\n issue('ig_item_id_required', ['items', index, 'id'], `Question ${ordinal} has no id.`),\n );\n } else if (typeof item.id === 'string') {\n if (seen.has(item.id)) {\n repeated.add(item.id);\n }\n seen.add(item.id);\n }\n\n if (item.type === 'item-group') {\n issues.push(\n issue(\n 'ig_item_nested_group',\n ['items', index, 'type'],\n 'Groups do not nest: every item must be an activity.',\n ),\n );\n continue;\n }\n if (isUnwritten(item.type)) {\n issues.push(\n issue(\n 'ig_item_type_required',\n ['items', index, 'type'],\n `Choose what kind of question ${ordinal} is.`,\n ),\n );\n continue;\n }\n if (typeof item.type !== 'string') {\n continue;\n }\n\n let result: DraftValidationResult<unknown>;\n try {\n result = validateDraft(item.type as ActivityType, item);\n } catch (error) {\n // Only an unregistered type is reported, never thrown — the same choice\n // `validateItemGroup` makes, for the same reason. Anything else is a fault\n // in a registered type's own checks or schema: it is rethrown, as\n // `validateDraft` throws it for the item on its own, because reported here\n // it read as an unknown type and sent the author after a mistake the draft\n // did not have. The error must name this item's type, too: a check that\n // validates a part of the item as some other, unregistered type has not\n // made this item's type unknown.\n if (!(error instanceof UnknownActivityTypeError) || error.activityType !== item.type) {\n throw error;\n }\n issues.push(\n issue(\n 'ig_item_type_unknown',\n ['items', index, 'type'],\n `\"${item.type}\" is not a registered activity type.`,\n ),\n );\n continue;\n }\n for (const found of result.issues) {\n issues.push({ ...found, path: ['items', String(index), ...found.path] });\n }\n }\n\n for (const id of repeated) {\n issues.push(\n issue('ig_item_id_duplicate', ['items'], `More than one question has the id \"${id}\".`),\n );\n }\n return issues;\n}\n","import { UnknownActivityTypeError } from '../errors.js';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ActivityDataMap, ActivityType } from '../types/activity.js';\nimport type { DraftContext, DraftIssue, DraftValidationResult } from '../types/authoring.js';\nimport { withValidationScope } from '../validation-scope.js';\nimport {\n coveredPathsOf,\n DRAFT_ISSUE_SEVERITY,\n type DraftIssueCode,\n isRecord,\n issue,\n pathKey,\n refusesEmpty,\n} from './issues.js';\n\n/**\n * Tells a draft that is not finished from a draft that is wrong.\n *\n * `validateActivity` answers \"may this be stored?\", and to that question an\n * empty new question and a broken one are the same answer: no. An editor needs\n * the difference — \"Add a title\" is a to-do, \"Only one option can be marked\n * correct\" is an error — so a freshly added question does not read as a\n * failure, disable a whole form, or blank a preview.\n *\n * - `complete` — the draft is a valid activity with nothing left to write.\n * `data` is exactly what `validateActivity` returns for it.\n * - `incomplete` — every problem is something not yet written.\n * - `invalid` — at least one problem is wrong in a way writing more cannot fix.\n *\n * It is stricter than `validateActivity`, never looser: `complete` requires the\n * activity's schema to pass, and a draft can fail here that the schema accepts\n * (a title that is only whitespace). Content stored by an older build can\n * therefore be valid and still not `complete`. `validateActivity` stays the\n * check at your write boundary.\n *\n * Issues come from the type's `authoring.checkDraft`, plus every schema failure\n * it did not already report at that path or inside it. (A failure at the root of\n * the draft counts as reported only by an issue at the root, since every path is\n * inside the root.) Such a failure is added as `invalid`: under the code\n * `null_not_allowed` when the schema refused a `null` there, or an `undefined`\n * entry in a list, and otherwise under the schema's own code and message. A type\n * with no `checkDraft` therefore reports every schema failure as `invalid`.\n *\n * The codes documented in `docs/authoring.md` are a contract, and each is\n * reported with its documented severity, whichever check reports it. A code\n * passed through from the schema is not a contract: the code and its English\n * message belong to the schema library, so give a code you do not recognise a\n * generic message of your own.\n *\n * @throws UnknownActivityTypeError when `type` has no registered descriptor —\n * including `'item-group'`, which is a container, not an activity type.\n */\nexport function validateDraft<T extends ActivityType>(\n type: T,\n draft: unknown,\n): DraftValidationResult<ActivityDataMap[T]> {\n // The type's checks and its schema read the same strings: one scope lets the\n // expensive normalisation behind both run once.\n return withValidationScope(() => validateDraftInScope(type, draft));\n}\n\nfunction validateDraftInScope<T extends ActivityType>(\n type: T,\n draft: unknown,\n): DraftValidationResult<ActivityDataMap[T]> {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(type));\n }\n\n const reported =\n isRecord(draft) && descriptor.authoring?.checkDraft !== undefined\n ? descriptor.authoring.checkDraft(draft).map(normalise)\n : [];\n const issues: DraftIssue[] = [...reported];\n\n // `reportInput` records on each issue the value its check was given, which is\n // how a refused `null` is told apart from a rule that merely points at one.\n const parsed = descriptor.schema.safeParse(draft, { reportInput: true });\n if (!parsed.success) {\n const covered = coveredPathsOf(reported);\n const reportedEmpty = new Set<string>();\n for (const schemaIssue of parsed.error.issues) {\n const path = schemaIssue.path.map(String);\n if (covered.has(pathKey(path))) {\n continue;\n }\n // `null` is how many editors and databases spell \"no value\". Where the\n // schema refuses one, name it under one documented code, for every type,\n // rather than hand over the schema library's own diagnostic.\n if (path.length > 0 && refusesEmpty(draft, schemaIssue)) {\n const key = JSON.stringify(path);\n if (!reportedEmpty.has(key)) {\n reportedEmpty.add(key);\n issues.push(\n issue(\n 'null_not_allowed',\n path,\n typeof schemaIssue.path.at(-1) === 'number'\n ? 'This entry has no value. Remove it, or fill it in.'\n : 'This field cannot be null. Leave it out if it is optional, or give it a value.',\n ),\n );\n }\n continue;\n }\n issues.push({\n path,\n message: schemaIssue.message,\n code: schemaIssue.code,\n severity: 'invalid',\n });\n }\n }\n\n if (parsed.success && issues.length === 0) {\n return { status: 'complete', data: parsed.data as ActivityDataMap[T], issues };\n }\n const invalid = issues.some((found) => found.severity !== 'incomplete');\n return { status: invalid ? 'invalid' : 'incomplete', issues };\n}\n\n/**\n * A new, empty draft of an activity type, for an editor to start from.\n *\n * Every required field is present and nothing is authored, so the draft comes\n * back from {@link validateDraft} as `incomplete`, and `validateActivity`\n * rejects it until someone writes it. The SDK invents no ids: `newId` is called\n * once per id the draft needs, and must return a different non-empty string each\n * time.\n *\n * ```ts\n * const draft = createDraft('multiple-choice', { newId: () => crypto.randomUUID() });\n * ```\n *\n * @throws UnknownActivityTypeError when `type` has no registered descriptor.\n * @throws Error when the type declares no `authoring.createDraft`, or when\n * `newId` returns an empty or repeated id.\n */\nexport function createDraft<T extends ActivityType>(\n type: T,\n context: DraftContext,\n): ActivityDataMap[T] {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(type));\n }\n const create = descriptor.authoring?.createDraft;\n if (create === undefined) {\n throw new Error(\n `Activity type \"${String(type)}\" declares no authoring.createDraft, so there is no empty draft to create. ` +\n 'Build the draft yourself; validateDraft works for every registered type.',\n );\n }\n const issued = new Set<string>();\n const newId = (): string => {\n const id: unknown = context.newId();\n if (typeof id !== 'string' || id === '') {\n throw new Error('createDraft: newId() must return a non-empty string.');\n }\n if (issued.has(id)) {\n throw new Error(\n `createDraft: newId() returned \"${id}\" twice. Ids within one draft must differ — two options sharing an id cannot be scored apart.`,\n );\n }\n issued.add(id);\n return id;\n };\n return create({ newId }) as ActivityDataMap[T];\n}\n\n/**\n * A check's issue as `validateDraft` reports it.\n *\n * A documented code carries its documented severity, whichever check reports\n * it. Any other code keeps the check's severity, and one that is not\n * `'incomplete'` — misspelled, or missing — is reported as `invalid`, so the\n * mistake fails closed. Path segments become strings, as the schema's are, so a\n * list index given as a number still covers the schema's failure there.\n */\nfunction normalise(found: DraftIssue): DraftIssue {\n const documented = Object.hasOwn(DRAFT_ISSUE_SEVERITY, found.code)\n ? DRAFT_ISSUE_SEVERITY[found.code as DraftIssueCode]\n : undefined;\n return {\n ...found,\n path: found.path.map(String),\n severity: documented ?? (found.severity === 'incomplete' ? 'incomplete' : 'invalid'),\n };\n}\n\nexport { createItemGroupDraft, validateItemGroupDraft } from './item-group.js';\n","import { ActivitySchemaError, UnknownActivityTypeError } from './errors.js';\nimport { MEDIA_FIELD_POLICY } from './registry/builtins.js';\nimport { getActivityTypeDescriptor } from './registry/index.js';\nimport type { FieldPolicy, Sensitivity } from './registry/registry.js';\nimport { RedactedItemGroupSchema } from './schemas/item-group.js';\nimport type { ItemGroup } from './types/item-group.js';\n\n/**\n * A learner-safe projection of activity data produced by {@link redact}:\n * the activity's public fields plus the `redacted: true` marker. Renderable\n * and validatable (each built-in type registers a strict redacted schema),\n * but stripped of the answer key, scoring rules, authored feedback, and\n * author-only assets.\n */\nexport interface RedactedActivityData {\n redacted: true;\n schemaVersion: string;\n type: string;\n id: string;\n title: string;\n [key: string]: unknown;\n}\n\n/** Options for {@link redact}. */\nexport interface RedactOptions {\n /**\n * Which sensitivity tiers to keep beyond `public`:\n * - `'none'` (default) — public fields only; the output satisfies the\n * type's strict redacted schema and `assertRedacted`.\n * - `'after-submit'` — public + answer-key fields (for post-submission\n * review renders). `author-only` fields and unclassified fields are\n * STILL removed; the output will NOT pass `assertRedacted`.\n */\n reveal?: 'none' | 'after-submit';\n /**\n * Per-call sensitivity overrides, merged over the type's registered\n * `fieldPolicy` (top-level keys replace; nested objects merge one level).\n *\n * Sensitivity is partly a PEDAGOGICAL decision, not purely a security one —\n * whether a rubric or a hint is learner-visible differs legitimately between\n * deployments — and the SDK must not freeze that choice. Use this to tighten\n * a field the SDK ships as `public`:\n *\n * ```ts\n * redact(essay, { policy: { rubric: 'author-only' } });\n * ```\n *\n * Overrides can only be applied to fields; they cannot re-open a field the\n * caller has not classified, because unclassified still means removed.\n * Note that tightening below what the type's `redactedSchema` requires is\n * allowed — the schema check only rejects payloads that reveal MORE than\n * the learner-safe shape.\n */\n policy?: FieldPolicy;\n}\n\n/** Merges per-call overrides over a registered policy, one level deep. */\nfunction mergePolicy(base: FieldPolicy, overrides: FieldPolicy | undefined): FieldPolicy {\n if (overrides === undefined) {\n return base;\n }\n const merged: Record<string, Sensitivity | FieldPolicy> = { ...base };\n for (const [key, override] of Object.entries(overrides)) {\n const current = merged[key];\n merged[key] =\n typeof override === 'object' && typeof current === 'object'\n ? { ...current, ...override }\n : override;\n }\n return merged;\n}\n\nfunction isSensitivity(value: Sensitivity | FieldPolicy): value is Sensitivity {\n return typeof value === 'string';\n}\n\nfunction keepField(sensitivity: Sensitivity, reveal: 'none' | 'after-submit'): boolean {\n if (sensitivity === 'public') {\n return true;\n }\n return sensitivity === 'answer-key' && reveal === 'after-submit';\n}\n\n/** An object projection that kept no fields at all. Arrays are never dropped. */\nfunction isEmptyObject(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Object.keys(value).length === 0\n );\n}\n\nfunction redactValue(\n value: unknown,\n policy: FieldPolicy,\n reveal: 'none' | 'after-submit',\n): unknown {\n if (Array.isArray(value)) {\n return value.map((element) => redactValue(element, policy, reveal));\n }\n if (value === null || typeof value !== 'object') {\n // A nested FieldPolicy cannot classify a primitive's sub-fields; the\n // policy author classified an object shape that is not there. Fail\n // closed: drop it (handled by the caller returning undefined).\n return undefined;\n }\n\n const source = value as Record<string, unknown>;\n const output: Record<string, unknown> = {};\n for (const [key, fieldValue] of Object.entries(source)) {\n if (fieldValue === undefined) {\n continue;\n }\n const classification = policy[key];\n if (classification === undefined) {\n // Fail closed: unclassified fields are never emitted, at any reveal\n // level. Adding a field without classifying it hides it — never leaks it.\n continue;\n }\n if (isSensitivity(classification)) {\n if (keepField(classification, reveal)) {\n output[key] = fieldValue;\n }\n continue;\n }\n const nested = redactValue(fieldValue, classification, reveal);\n // A nested projection that emitted nothing is omitted rather than emitted\n // as `{}`. \"Nothing survived redaction\" and \"the field was absent\" are the\n // same thing to a learner — and without this, giving an all-`answer-key`\n // object a nested policy would turn its absence under `reveal: 'none'`\n // into an empty object, changing every existing projection.\n if (nested !== undefined && !isEmptyObject(nested)) {\n output[key] = nested;\n }\n }\n return output;\n}\n\n/**\n * Produces the learner-safe projection of activity data (R7), driven by the\n * `fieldPolicy` registered for `data.type`. Fail-closed and exhaustive by\n * construction: a field the policy does not classify is removed — including\n * unknown passthrough fields — so a NEW field added by a future SDK or a\n * consumer sidecar can never leak through an out-of-date redactor.\n *\n * With the default `reveal: 'none'`, the output validates against the type's\n * strict redacted schema (verified here; an invalid projection throws\n * {@link ActivitySchemaError} rather than shipping an unproven payload).\n *\n * @throws UnknownActivityTypeError when `data.type` is not registered.\n * @throws Error when the registered descriptor declares no `fieldPolicy`\n * (redaction cannot guess sensitivities).\n */\nexport function redact<T extends { type: string }>(\n data: T,\n options: RedactOptions = {},\n): RedactedActivityData {\n const reveal = options.reveal ?? 'none';\n const descriptor = getActivityTypeDescriptor(data.type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(data.type));\n }\n if (descriptor.fieldPolicy === undefined) {\n throw new Error(\n `Activity type \"${descriptor.type}\" has no fieldPolicy; redact() cannot run fail-closed redaction without one.`,\n );\n }\n\n const effectivePolicy = mergePolicy(descriptor.fieldPolicy, options.policy);\n const projected = redactValue(data, effectivePolicy, reveal) as Record<string, unknown>;\n const result = { ...projected, redacted: true as const } as RedactedActivityData;\n\n if (reveal === 'none' && descriptor.redactedSchema !== undefined) {\n const parsed = descriptor.redactedSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe redacted projection: it carries the\n * `redacted: true` marker and, when its type registers a strict redacted\n * schema, validates against it (proving the absence of answer-key fields).\n * Use this at the server boundary before sending activity data to a client\n * that must not hold the key.\n */\nexport function assertRedacted(data: unknown): asserts data is RedactedActivityData {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('unknown', [\n { path: [], message: 'Redacted activity data must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError(String(candidate.type ?? 'unknown'), [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redact() projection.',\n code: 'custom',\n },\n ]);\n }\n const type = typeof candidate.type === 'string' ? candidate.type : '';\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(type);\n }\n if (descriptor.redactedSchema === undefined) {\n // Fail closed: without a registered redacted schema there is no way to\n // PROVE the absence of answer-key fields, and a marker alone proves\n // nothing (any object can carry `redacted: true`).\n throw new ActivitySchemaError(descriptor.type, [\n {\n path: [],\n message: `Activity type \"${descriptor.type}\" registers no redactedSchema; assertRedacted cannot prove this payload is learner-safe.`,\n code: 'custom',\n },\n ]);\n }\n const parsed = descriptor.redactedSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n}\n\n/**\n * Sensitivity of a stimulus. Everything is learner-visible — that is what a\n * stimulus IS — except the author transcript. Fail-closed like every other\n * policy: a field added to `Stimulus` without a classification here is\n * dropped, never leaked.\n */\nconst STIMULUS_FIELD_POLICY: FieldPolicy = {\n id: 'public',\n kind: 'public',\n title: 'public',\n body: 'public',\n bodyHtml: 'public',\n media: MEDIA_FIELD_POLICY,\n locale: 'public',\n attribution: 'public',\n transcript: 'author-only',\n};\n\n/** The group container's own fields. `items` is handled separately, per item type. */\nconst ITEM_GROUP_FIELD_POLICY: FieldPolicy = {\n schemaVersion: 'public',\n type: 'public',\n id: 'public',\n title: 'public',\n // See the note on the built-in activity policies: a slot key is identity,\n // and identity has to cross the redaction boundary intact.\n slotKey: 'public',\n shuffle: 'public',\n stimulus: STIMULUS_FIELD_POLICY,\n};\n\n/** A learner-safe item group: the container with its marker, holding `redact()` projections. */\nexport type RedactedItemGroup = ItemGroup<RedactedActivityData> & { redacted: true };\n\n/**\n * Produces the learner-safe projection of an item group: the container and\n * stimulus under their own fail-closed policy (the author transcript goes;\n * the passage, media and attribution stay — the learner is meant to see\n * them), and every item through {@link redact} with the same `options`, so\n * a per-call `policy` tightens each item exactly as it would alone.\n *\n * With the default `reveal: 'none'` the container is verified against the\n * strict redacted schema; each item was already verified by `redact`.\n */\nexport function redactItemGroup<TItem extends { type: string }>(\n group: ItemGroup<TItem>,\n options: RedactOptions = {},\n): RedactedItemGroup {\n const reveal = options.reveal ?? 'none';\n const { items, ...container } = group;\n const projected = redactValue(container, ITEM_GROUP_FIELD_POLICY, reveal) as Record<\n string,\n unknown\n >;\n const result = {\n ...projected,\n items: items.map((item) => redact(item, options)),\n redacted: true as const,\n } as RedactedItemGroup;\n\n if (reveal === 'none') {\n const parsed = RedactedItemGroupSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe item group: it carries the marker,\n * its container and stimulus satisfy the strict redacted schema (so no\n * transcript, no unclassified field), and EVERY item passes\n * {@link assertRedacted} against its own type's redacted schema. Item\n * failures are reported at `items.<index>.…`. Use it at the server boundary\n * before sending a group to a client that must not hold the key.\n */\nexport function assertRedactedItemGroup(data: unknown): asserts data is RedactedItemGroup {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('item-group', [\n { path: [], message: 'Redacted item group must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError('item-group', [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redactItemGroup() projection.',\n code: 'custom',\n },\n ]);\n }\n const parsed = RedactedItemGroupSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n parsed.data.items.forEach((item, index) => {\n try {\n assertRedacted(item);\n } catch (error) {\n if (error instanceof ActivitySchemaError) {\n throw new ActivitySchemaError(\n 'item-group',\n error.errors.map((issue) => ({\n ...issue,\n path: ['items', String(index), ...issue.path],\n })),\n );\n }\n throw error;\n }\n });\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -2,8 +2,8 @@ import { ScoredItem } from './scoring.cjs';
2
2
  export { AssessmentScore, AssessmentSectionInput, Band, CompositionPolicy, DEFAULT_PASS_THRESHOLD, DICTATION_MAX_ACCEPTED_TRANSCRIPTS, DICTATION_MAX_EQUIVALENCES, DICTATION_MAX_EQUIVALENCE_LENGTH, DICTATION_MAX_TEXT_LENGTH, DICTATION_MAX_TRANSCRIPT_LENGTH, DictationAlignment, DictationCharOp, DictationReference, DictationWordAlignment, PassFailureReason, RoundingMode, RoundingPolicy, ScoringOptions, SectionScore, alignDictation, classifyBand, composeAssessmentScore, computePassThreshold, dictationReferenceWords, diffDictationChars, evaluate, gte, roundGrade, score } from './scoring.cjs';
3
3
  import { w as ItemOutcome, A as ActivityData, L as LearnerResponse, V as ValidationError, e as ActivityType, a as ActivityDataMap, C as CriterionScore, p as GradeRecord, N as NativeControlHint, c as ActivityMedia, K as ScoringResult, D as DeferredScoringPartial, f as DictationData, h as DictationLearnerResponse, F as FillInTheBlanksData, k as FillInTheBlanksLearnerResponse, m as GapSelectData, o as GapSelectLearnerResponse, y as MultipleChoiceData, z as MultipleChoiceLearnerResponse, W as WrittenResponseData, Q as WrittenResponseLearnerResponse } from './activity-DfAmJ1sl.cjs';
4
4
  export { b as ActivityFeedback, d as ActivityResult, B as BlankConfig, g as DictationEquivalence, i as DictationSlowMedia, j as DictationTolerance, G as GapSelectBank, l as GapSelectChoice, n as GapSelectGap, q as Grader, r as GraderKind, s as GraderUsage, t as GradingState, I as InlineCorrection, u as InteractionEvent, v as InteractionKind, x as LearnerResponseMap, M as MediaPlaybackPolicy, E as MultipleChoiceOption, H as MultipleChoiceOptionMedia, S as ScoringDetail, J as ScoringOutcome, T as TextMatchPolicy, O as TextMatchResult, P as ValidationResult, R as WrittenResponseRubric, U as WrittenResponseRubricCriterion, X as XAPIActor, Y as XAPIConfig, Z as XAPIContext, _ as XAPIContextActivities, $ as XAPIError, a0 as XAPIObject, a1 as XAPIResult, a2 as XAPIScore, a3 as XAPIStatement, a4 as XAPIVerbObject, a5 as levenshteinDistance, a6 as matchText } from './activity-DfAmJ1sl.cjs';
5
- import { Y as SequenceSlot, X as SequenceEntry, I as ItemGroup } from './index-Bz9wUigA.cjs';
6
- export { B as BlankConfigSchema, D as DictationDataSchema, a as DictationEquivalenceSchema, b as DictationSlowMediaSchema, c as DictationToleranceSchema, F as FeedbackSchema, d as FillInTheBlanksDataSchema, G as GapSelectBankSchema, e as GapSelectChoiceSchema, f as GapSelectDataSchema, g as GapSelectGapSchema, h as ItemGroupSchema, M as MediaPlaybackSchema, i as MediaSchema, j as MediaUrlSchema, k as MultipleChoiceDataSchema, l as MultipleChoiceOptionMediaSchema, m as MultipleChoiceOptionSchema, N as NativeControlHintSchema, R as RedactedActivity, n as RedactedBlankConfig, o as RedactedBlankConfigSchema, p as RedactedDictationData, q as RedactedDictationDataSchema, r as RedactedDictationSlowMedia, s as RedactedDictationSlowMediaSchema, t as RedactedFillInTheBlanksData, u as RedactedFillInTheBlanksDataSchema, v as RedactedGapSelectBank, w as RedactedGapSelectBankSchema, x as RedactedGapSelectChoice, y as RedactedGapSelectChoiceSchema, z as RedactedGapSelectData, A as RedactedGapSelectDataSchema, C as RedactedGapSelectGap, E as RedactedGapSelectGapSchema, H as RedactedItemGroupSchema, J as RedactedMediaSchema, K as RedactedMultipleChoiceData, L as RedactedMultipleChoiceDataSchema, O as RedactedMultipleChoiceOption, P as RedactedMultipleChoiceOptionMedia, Q as RedactedMultipleChoiceOptionMediaSchema, S as RedactedMultipleChoiceOptionSchema, T as RedactedStimulus, U as RedactedStimulusSchema, V as RedactedWrittenResponseData, W as RedactedWrittenResponseDataSchema, Z as SequenceSlotGroup, _ as Stimulus, $ as StimulusKind, a0 as StimulusSchema, a1 as TextMatchPolicySchema, a2 as WrittenResponseDataSchema, a3 as WrittenResponseRubricCriterionSchema, a4 as WrittenResponseRubricSchema, a5 as dictationJsonSchema, a6 as fillInTheBlanksJsonSchema, a7 as gapSelectJsonSchema, a8 as itemGroupJsonSchema, a9 as jsonSchemaFor, aa as multipleChoiceJsonSchema, ab as stimulusJsonSchema, ac as validateActivity, ad as validateItemGroup, ae as writtenResponseJsonSchema } from './index-Bz9wUigA.cjs';
5
+ import { Y as SequenceSlot, X as SequenceEntry, I as ItemGroup } from './index-BefQ8FAS.cjs';
6
+ export { B as BlankConfigSchema, D as DictationDataSchema, a as DictationEquivalenceSchema, b as DictationSlowMediaSchema, c as DictationToleranceSchema, F as FeedbackSchema, d as FillInTheBlanksDataSchema, G as GapSelectBankSchema, e as GapSelectChoiceSchema, f as GapSelectDataSchema, g as GapSelectGapSchema, h as ItemGroupSchema, M as MediaPlaybackSchema, i as MediaSchema, j as MediaUrlSchema, k as MultipleChoiceDataSchema, l as MultipleChoiceOptionMediaSchema, m as MultipleChoiceOptionSchema, N as NativeControlHintSchema, R as RedactedActivity, n as RedactedBlankConfig, o as RedactedBlankConfigSchema, p as RedactedDictationData, q as RedactedDictationDataSchema, r as RedactedDictationSlowMedia, s as RedactedDictationSlowMediaSchema, t as RedactedFillInTheBlanksData, u as RedactedFillInTheBlanksDataSchema, v as RedactedGapSelectBank, w as RedactedGapSelectBankSchema, x as RedactedGapSelectChoice, y as RedactedGapSelectChoiceSchema, z as RedactedGapSelectData, A as RedactedGapSelectDataSchema, C as RedactedGapSelectGap, E as RedactedGapSelectGapSchema, H as RedactedItemGroupSchema, J as RedactedMediaSchema, K as RedactedMultipleChoiceData, L as RedactedMultipleChoiceDataSchema, O as RedactedMultipleChoiceOption, P as RedactedMultipleChoiceOptionMedia, Q as RedactedMultipleChoiceOptionMediaSchema, S as RedactedMultipleChoiceOptionSchema, T as RedactedStimulus, U as RedactedStimulusSchema, V as RedactedWrittenResponseData, W as RedactedWrittenResponseDataSchema, Z as SequenceSlotGroup, _ as Stimulus, $ as StimulusKind, a0 as StimulusSchema, a1 as TextMatchPolicySchema, a2 as WrittenResponseDataSchema, a3 as WrittenResponseRubricCriterionSchema, a4 as WrittenResponseRubricSchema, a5 as dictationJsonSchema, a6 as fillInTheBlanksJsonSchema, a7 as gapSelectJsonSchema, a8 as itemGroupJsonSchema, a9 as jsonSchemaFor, aa as multipleChoiceJsonSchema, ab as stimulusJsonSchema, ac as validateActivity, ad as validateItemGroup, ae as writtenResponseJsonSchema } from './index-BefQ8FAS.cjs';
7
7
  import { z } from 'zod/v4';
8
8
  export { AnsweredStatementParams, CompletedStatementParams, SubmittedStatementParams, XAPIObjectParams, XAPIStatementParams, XAPIVerb, XAPIVerbKey, XAPI_VERB_DISPLAY, validateXAPIStatement, xAPIBuilder, xapiDefinitionFor } from './xapi.cjs';
9
9
 
@@ -413,6 +413,11 @@ declare function createItemGroupDraft(context: DraftContext): ItemGroup;
413
413
  *
414
414
  * The group is `complete` only when the container passes, every item passes its
415
415
  * own schema, and every item is itself `complete`.
416
+ *
417
+ * @throws the error a registered item type's `checkDraft` or schema throws, as
418
+ * `validateDraft` does for that item on its own. Only an unregistered type is
419
+ * turned into an issue: a fault in a type's own code is not a problem with the
420
+ * draft, and reporting it as an unknown type would hide it.
416
421
  */
417
422
  declare function validateItemGroupDraft(draft: unknown): DraftValidationResult<ItemGroup>;
418
423
 
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import { ScoredItem } from './scoring.js';
2
2
  export { AssessmentScore, AssessmentSectionInput, Band, CompositionPolicy, DEFAULT_PASS_THRESHOLD, DICTATION_MAX_ACCEPTED_TRANSCRIPTS, DICTATION_MAX_EQUIVALENCES, DICTATION_MAX_EQUIVALENCE_LENGTH, DICTATION_MAX_TEXT_LENGTH, DICTATION_MAX_TRANSCRIPT_LENGTH, DictationAlignment, DictationCharOp, DictationReference, DictationWordAlignment, PassFailureReason, RoundingMode, RoundingPolicy, ScoringOptions, SectionScore, alignDictation, classifyBand, composeAssessmentScore, computePassThreshold, dictationReferenceWords, diffDictationChars, evaluate, gte, roundGrade, score } from './scoring.js';
3
3
  import { w as ItemOutcome, A as ActivityData, L as LearnerResponse, V as ValidationError, e as ActivityType, a as ActivityDataMap, C as CriterionScore, p as GradeRecord, N as NativeControlHint, c as ActivityMedia, K as ScoringResult, D as DeferredScoringPartial, f as DictationData, h as DictationLearnerResponse, F as FillInTheBlanksData, k as FillInTheBlanksLearnerResponse, m as GapSelectData, o as GapSelectLearnerResponse, y as MultipleChoiceData, z as MultipleChoiceLearnerResponse, W as WrittenResponseData, Q as WrittenResponseLearnerResponse } from './activity-DfAmJ1sl.js';
4
4
  export { b as ActivityFeedback, d as ActivityResult, B as BlankConfig, g as DictationEquivalence, i as DictationSlowMedia, j as DictationTolerance, G as GapSelectBank, l as GapSelectChoice, n as GapSelectGap, q as Grader, r as GraderKind, s as GraderUsage, t as GradingState, I as InlineCorrection, u as InteractionEvent, v as InteractionKind, x as LearnerResponseMap, M as MediaPlaybackPolicy, E as MultipleChoiceOption, H as MultipleChoiceOptionMedia, S as ScoringDetail, J as ScoringOutcome, T as TextMatchPolicy, O as TextMatchResult, P as ValidationResult, R as WrittenResponseRubric, U as WrittenResponseRubricCriterion, X as XAPIActor, Y as XAPIConfig, Z as XAPIContext, _ as XAPIContextActivities, $ as XAPIError, a0 as XAPIObject, a1 as XAPIResult, a2 as XAPIScore, a3 as XAPIStatement, a4 as XAPIVerbObject, a5 as levenshteinDistance, a6 as matchText } from './activity-DfAmJ1sl.js';
5
- import { Y as SequenceSlot, X as SequenceEntry, I as ItemGroup } from './index-CJbbVE9o.js';
6
- export { B as BlankConfigSchema, D as DictationDataSchema, a as DictationEquivalenceSchema, b as DictationSlowMediaSchema, c as DictationToleranceSchema, F as FeedbackSchema, d as FillInTheBlanksDataSchema, G as GapSelectBankSchema, e as GapSelectChoiceSchema, f as GapSelectDataSchema, g as GapSelectGapSchema, h as ItemGroupSchema, M as MediaPlaybackSchema, i as MediaSchema, j as MediaUrlSchema, k as MultipleChoiceDataSchema, l as MultipleChoiceOptionMediaSchema, m as MultipleChoiceOptionSchema, N as NativeControlHintSchema, R as RedactedActivity, n as RedactedBlankConfig, o as RedactedBlankConfigSchema, p as RedactedDictationData, q as RedactedDictationDataSchema, r as RedactedDictationSlowMedia, s as RedactedDictationSlowMediaSchema, t as RedactedFillInTheBlanksData, u as RedactedFillInTheBlanksDataSchema, v as RedactedGapSelectBank, w as RedactedGapSelectBankSchema, x as RedactedGapSelectChoice, y as RedactedGapSelectChoiceSchema, z as RedactedGapSelectData, A as RedactedGapSelectDataSchema, C as RedactedGapSelectGap, E as RedactedGapSelectGapSchema, H as RedactedItemGroupSchema, J as RedactedMediaSchema, K as RedactedMultipleChoiceData, L as RedactedMultipleChoiceDataSchema, O as RedactedMultipleChoiceOption, P as RedactedMultipleChoiceOptionMedia, Q as RedactedMultipleChoiceOptionMediaSchema, S as RedactedMultipleChoiceOptionSchema, T as RedactedStimulus, U as RedactedStimulusSchema, V as RedactedWrittenResponseData, W as RedactedWrittenResponseDataSchema, Z as SequenceSlotGroup, _ as Stimulus, $ as StimulusKind, a0 as StimulusSchema, a1 as TextMatchPolicySchema, a2 as WrittenResponseDataSchema, a3 as WrittenResponseRubricCriterionSchema, a4 as WrittenResponseRubricSchema, a5 as dictationJsonSchema, a6 as fillInTheBlanksJsonSchema, a7 as gapSelectJsonSchema, a8 as itemGroupJsonSchema, a9 as jsonSchemaFor, aa as multipleChoiceJsonSchema, ab as stimulusJsonSchema, ac as validateActivity, ad as validateItemGroup, ae as writtenResponseJsonSchema } from './index-CJbbVE9o.js';
5
+ import { Y as SequenceSlot, X as SequenceEntry, I as ItemGroup } from './index-BiIvdASA.js';
6
+ export { B as BlankConfigSchema, D as DictationDataSchema, a as DictationEquivalenceSchema, b as DictationSlowMediaSchema, c as DictationToleranceSchema, F as FeedbackSchema, d as FillInTheBlanksDataSchema, G as GapSelectBankSchema, e as GapSelectChoiceSchema, f as GapSelectDataSchema, g as GapSelectGapSchema, h as ItemGroupSchema, M as MediaPlaybackSchema, i as MediaSchema, j as MediaUrlSchema, k as MultipleChoiceDataSchema, l as MultipleChoiceOptionMediaSchema, m as MultipleChoiceOptionSchema, N as NativeControlHintSchema, R as RedactedActivity, n as RedactedBlankConfig, o as RedactedBlankConfigSchema, p as RedactedDictationData, q as RedactedDictationDataSchema, r as RedactedDictationSlowMedia, s as RedactedDictationSlowMediaSchema, t as RedactedFillInTheBlanksData, u as RedactedFillInTheBlanksDataSchema, v as RedactedGapSelectBank, w as RedactedGapSelectBankSchema, x as RedactedGapSelectChoice, y as RedactedGapSelectChoiceSchema, z as RedactedGapSelectData, A as RedactedGapSelectDataSchema, C as RedactedGapSelectGap, E as RedactedGapSelectGapSchema, H as RedactedItemGroupSchema, J as RedactedMediaSchema, K as RedactedMultipleChoiceData, L as RedactedMultipleChoiceDataSchema, O as RedactedMultipleChoiceOption, P as RedactedMultipleChoiceOptionMedia, Q as RedactedMultipleChoiceOptionMediaSchema, S as RedactedMultipleChoiceOptionSchema, T as RedactedStimulus, U as RedactedStimulusSchema, V as RedactedWrittenResponseData, W as RedactedWrittenResponseDataSchema, Z as SequenceSlotGroup, _ as Stimulus, $ as StimulusKind, a0 as StimulusSchema, a1 as TextMatchPolicySchema, a2 as WrittenResponseDataSchema, a3 as WrittenResponseRubricCriterionSchema, a4 as WrittenResponseRubricSchema, a5 as dictationJsonSchema, a6 as fillInTheBlanksJsonSchema, a7 as gapSelectJsonSchema, a8 as itemGroupJsonSchema, a9 as jsonSchemaFor, aa as multipleChoiceJsonSchema, ab as stimulusJsonSchema, ac as validateActivity, ad as validateItemGroup, ae as writtenResponseJsonSchema } from './index-BiIvdASA.js';
7
7
  import { z } from 'zod/v4';
8
8
  export { AnsweredStatementParams, CompletedStatementParams, SubmittedStatementParams, XAPIObjectParams, XAPIStatementParams, XAPIVerb, XAPIVerbKey, XAPI_VERB_DISPLAY, validateXAPIStatement, xAPIBuilder, xapiDefinitionFor } from './xapi.js';
9
9
 
@@ -413,6 +413,11 @@ declare function createItemGroupDraft(context: DraftContext): ItemGroup;
413
413
  *
414
414
  * The group is `complete` only when the container passes, every item passes its
415
415
  * own schema, and every item is itself `complete`.
416
+ *
417
+ * @throws the error a registered item type's `checkDraft` or schema throws, as
418
+ * `validateDraft` does for that item on its own. Only an unregistered type is
419
+ * turned into an issue: a fault in a type's own code is not a problem with the
420
+ * draft, and reporting it as an unknown type would hide it.
416
421
  */
417
422
  declare function validateItemGroupDraft(draft: unknown): DraftValidationResult<ItemGroup>;
418
423
 
package/dist/index.js CHANGED
@@ -858,7 +858,10 @@ function checkItems(draft) {
858
858
  let result;
859
859
  try {
860
860
  result = validateDraft(item.type, item);
861
- } catch {
861
+ } catch (error) {
862
+ if (!(error instanceof UnknownActivityTypeError) || error.activityType !== item.type) {
863
+ throw error;
864
+ }
862
865
  issues.push(
863
866
  issue(
864
867
  "ig_item_type_unknown",