@intellectif/lk-core 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +5 -4
  3. package/dist/{chunk-2M76F32Y.js → chunk-6DM2H6BD.js} +2 -2
  4. package/dist/{chunk-HCOWSGEZ.js → chunk-AHEUYOT3.js} +705 -17
  5. package/dist/chunk-AHEUYOT3.js.map +1 -0
  6. package/dist/{chunk-FKH4YT5X.cjs → chunk-CVRALNUK.cjs} +706 -18
  7. package/dist/chunk-CVRALNUK.cjs.map +1 -0
  8. package/dist/{chunk-NHGXOOZ2.js → chunk-ELTP5P6V.js} +2 -2
  9. package/dist/{chunk-YJZY5TPY.cjs → chunk-MOLL5KXO.cjs} +8 -8
  10. package/dist/{chunk-YJZY5TPY.cjs.map → chunk-MOLL5KXO.cjs.map} +1 -1
  11. package/dist/{chunk-LNA33IK7.js → chunk-QX7P3CHP.js} +2 -2
  12. package/dist/{chunk-7ACNBDSF.cjs → chunk-RL2PQLCY.cjs} +4 -4
  13. package/dist/{chunk-7ACNBDSF.cjs.map → chunk-RL2PQLCY.cjs.map} +1 -1
  14. package/dist/{chunk-FVLKIL6W.cjs → chunk-YVZCFUGP.cjs} +12 -12
  15. package/dist/{chunk-FVLKIL6W.cjs.map → chunk-YVZCFUGP.cjs.map} +1 -1
  16. package/dist/index.cjs +134 -42
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +157 -6
  19. package/dist/index.d.ts +157 -6
  20. package/dist/index.js +115 -23
  21. package/dist/index.js.map +1 -1
  22. package/dist/schemas.cjs +3 -3
  23. package/dist/schemas.js +2 -2
  24. package/dist/scoring.cjs +3 -3
  25. package/dist/scoring.js +2 -2
  26. package/dist/xapi.cjs +3 -3
  27. package/dist/xapi.js +2 -2
  28. package/package.json +1 -1
  29. package/dist/chunk-FKH4YT5X.cjs.map +0 -1
  30. package/dist/chunk-HCOWSGEZ.js.map +0 -1
  31. /package/dist/{chunk-2M76F32Y.js.map → chunk-6DM2H6BD.js.map} +0 -0
  32. /package/dist/{chunk-NHGXOOZ2.js.map → chunk-ELTP5P6V.js.map} +0 -0
  33. /package/dist/{chunk-LNA33IK7.js.map → chunk-QX7P3CHP.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/schemas/feedback.ts","../src/schemas/media.ts","../src/schemas/fill-in-the-blanks.ts","../src/count-words.ts","../src/schemas/multiple-choice.ts","../src/schemas/written-response.ts","../src/schemas/redacted.ts","../src/scoring/text-match.ts","../src/registry/registry.ts","../src/authoring/issues.ts","../src/authoring/fill-in-the-blanks.ts","../src/authoring/multiple-choice.ts","../src/authoring/written-response.ts","../src/scoring/strategies/all-or-nothing.ts","../src/scoring/strategies/partial.ts","../src/scoring/activity-scorers/fill-in-the-blanks.ts","../src/scoring/activity-scorers/multiple-choice.ts","../src/registry/builtins.ts"],"sourcesContent":["import type { ValidationError } from './types/activity.js';\n\n/** Thrown when activity data fails schema validation at a component boundary. */\nexport class ActivitySchemaError extends Error {\n constructor(\n public readonly activityType: string,\n public readonly errors: ValidationError[],\n ) {\n super(`Invalid activity data for type \"${activityType}\"`);\n this.name = 'ActivitySchemaError';\n }\n}\n\n/** Thrown when an unrecognised activity type is passed to the scoring engine. */\nexport class UnknownActivityTypeError extends Error {\n constructor(public readonly activityType: string) {\n super(`Activity type \"${activityType}\" is not registered`);\n this.name = 'UnknownActivityTypeError';\n }\n}\n\n/**\n * Thrown when `score()` is asked to grade a `redact()` projection (or any\n * activity data whose answer key is missing, yielding a non-finite score).\n * Redacted data is learner-safe precisely because the key was removed, so a\n * score derived from it is meaningless — previously this produced a silent\n * `NaN` that serialized to `null` in a grade column. `evaluate()` returns\n * `{ status: 'unscorable' }` for the same input instead of throwing.\n */\nexport class RedactedScoringError extends Error {\n constructor(public readonly activityType: string) {\n super(\n `Activity data for \"${activityType}\" carries no answer key (it looks redacted), so it cannot be scored. ` +\n 'Score against the full activity data server-side, or use evaluate() which returns { status: \"unscorable\" }.',\n );\n this.name = 'RedactedScoringError';\n }\n}\n\n/**\n * Thrown when `score()` is called for an activity type whose grading is\n * deferred (asynchronous AI/human grading, e.g. `written-response`). A\n * deferred submission has no synchronous score — treating it as 0 would show\n * a learner a failing grade for work that simply has not been graded yet.\n * Call `evaluate()` instead, which returns `{ status: 'deferred', ... }`.\n */\nexport class DeferredScoringError extends Error {\n constructor(public readonly activityType: string) {\n super(\n `Activity type \"${activityType}\" is graded asynchronously and has no synchronous score. ` +\n `Use evaluate() — it returns { status: 'deferred' } for this type.`,\n );\n this.name = 'DeferredScoringError';\n }\n}\n","import { z } from 'zod/v4';\n\n/**\n * Optional authored \"overall feedback\" shown after submission, selected by\n * whether the learner passed (h5p-style overall feedback). Both fields are\n * optional; non-empty when present.\n */\nexport const FeedbackSchema = z.looseObject({\n correct: z.string().min(1).optional(),\n incorrect: z.string().min(1).optional(),\n});\n","import { z } from 'zod/v4';\n\n/**\n * Optional media attached to an activity, rendered above the question or\n * passage — e.g. a recording to listen to, or an embedded video to watch\n * before answering. URL-only by design: hosting/delivery (S3/CDN, or the\n * provider's own embed for `embed`) is the consuming app's responsibility\n * (see requirements \"Non-Goals and Shared Responsibility\").\n *\n * - `image`: rendered as `<img>` — `alt` is REQUIRED (WCAG 1.1.1 / Req 14.5).\n * - `audio` / `video`: rendered with native controls; `alt` is an optional\n * accessible label; `captionsUrl` points at a WebVTT `<track>`. `url` must\n * be a direct media file (NOT a YouTube/Vimeo page — use `embed` for those).\n * - `embed`: rendered as a sandboxed `<iframe>` for provider players\n * (YouTube/Vimeo/etc.). `url` MUST be the provider's *embeddable* URL\n * (e.g. `https://www.youtube.com/embed/<id>`). `alt` is REQUIRED and used\n * as the iframe's accessible `title` (WCAG 4.1.2 / 2.4.1).\n */\n/**\n * Media URL policy (security-reviewed): absolute URLs must use `https:`,\n * `http:`, `data:`, or `blob:`; root-relative paths (`/media/x.mp3`) are\n * allowed for same-origin hosting. Everything else — notably `javascript:`,\n * `file:`, `ftp:` — is rejected: these URLs land in `src` attributes\n * (including an iframe for `embed`), so an unvetted scheme is a stored-XSS\n * vector in every consuming app.\n */\nexport const MediaUrlSchema = z.union([\n z.url().refine((value) => /^(https?|data|blob):/i.test(value), {\n error: 'Absolute media URLs must use the https:, http:, data:, or blob: scheme.',\n }),\n z.string().regex(/^\\/(?!\\/)\\S*$/, {\n error: 'Relative media URLs must be root-relative (a single leading \"/\").',\n }),\n]);\n\n/**\n * Hints to the BROWSER'S OWN control bar, emitted as `controlsList` tokens.\n *\n * They remove a button, never a capability, and only in engines that implement\n * `controlsList` at all. `hide-download` does NOT prevent a download — the URL\n * is in the page and the bytes are in the network panel. If a recording must\n * not be kept, issue a short-lived signed URL; that is the consuming\n * application's control, not the SDK's.\n *\n * Meaningful only alongside the native bar: there is nothing to hint at once\n * the SDK owns the transport.\n */\nexport const NativeControlHintSchema = z.enum(['hide-download', 'hide-rate']);\n\n/**\n * How an audio recording may be played.\n *\n * STRICT on purpose: an unknown key here is an authoring error. {@link\n * MediaSchema} is loose, so without this a typo one level down (`maxPlay`,\n * `seeking`) would be silently accepted and the whole policy would quietly do\n * nothing on an exam that believed it was enforced.\n *\n * Nothing here is required together with anything else — `{ maxPlays: 2 }` is a\n * complete, valid policy, because `controls` and `seek` RESOLVE to the only\n * values that can keep that promise. The refinements below reject only a\n * combination an author wrote **explicitly** that the renderer cannot honour.\n */\nexport const MediaPlaybackSchema = z.strictObject({\n /**\n * `native` (the resolved default) renders today's `<audio controls>`\n * unchanged. `minimal` — resolved automatically whenever any enforcement\n * field is set — replaces the browser bar with the SDK transport:\n * play/pause, elapsed/total, mute, volume, optional speed, optional\n * scrubber, and a live plays-remaining status.\n */\n controls: z.enum(['native', 'minimal']).optional(),\n /**\n * How many times the recording may be STARTED. A play is consumed when\n * playback begins from anywhere other than where it last stopped, so\n * pausing, resuming, and paging between the questions of one listening\n * group are all free. Enforced in `practice` and `exam`; never in `review`.\n */\n maxPlays: z.number().int().min(1).max(20).optional(),\n /** `none` renders no scrubber and reverts an out-of-band seek to the high-water mark. */\n seek: z.enum(['allow', 'none']).optional(),\n /** `fixed` renders no speed control and snaps `playbackRate` back to 1. */\n rate: z.enum(['allow', 'fixed']).optional(),\n /** Advisory only. See {@link NativeControlHintSchema}. */\n nativeControlHints: z.array(NativeControlHintSchema).min(1).max(2).optional(),\n});\n\nexport const MediaSchema = z\n .looseObject({\n type: z.enum(['image', 'audio', 'video', 'embed']),\n url: MediaUrlSchema,\n alt: z.string().min(1).optional(),\n captionsUrl: MediaUrlSchema.optional(),\n playback: MediaPlaybackSchema.optional(),\n })\n .refine(\n (m) =>\n (m.type !== 'image' && m.type !== 'embed') || (typeof m.alt === 'string' && m.alt.length > 0),\n {\n error: 'image and embed media require non-empty alt text (WCAG 1.1.1 / 4.1.2).',\n path: ['alt'],\n },\n )\n .refine((m) => m.type !== 'embed' || /^https?:\\/\\//i.test(m.url), {\n error:\n 'embed media requires an absolute http(s) provider URL. data:, blob:, and relative URLs are not allowed for embeds — the embed iframe runs with allow-scripts, and a data:/same-origin document there is an XSS vector.',\n path: ['url'],\n })\n .refine((m) => m.playback === undefined || m.type === 'audio', {\n error:\n 'playback policy is supported on audio media only. An embed is a provider iframe the SDK cannot control at all (it has no reliable JS API for a third-party player); an image has nothing to play; video is deliberately deferred, because a video transport must also own fullscreen and Picture-in-Picture and the SDK will not pretend to govern those yet.',\n path: ['playback'],\n })\n .refine(\n (m) =>\n m.playback?.controls !== 'native' ||\n (m.playback.maxPlays === undefined &&\n m.playback.seek !== 'none' &&\n m.playback.rate !== 'fixed'),\n {\n error:\n 'controls: \"native\" cannot carry maxPlays, seek: \"none\" or rate: \"fixed\". The browser\\'s own bar keeps its play button enabled after a budget is spent, and keeps a scrubber that would move and then silently snap back — a control that looks operable and does nothing (WCAG 3.2.2 / 4.1.3). Omit `controls` and the SDK transport is used automatically, or use nativeControlHints for a cosmetic hint.',\n path: ['playback', 'controls'],\n },\n )\n .refine((m) => m.playback?.maxPlays === undefined || m.playback.seek !== 'allow', {\n error:\n 'maxPlays cannot be combined with seek: \"allow\". A play is consumed when playback starts from somewhere other than where it stopped, so scrubbing back mid-play would replay the whole recording without spending anything. Omit `seek` — it resolves to \"none\" under a budget.',\n path: ['playback', 'seek'],\n })\n .refine(\n (m) =>\n m.playback?.controls !== 'minimal' ||\n m.playback.maxPlays !== undefined ||\n m.playback.seek === 'none' ||\n m.playback.rate === 'fixed',\n {\n error:\n 'controls: \"minimal\" with nothing to enforce trades the browser\\'s localized, familiar control bar for the SDK\\'s, and buys nothing. Set maxPlays, seek: \"none\" or rate: \"fixed\", or omit `controls`.',\n path: ['playback', 'controls'],\n },\n )\n .refine(\n (m) =>\n m.playback?.nativeControlHints === undefined ||\n (m.playback.controls !== 'minimal' &&\n m.playback.maxPlays === undefined &&\n m.playback.seek !== 'none' &&\n m.playback.rate !== 'fixed'),\n {\n error:\n \"nativeControlHints only affects the browser's own control bar, and an enforcing policy replaces that bar with the SDK transport — so the hints would be silently inert. Use them on an otherwise unrestricted recording, or drop them.\",\n path: ['playback', 'nativeControlHints'],\n },\n );\n\n/**\n * The strict counterpart of {@link MediaSchema}, for the redacted shapes.\n *\n * `RedactedActivityDataSchema` and `RedactedStimulusSchema` are `strictObject`\n * precisely so an unknown key is a validation failure rather than a\n * passthrough — but they embedded the LOOSE `MediaSchema`, so the strictness\n * stopped at the media boundary and `media.secretAnswerHint` passed\n * `assertRedacted`. This closes it.\n */\nexport const RedactedMediaSchema = z\n .strictObject({\n type: z.enum(['image', 'audio', 'video', 'embed']),\n url: MediaUrlSchema,\n alt: z.string().min(1).optional(),\n captionsUrl: MediaUrlSchema.optional(),\n playback: MediaPlaybackSchema.optional(),\n })\n .refine(\n (m) =>\n (m.type !== 'image' && m.type !== 'embed') || (typeof m.alt === 'string' && m.alt.length > 0),\n {\n error: 'image and embed media require non-empty alt text (WCAG 1.1.1 / 4.1.2).',\n path: ['alt'],\n },\n )\n .refine((m) => m.type !== 'embed' || /^https?:\\/\\//i.test(m.url), {\n error:\n 'embed media requires an absolute http(s) provider URL. data:, blob:, and relative URLs are not allowed for embeds — the embed iframe runs with allow-scripts, and a data:/same-origin document there is an XSS vector.',\n path: ['url'],\n });\n","import { z } from 'zod/v4';\nimport { FeedbackSchema } from './feedback.js';\nimport { MediaSchema } from './media.js';\n\n/**\n * Matches `{{ blank_id }}` placeholders in a passage, capturing the trimmed id.\n * Exported for the draft checks in `authoring/`, which must read a passage\n * exactly as this schema does. It is not re-exported from the package.\n */\nexport const PLACEHOLDER_RE = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/**\n * Zod schema for a `TextMatchPolicy` — the opt-in matching tolerances a blank\n * may declare. Every default reproduces the v1 trim + case-fold semantics.\n */\nexport const TextMatchPolicySchema = z.looseObject({\n caseSensitive: z.boolean().optional(),\n trim: z.boolean().optional(),\n normalize: z.enum(['none', 'NFC', 'NFKC']).optional(),\n foldDiacritics: z.boolean().optional(),\n collapseInnerWhitespace: z.boolean().optional(),\n ignorePunctuation: z.boolean().optional(),\n levenshtein: z.number().int().min(0).optional(),\n locale: z.string().optional(),\n});\n\n/**\n * Zod schema for a single fill-in-the-blank slot configuration. Loose:\n * unknown keys are preserved through validation. Accepted answers must\n * contain non-whitespace characters — a whitespace-only accepted answer\n * normalizes to the empty string and would mark an empty response correct.\n */\nexport const BlankConfigSchema = z.looseObject({\n id: z.string().min(1),\n acceptedAnswers: z\n .array(\n z\n .string()\n .min(1)\n .refine((answer) => answer.trim().length > 0, {\n error: 'Accepted answers must contain non-whitespace characters.',\n }),\n )\n .min(1),\n caseSensitive: z.boolean().optional(),\n trimWhitespace: z.boolean().optional(),\n match: TextMatchPolicySchema.optional(),\n hint: z.string().optional(),\n feedback: z.string().optional(),\n});\n\n/**\n * Zod schema validating the full Fill-in-the-Blanks activity data contract.\n * Loose at every level: unknown keys are preserved, never stripped (B7).\n *\n * The refinement enforces a true one-to-one correspondence between `{{id}}`\n * placeholders and `blanks[].id`: every blank id appears EXACTLY ONCE in the\n * passage and exactly once in `blanks[]`. (The previous set-based check let\n * duplicate placeholders and duplicate blank configs through, corrupting the\n * partial-score denominator and per-item details.)\n */\nexport const FillInTheBlanksDataSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('fill-in-the-blanks'),\n id: z.string().min(1),\n title: z.string().min(1),\n passage: z.string().min(1),\n passageHtml: z.string().optional(),\n blanks: z.array(BlankConfigSchema).min(1),\n scoringStrategy: z.enum(['all-or-nothing', 'partial']),\n media: MediaSchema.optional(),\n feedback: FeedbackSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n })\n .refine(\n (data) => {\n const placeholderCounts = new Map<string, number>();\n for (const match of data.passage.matchAll(PLACEHOLDER_RE)) {\n const id = match[1] as string;\n placeholderCounts.set(id, (placeholderCounts.get(id) ?? 0) + 1);\n }\n const blankIds = data.blanks.map((blank) => blank.id);\n if (new Set(blankIds).size !== blankIds.length) {\n return false;\n }\n if (placeholderCounts.size !== blankIds.length) {\n return false;\n }\n return blankIds.every((id) => placeholderCounts.get(id) === 1);\n },\n {\n error:\n 'Each blank id must appear exactly once in blanks[] and have exactly one matching {{id}} placeholder in the passage, and vice versa.',\n path: ['passage'],\n },\n );\n","/**\n * Canonical word counter for written-response bounds (Req 22.9): tokens are\n * maximal runs of non-whitespace (split on `\\s+`), so hyphenated forms\n * (`well-known`) count as one word. The empty / whitespace-only string counts\n * 0. Consumers must use this helper rather than re-implementing the split so\n * client previews, SDK scoring, and stored `wordCount` values always agree.\n */\nexport function countWords(text: string): number {\n // Tolerate non-strings: this runs on client-supplied submission payloads,\n // where a malformed value must score 0 rather than throw mid-grading.\n if (typeof text !== 'string') {\n return 0;\n }\n const trimmed = text.trim();\n if (trimmed === '') {\n return 0;\n }\n return trimmed.split(/\\s+/).length;\n}\n","import { z } from 'zod/v4';\nimport { FeedbackSchema } from './feedback.js';\nimport { MediaSchema } from './media.js';\n\n/**\n * Zod schema for a single Multiple Choice option. Loose: unknown keys are\n * preserved through validation (forward-compat / consumer sidecars — B7).\n */\nexport const MultipleChoiceOptionSchema = z.looseObject({\n id: z.string().min(1),\n text: z.string().min(1),\n isCorrect: z.boolean(),\n feedback: z.string().optional(),\n});\n\n/**\n * Zod schema validating the full Multiple Choice activity data contract.\n * Loose at every level: unknown keys are preserved, never stripped, so a\n * v0.3 runtime reading a future payload (or a consumer sidecar field) does\n * not silently delete data.\n *\n * Semantic guards: (1) at least one option must be correct, otherwise the\n * activity can never be answered correctly; (2) `mode: 'single'` must have\n * exactly one correct option — multiple correct options under single-select\n * make `showCorrectAnswers` and the xAPI correct-response ambiguous and mask\n * authoring errors; (3) option ids must be unique — the scorer looks options\n * up by id, so a duplicate id makes one option unscoreable. All are\n * unrepresentable in JSON Schema and are dropped from `toJSONSchema` output\n * by design.\n */\nexport const MultipleChoiceDataSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('multiple-choice'),\n id: z.string().min(1),\n title: z.string().min(1),\n question: z.string().min(1),\n questionHtml: z.string().optional(),\n mode: z.enum(['single', 'multi']),\n options: z.array(MultipleChoiceOptionSchema).min(2).max(26),\n scoringStrategy: z.enum(['all-or-nothing', 'partial']),\n media: MediaSchema.optional(),\n feedback: FeedbackSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n shuffle: z.boolean().optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n })\n .refine((data) => data.options.some((option) => option.isCorrect), {\n error: 'At least one option must be marked correct.',\n path: ['options'],\n })\n .refine(\n (data) =>\n data.mode !== 'single' || data.options.filter((option) => option.isCorrect).length === 1,\n {\n error: 'Single-select activities (mode: \"single\") must have exactly one correct option.',\n path: ['options'],\n },\n )\n .refine((data) => new Set(data.options.map((option) => option.id)).size === data.options.length, {\n error: 'Option ids must be unique within the activity.',\n path: ['options'],\n });\n","import { z } from 'zod/v4';\nimport { FeedbackSchema } from './feedback.js';\nimport { MediaSchema } from './media.js';\n\n/** Zod schema for a single rubric criterion. Loose: unknown keys preserved. */\nexport const WrittenResponseRubricCriterionSchema = z.looseObject({\n name: z.string().min(1),\n description: z.string().optional(),\n weight: z.number().min(0),\n});\n\n/** Zod schema for a written-response grading rubric. Loose: unknown keys preserved. */\nexport const WrittenResponseRubricSchema = z.looseObject({\n label: z.string().optional(),\n criteria: z.array(WrittenResponseRubricCriterionSchema).min(1),\n});\n\n/**\n * The strict counterparts of the rubric schemas, for the redacted shapes.\n *\n * The authoring schemas above are loose on purpose (Req 22.5: a consumer's\n * rubric sidecars must survive `validateActivity` verbatim). The REDACTED\n * shape must not be: `RedactedWrittenResponseDataSchema` is a `strictObject`\n * precisely so an unknown key is a validation failure, and embedding the loose\n * rubric there meant the strictness stopped at the rubric boundary — a\n * `rubric.modelAnswer` reached the learner and `assertRedacted` blessed it.\n */\nexport const RedactedWrittenResponseRubricCriterionSchema = z.strictObject({\n name: z.string().min(1),\n description: z.string().optional(),\n weight: z.number().min(0),\n});\n\nexport const RedactedWrittenResponseRubricSchema = z.strictObject({\n label: z.string().optional(),\n criteria: z.array(RedactedWrittenResponseRubricCriterionSchema).min(1),\n});\n\n/**\n * Zod schema validating the Written Response activity data contract (Req 22).\n *\n * Wire-format constraints (Req 22.9): field names are locked for\n * byte-compatibility with consumer-stored rows, and the schema is loose at\n * EVERY level (Req 22.5) — unknown top-level keys, `promptHtml`, `rubric`\n * sidecars and any future fields survive `validateActivity` verbatim.\n */\nexport const WrittenResponseDataSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('written-response'),\n id: z.string().min(1),\n title: z.string().min(1),\n prompt: z.string(),\n promptHtml: z.string().optional(),\n minWords: z.number().int().min(0),\n maxWords: z.number().int().min(1),\n rubric: WrittenResponseRubricSchema.optional(),\n languageTarget: z.string().optional(),\n media: MediaSchema.optional(),\n feedback: FeedbackSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n })\n .refine((data) => data.maxWords >= data.minWords, {\n error: 'maxWords must be greater than or equal to minWords.',\n path: ['maxWords'],\n });\n","import { z } from 'zod/v4';\nimport { RedactedMediaSchema } from './media.js';\nimport { RedactedWrittenResponseRubricSchema } from './written-response.js';\n\n/**\n * Schemas for REDACTED activity data — the learner-safe projection `redact()`\n * produces (R7). Deliberately STRICT (`z.strictObject`), the opposite of the\n * loose content schemas: a redacted payload must prove the ABSENCE of every\n * answer-key and author-only field, so any unknown key is a validation\n * failure, not a passthrough. `assertRedacted` validates against these.\n */\n\n/** Shared fields every redacted activity carries. */\nconst redactedBase = {\n /** Marker distinguishing a redacted projection from full activity data. */\n redacted: z.literal(true),\n /** Slot identity, carried through redaction so the client and the plan agree. */\n slotKey: z.string().min(1).optional(),\n schemaVersion: z.literal('1.0'),\n id: z.string().min(1),\n title: z.string().min(1),\n media: RedactedMediaSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n};\n\n/** A redacted Multiple Choice option: id and display text only — no `isCorrect`, no feedback. */\nexport const RedactedMultipleChoiceOptionSchema = z.strictObject({\n id: z.string().min(1),\n text: z.string().min(1),\n});\n\n/**\n * Redacted Multiple Choice data: renderable (question, mode, options to pick\n * from) with the answer key, per-option feedback, overall feedback, and the\n * scoring strategy removed. `scoringStrategy` is answer-key by design: MC\n * `partial` carries a wrong-selection penalty `all-or-nothing` does not, so\n * knowing the strategy tells a learner whether guessing is free.\n */\nexport const RedactedMultipleChoiceDataSchema = z.strictObject({\n ...redactedBase,\n type: z.literal('multiple-choice'),\n question: z.string().min(1),\n questionHtml: z.string().optional(),\n mode: z.enum(['single', 'multi']),\n options: z.array(RedactedMultipleChoiceOptionSchema).min(2).max(26),\n shuffle: z.boolean().optional(),\n});\n\n/** A redacted blank: id and hint only — no accepted answers, no matching rules, no feedback. */\nexport const RedactedBlankConfigSchema = z.strictObject({\n id: z.string().min(1),\n hint: z.string().optional(),\n});\n\n/** Redacted Fill-in-the-Blanks data: passage and blank slots, key removed. */\nexport const RedactedFillInTheBlanksDataSchema = z.strictObject({\n ...redactedBase,\n type: z.literal('fill-in-the-blanks'),\n passage: z.string().min(1),\n passageHtml: z.string().optional(),\n blanks: z.array(RedactedBlankConfigSchema).min(1),\n});\n\n/**\n * Redacted Written Response data: the prompt, word bounds and rubric are\n * learner-visible (a rubric tells the learner what they are graded on);\n * authored pass/fail feedback is removed until the grade exists.\n */\nexport const RedactedWrittenResponseDataSchema = z.strictObject({\n ...redactedBase,\n type: z.literal('written-response'),\n prompt: z.string(),\n promptHtml: z.string().optional(),\n minWords: z.number().int().min(0),\n maxWords: z.number().int().min(1),\n rubric: RedactedWrittenResponseRubricSchema.optional(),\n languageTarget: z.string().optional(),\n});\n\n/**\n * The learner-safe SHAPE of each built-in type, derived from the strict schema\n * above rather than hand-written beside it.\n *\n * `redact()` returns {@link RedactedActivityData}, which proves a payload is\n * learner-safe but is index-signature typed — it deliberately says nothing\n * about what the payload still CONTAINS. That is right for the assertion and\n * useless for anything that has to render or transport the result, so every\n * integrator ends up re-declaring these interfaces by hand and they drift the\n * moment a schema changes. Deriving them with `z.infer` means the type and the\n * validator can never disagree.\n *\n * Use them for the payload a server sends an exam client, and for the props of\n * a renderer that must never see an answer key.\n */\nexport type RedactedMultipleChoiceOption = z.infer<typeof RedactedMultipleChoiceOptionSchema>;\n/** A Multiple Choice item with the answer key, feedback and strategy removed. */\nexport type RedactedMultipleChoiceData = z.infer<typeof RedactedMultipleChoiceDataSchema>;\n/** A blank with its accepted answers and matching rules removed; the hint survives. */\nexport type RedactedBlankConfig = z.infer<typeof RedactedBlankConfigSchema>;\n/** A Fill-in-the-Blanks item with every accepted answer removed. */\nexport type RedactedFillInTheBlanksData = z.infer<typeof RedactedFillInTheBlanksDataSchema>;\n/** A Written Response item; the rubric survives, because it tells the learner what is assessed. */\nexport type RedactedWrittenResponseData = z.infer<typeof RedactedWrittenResponseDataSchema>;\n\n/**\n * Discriminated union of every built-in redacted activity. Narrow it on\n * `type`, exactly as you would {@link ActivityData}:\n *\n * ```ts\n * function render(item: RedactedActivity) {\n * if (item.type === 'multiple-choice') {\n * return item.options.map((option) => option.text); // no `isCorrect` to leak\n * }\n * }\n * ```\n */\nexport type RedactedActivity =\n | RedactedMultipleChoiceData\n | RedactedFillInTheBlanksData\n | RedactedWrittenResponseData;\n","/**\n * Configurable free-text answer matching (R3.3).\n *\n * Grade-stability contract: the DEFAULTS reproduce the v1 fill-in-the-blanks\n * semantics exactly (trim, then locale-insensitive lowercase, strict `===`).\n * Every tolerance below is opt-in, because changing a default here changes\n * historical grades — and this SDK powers real summative exams.\n */\nexport interface TextMatchPolicy {\n /** Compare case-sensitively. Default `false` (v1 behaviour). */\n caseSensitive?: boolean;\n /** Strip leading/trailing whitespace before comparing. Default `true` (v1 behaviour). */\n trim?: boolean;\n /**\n * Unicode normalization applied to both sides before comparing. Default\n * `'none'` (v1 behaviour). `'NFC'` makes a decomposed `está` (combining\n * U+0301) equal its composed form — the fix for accent-input mismatches in\n * EN/ES/PT content.\n */\n normalize?: 'none' | 'NFC' | 'NFKC';\n /** Treat diacritics as equal to their base letters (`está` ≡ `esta`). Default `false`. */\n foldDiacritics?: boolean;\n /** Collapse runs of inner whitespace to a single space. Default `false`. */\n collapseInnerWhitespace?: boolean;\n /** Ignore Unicode punctuation on both sides. Default `false`. */\n ignorePunctuation?: boolean;\n /** Maximum Levenshtein edit distance still accepted as a match. Default `0`. */\n levenshtein?: number;\n /**\n * BCP 47 tag for locale-aware case folding (e.g. `'tr'` for Turkish dotted /\n * dotless I). Default: locale-insensitive `toLowerCase()` (v1 behaviour).\n */\n locale?: string;\n}\n\n/**\n * How a match was achieved. Lets a consumer award full credit for an `exact`\n * match and partial credit for a `folded` or `fuzzy` one (e.g. diacritic\n * tolerance in a listening gap-fill vs. a spelling test).\n * - `exact` — equal under the baseline trim/case rules alone.\n * - `normalized` — required Unicode normalization, whitespace collapse, or punctuation tolerance.\n * - `folded` — required diacritic folding.\n * - `fuzzy` — required Levenshtein tolerance.\n * - `none` — no accepted answer matched.\n */\nexport interface TextMatchResult {\n matched: boolean;\n via: 'exact' | 'normalized' | 'folded' | 'fuzzy' | 'none';\n}\n\n/** Combining marks (any script) removed for diacritic folding after NFD decomposition. */\nconst COMBINING_MARKS_RE = /\\p{M}/gu;\n/**\n * Unicode punctuation (`\\p{P}`) removed by `ignorePunctuation`. Deliberately\n * NOT `\\p{S}`: symbols like `$`, `+`, `%` can be the substance of an answer\n * (`$100` vs `100`), so a \"punctuation\" toggle must not erase them.\n */\nconst PUNCTUATION_RE = /\\p{P}/gu;\n\nfunction applyBaseline(value: string, policy: TextMatchPolicy): string {\n let result = value;\n if (policy.trim !== false) {\n result = result.trim();\n }\n if (policy.caseSensitive !== true) {\n result = policy.locale ? result.toLocaleLowerCase(policy.locale) : result.toLowerCase();\n }\n return result;\n}\n\nfunction applyNormalization(value: string, policy: TextMatchPolicy): string {\n let result = value;\n if (policy.normalize === 'NFC' || policy.normalize === 'NFKC') {\n result = result.normalize(policy.normalize);\n }\n if (policy.ignorePunctuation === true) {\n result = result.replace(PUNCTUATION_RE, '');\n }\n if (policy.collapseInnerWhitespace === true) {\n // \"Inner\" means between non-space runs. Only trim the ends when the\n // policy's trim is on (its default) — an explicit `trim: false` must not\n // be silently overridden by the collapse.\n result = result.replace(/(?<=\\S)\\s+(?=\\S)/g, ' ');\n if (policy.trim !== false) {\n result = result.trim();\n }\n }\n return result;\n}\n\nfunction applyDiacriticFold(value: string): string {\n return value.normalize('NFD').replace(COMBINING_MARKS_RE, '').normalize('NFC');\n}\n\n/**\n * Levenshtein distance with an early-exit bound: returns `max + 1` as soon as\n * the distance provably exceeds `max`.\n */\nexport function levenshteinDistance(a: string, b: string, max: number): number {\n if (a === b) return 0;\n if (Math.abs(a.length - b.length) > max) return max + 1;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n\n let previous = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i += 1) {\n const current = [i];\n let rowMin = i;\n for (let j = 1; j <= b.length; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n const value = Math.min(\n (previous[j] as number) + 1,\n (current[j - 1] as number) + 1,\n (previous[j - 1] as number) + cost,\n );\n current.push(value);\n if (value < rowMin) rowMin = value;\n }\n if (rowMin > max) return max + 1;\n previous = current;\n }\n return previous[b.length] as number;\n}\n\n/**\n * Matches a learner's input against one or more accepted answers under a\n * {@link TextMatchPolicy}. Tolerances are evaluated in stages — baseline\n * (trim/case), then normalization, then diacritic folding, then Levenshtein —\n * and {@link TextMatchResult.via} reports the first stage that produced the\n * match, so graders can award credit by match quality.\n *\n * With no policy (or an empty one) this is byte-for-byte the v1 matching\n * semantics: `trim` + locale-insensitive `toLowerCase` + strict equality.\n */\nexport function matchText(\n input: string,\n accepted: string | readonly string[],\n policy: TextMatchPolicy = {},\n): TextMatchResult {\n const acceptedList = typeof accepted === 'string' ? [accepted] : accepted;\n const baselineInput = applyBaseline(input, policy);\n const baselineAccepted = acceptedList.map((answer) => applyBaseline(answer, policy));\n\n if (baselineAccepted.some((answer) => answer === baselineInput)) {\n return { matched: true, via: 'exact' };\n }\n\n const usesNormalization =\n policy.normalize === 'NFC' ||\n policy.normalize === 'NFKC' ||\n policy.ignorePunctuation === true ||\n policy.collapseInnerWhitespace === true;\n const normalizedInput = usesNormalization\n ? applyNormalization(baselineInput, policy)\n : baselineInput;\n const normalizedAccepted = usesNormalization\n ? baselineAccepted.map((answer) => applyNormalization(answer, policy))\n : baselineAccepted;\n\n if (usesNormalization && normalizedAccepted.some((answer) => answer === normalizedInput)) {\n return { matched: true, via: 'normalized' };\n }\n\n const foldedInput =\n policy.foldDiacritics === true ? applyDiacriticFold(normalizedInput) : normalizedInput;\n const foldedAccepted =\n policy.foldDiacritics === true\n ? normalizedAccepted.map((answer) => applyDiacriticFold(answer))\n : normalizedAccepted;\n\n if (policy.foldDiacritics === true && foldedAccepted.some((answer) => answer === foldedInput)) {\n return { matched: true, via: 'folded' };\n }\n\n // A learner who typed nothing made no typo. Levenshtein distance from an\n // empty string is just the answer's length, so `levenshtein: 1` on a\n // one-letter blank (\"a\", \"I\") marked an UNANSWERED blank correct — the\n // fuzzy stage rescuing a blank rather than a misspelling. No author enabling\n // typo tolerance intends that, so an empty input never reaches this stage.\n // Exact and normalized matching are untouched: an author who genuinely lists\n // \"\" as an accepted answer still gets it, deliberately, one stage earlier.\n const maxDistance = policy.levenshtein ?? 0;\n if (\n maxDistance > 0 &&\n foldedInput.trim().length > 0 &&\n foldedAccepted.some(\n (answer) => levenshteinDistance(foldedInput, answer, maxDistance) <= maxDistance,\n )\n ) {\n return { matched: true, via: 'fuzzy' };\n }\n\n return { matched: false, via: 'none' };\n}\n","import type { z } from 'zod/v4';\nimport type { DeferredScoringPartial, ScoringResult } from '../types/activity.js';\nimport type { DraftContext, DraftIssue } from '../types/authoring.js';\n\n/** ScoringResult without `passed` — the public `score()` / `evaluate()` fill that in. */\nexport type PartialScoringResult = Omit<ScoringResult, 'passed'>;\n\n/**\n * Sensitivity classification of a single activity-data field, driving\n * `redact()`:\n * - `public` — safe to send to a learner before they answer.\n * - `answer-key` — reveals (or helps infer) the correct answer or the scoring\n * rules; removed unless `reveal: 'after-submit'` is requested.\n * - `author-only` — never leaves the authoring/grading context (e.g. rubrics).\n */\nexport type Sensitivity = 'public' | 'answer-key' | 'author-only';\n\n/**\n * Per-field sensitivity map for an activity type. A `Sensitivity` value\n * classifies the whole field (objects and arrays included); a nested\n * `FieldPolicy` recurses into an object field — and, for an array field,\n * applies to every element. Fail-closed: any field a policy does not mention\n * is treated as `author-only` and removed by `redact()` — adding a field\n * without classifying it hides it, never leaks it.\n */\nexport interface FieldPolicy {\n readonly [field: string]: Sensitivity | FieldPolicy;\n}\n\n/** xAPI interaction types defined by xAPI 1.0.3 (cmi.interaction vocabulary). */\nexport type XAPIInteractionType =\n | 'choice'\n | 'fill-in'\n | 'long-fill-in'\n | 'matching'\n | 'sequencing'\n | 'performance'\n | 'true-false'\n | 'other';\n\n/** Interop facts a generic statement builder cannot infer from data alone. */\nexport interface ActivityTypeInterop<TData> {\n /** IRI for the xAPI Activity `definition.type`. */\n readonly xapiActivityTypeIri?: string;\n /** xAPI `definition.interactionType` for this activity type. */\n readonly xapiInteractionType?: XAPIInteractionType;\n /** Builds the xAPI `correctResponsesPattern` strings for an item. */\n readonly correctResponsesPattern?: (data: TData) => string[];\n}\n\n/**\n * How responses to an activity type are graded:\n * - `sync` — a pure function produces the grade at submit time.\n * - `deferred` — grading happens asynchronously (AI or human) after\n * submission; `partial` reports the facts computable synchronously\n * (e.g. word counts), surfaced in `ItemOutcome.partial`.\n */\nexport type ActivityTypeScoring<TData, TResponse> =\n | {\n readonly kind: 'sync';\n readonly score: (data: TData, response: TResponse) => PartialScoringResult;\n }\n | {\n readonly kind: 'deferred';\n readonly reason: 'requires_async_grading';\n readonly partial?: (data: TData, response: TResponse | undefined) => DeferredScoringPartial;\n };\n\n/**\n * Authoring support for an activity type: the empty draft an editor starts\n * from, and the rules that tell a draft that is unfinished from one that is\n * wrong. Both are optional. Without `checkDraft`, `validateDraft` still works\n * and reports every schema failure as `invalid`; without `createDraft`,\n * `createDraft()` throws for the type.\n */\nexport interface ActivityTypeAuthoring<TData> {\n /**\n * A new draft: every required field present, nothing authored yet. It must\n * come back from `validateDraft` as `incomplete` — never `invalid`, and never\n * `complete` — so a freshly added question is not reported as an error, and\n * cannot pass validation before anyone has written it.\n */\n readonly createDraft?: (context: DraftContext) => TData;\n /**\n * Reports what is missing (`incomplete`) and what is wrong (`invalid`) in a\n * draft. Receives any plain object and must not throw on one.\n *\n * Report each problem at the path the schema reports it. `validateDraft` adds\n * every schema failure as `invalid` unless an issue returned here sits at that\n * path or inside it — so an issue at the wrong path leaves the schema's\n * message standing beside yours, and makes an unfinished draft read as wrong.\n * An issue inside a path accounts for every failure at that path, a list's\n * length included, so report a rule about a whole list at the list's own path.\n * A failure at the root of the draft is accounted for only by an issue at the\n * root. A `null` the schema refuses, where nothing here reports it, comes back\n * as `null_not_allowed` — except inside a plain `z.union`, which reports a\n * failure once, at the union's own path, under its own code.\n *\n * A code documented in `docs/authoring.md` is reported with its documented\n * severity. For a code of your own, a severity other than `'incomplete'` is\n * reported as `invalid`.\n */\n readonly checkDraft?: (draft: Readonly<Record<string, unknown>>) => DraftIssue[];\n}\n\n/**\n * A value-level description of an activity type: its contract (schema), its\n * grading, its redaction policy, and its interop facts. Registering a\n * descriptor makes `validateActivity`, `validateDraft`, `score`, `evaluate`,\n * `redact`, and `jsonSchemaFor` work for the type — an activity type is a value,\n * not a hardcoded union member (R1).\n */\nexport interface ActivityTypeDescriptor<TData extends { type: string }, TResponse> {\n /** The `type` discriminator string (kebab-case by convention). */\n readonly type: TData['type'];\n /** Zod schema validating the activity's data contract. */\n readonly schema: z.ZodType<TData>;\n /** How responses are graded. */\n readonly scoring: ActivityTypeScoring<TData, TResponse>;\n /** Whether a response counts as an answer (vs. blank/untouched). */\n readonly isAnswered?: (response: TResponse | undefined) => boolean;\n /** Per-field sensitivity map driving `redact()`. Fail-closed. */\n readonly fieldPolicy?: FieldPolicy;\n /**\n * Schema the output of `redact(data)` (with default `reveal: 'none'`) must\n * satisfy. Strict by design: it proves the ABSENCE of answer-key fields,\n * so `assertRedacted` can guarantee a payload is safe to send to a learner.\n */\n readonly redactedSchema?: z.ZodType<unknown>;\n /** Interop facts for xAPI (and later QTI) statement building. */\n readonly interop?: ActivityTypeInterop<TData>;\n /** The interaction-event kinds components for this type emit. */\n readonly interactions?: readonly string[];\n /** Draft support for authoring tools. See {@link ActivityTypeAuthoring}. */\n readonly authoring?: ActivityTypeAuthoring<TData>;\n}\n\n/**\n * Internal type-erased descriptor shape stored in the registry. Dispatch call\n * sites cast payloads back; the public generic API preserves inference.\n */\nexport interface RegisteredActivityTypeDescriptor {\n readonly type: string;\n readonly schema: z.ZodType<unknown>;\n readonly scoring:\n | {\n readonly kind: 'sync';\n readonly score: (data: unknown, response: unknown) => PartialScoringResult;\n }\n | {\n readonly kind: 'deferred';\n readonly reason: 'requires_async_grading';\n readonly partial?: (data: unknown, response: unknown) => DeferredScoringPartial;\n };\n readonly isAnswered?: (response: unknown) => boolean;\n readonly fieldPolicy?: FieldPolicy;\n readonly redactedSchema?: z.ZodType<unknown>;\n readonly interop?: ActivityTypeInterop<unknown>;\n readonly interactions?: readonly string[];\n readonly authoring?: ActivityTypeAuthoring<unknown>;\n}\n\n/**\n * Module-scoped default registry (deliberate — no registry instances until a\n * second consumer exists; see roadmap §3.2 / audit §15.3).\n */\nconst registry = new Map<string, RegisteredActivityTypeDescriptor>();\n\n/**\n * Identity helper that gives full type inference when authoring a descriptor:\n *\n * ```ts\n * const myType = defineActivityType<MyTypeData, MyTypeLearnerResponse>({ ... });\n * registerActivityType(myType);\n * ```\n */\nexport function defineActivityType<TData extends { type: string }, TResponse>(\n descriptor: ActivityTypeDescriptor<TData, TResponse>,\n): ActivityTypeDescriptor<TData, TResponse> {\n return descriptor;\n}\n\n/**\n * Registers an activity type on the default registry, making it live for\n * `validateActivity`, `score`, `evaluate`, `redact`, and `jsonSchemaFor`.\n * Re-registering the same descriptor object is a no-op; registering a\n * DIFFERENT descriptor under an existing type throws — silently replacing a\n * type's contract or scoring is exactly the class of accident a summative\n * SDK must not allow.\n */\nexport function registerActivityType<TData extends { type: string }, TResponse>(\n descriptor: ActivityTypeDescriptor<TData, TResponse>,\n): void {\n if (descriptor.type === 'item-group') {\n // The container that holds several items around one stimulus. It has no\n // learner response and no score of its own, so it can never satisfy this\n // contract — and letting a consumer register one would make `isItemGroup`\n // and `flattenSequence` misread their own container.\n throw new Error(\n '\"item-group\" is reserved for the SDK\\'s item-group container (see ItemGroup) and cannot be registered as an activity type.',\n );\n }\n const existing = registry.get(descriptor.type);\n if (existing !== undefined) {\n if ((existing as unknown) === (descriptor as unknown)) {\n return;\n }\n throw new Error(\n `Activity type \"${descriptor.type}\" is already registered. ` +\n 'Registering a different descriptor for an existing type is not allowed.',\n );\n }\n registry.set(descriptor.type, descriptor as unknown as RegisteredActivityTypeDescriptor);\n}\n\n/** Returns the registered descriptor for `type`, or `undefined`. */\nexport function getActivityTypeDescriptor(\n type: string,\n): RegisteredActivityTypeDescriptor | undefined {\n return registry.get(type);\n}\n\n/** The type strings currently registered (built-ins plus consumer-registered). */\nexport function registeredActivityTypes(): string[] {\n return [...registry.keys()];\n}\n","import { MediaSchema } from '../schemas/media.js';\nimport type { DraftIssue, DraftSeverity } from '../types/authoring.js';\n\n/**\n * Every issue code the SDK's draft checks can report, with its severity.\n *\n * A code's severity is part of its contract, so it is fixed here, once: an\n * issue is built from its code, and the same code cannot be `incomplete` in one\n * place and `invalid` in another. `docs/authoring.md` documents this table, and\n * a test holds the two together.\n */\nexport const DRAFT_ISSUE_SEVERITY = {\n // Every registered type — reported by validateDraft itself\n null_not_allowed: 'invalid',\n // Every built-in activity\n schema_version_invalid: 'invalid',\n type_mismatch: 'invalid',\n id_required: 'invalid',\n title_required: 'incomplete',\n scoring_strategy_required: 'incomplete',\n pass_threshold_invalid: 'invalid',\n difficulty_level_invalid: 'invalid',\n feedback_empty: 'incomplete',\n redacted_data: 'invalid',\n media_type_required: 'incomplete',\n media_url_required: 'incomplete',\n media_url_invalid: 'invalid',\n media_alt_required: 'incomplete',\n media_playback_invalid: 'invalid',\n media_invalid: 'invalid',\n // multiple-choice\n mc_question_required: 'incomplete',\n mc_mode_required: 'incomplete',\n mc_options_too_few: 'incomplete',\n mc_options_too_many: 'invalid',\n mc_option_id_required: 'invalid',\n mc_option_id_duplicate: 'invalid',\n mc_option_text_required: 'incomplete',\n mc_option_correctness_required: 'incomplete',\n mc_correct_option_required: 'incomplete',\n mc_single_mode_one_correct: 'invalid',\n // fill-in-the-blanks\n fib_passage_required: 'incomplete',\n fib_blanks_required: 'incomplete',\n fib_blank_id_required: 'invalid',\n fib_blank_id_duplicate: 'invalid',\n fib_accepted_answers_required: 'incomplete',\n fib_accepted_answer_empty: 'incomplete',\n fib_levenshtein_invalid: 'invalid',\n fib_match_locale_invalid: 'invalid',\n fib_match_invalid: 'invalid',\n fib_blank_missing: 'incomplete',\n fib_placeholder_missing: 'incomplete',\n fib_placeholder_duplicate: 'invalid',\n fib_blanks_mismatch: 'invalid',\n // written-response\n wr_prompt_required: 'incomplete',\n wr_min_words_required: 'incomplete',\n wr_min_words_invalid: 'invalid',\n wr_max_words_required: 'incomplete',\n wr_max_words_invalid: 'invalid',\n wr_word_bounds_order: 'invalid',\n wr_rubric_criteria_required: 'incomplete',\n wr_criterion_name_required: 'incomplete',\n wr_criterion_weight_required: 'incomplete',\n wr_criterion_weight_invalid: 'invalid',\n wr_rubric_weights_zero: 'incomplete',\n wr_rubric_weights_too_large: 'invalid',\n} as const satisfies Readonly<Record<string, DraftSeverity>>;\n\nexport type DraftIssueCode = keyof typeof DRAFT_ISSUE_SEVERITY;\n\n/** A draft as a check receives it: any plain object. */\nexport type DraftFields = Readonly<Record<string, unknown>>;\n\n/** A schema library issue, as far as the draft checks read one. */\nexport interface SchemaIssue {\n readonly code: string;\n readonly path: readonly PropertyKey[];\n readonly input?: unknown;\n}\n\nexport function issue(\n code: DraftIssueCode,\n path: readonly (string | number)[],\n message: string,\n): DraftIssue {\n return { path: path.map(String), message, code, severity: DRAFT_ISSUE_SEVERITY[code] };\n}\n\nexport function isRecord(value: unknown): value is DraftFields {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * The value at `path` inside `root`, or `undefined` once the path leaves the\n * data. Used to tell a schema failure caused by `null` from any other.\n */\nexport function valueAt(root: unknown, path: readonly PropertyKey[]): unknown {\n let node: unknown = root;\n for (const segment of path) {\n if (typeof node !== 'object' || node === null) {\n return undefined;\n }\n node = (node as Record<PropertyKey, unknown>)[segment];\n }\n return node;\n}\n\n/**\n * Whether a schema issue is the schema refusing an empty value: a `null`, or an\n * `undefined` entry in a list, which JSON writes as `null`. `validateDraft`\n * reports each such refusal as `null_not_allowed`, so a check leaves them to it.\n *\n * It reads the issue's `input`, so parse with `{ reportInput: true }`. The input\n * is the value the failing check was given. A refinement on a whole object that\n * reports at one of its fields carries the object, so a rule that points at an\n * empty field keeps its own code and message. A discriminated union with no\n * member for its discriminator is the one refusal reported with the object as\n * its input.\n */\nexport function refusesEmpty(root: unknown, schemaIssue: SchemaIssue): boolean {\n const { path } = schemaIssue;\n const value = valueAt(root, path);\n const index = path.at(-1);\n const list = valueAt(root, path.slice(0, -1));\n const empty =\n value === null ||\n (value === undefined &&\n typeof index === 'number' &&\n Array.isArray(list) &&\n index < list.length);\n return empty && (schemaIssue.input === value || schemaIssue.code === 'invalid_union');\n}\n\n/** Absent or `null`: a field nobody has set. */\nexport function isUnset(value: unknown): boolean {\n return value === undefined || value === null;\n}\n\n/**\n * Not written yet: absent, `null`, or a string holding nothing but whitespace.\n *\n * Whitespace counts as unwritten even where the schema accepts it — a title of\n * `\" \"` is a valid string and an unfinished question. So does the empty string\n * a `<select>` placeholder hands over for a field that must be chosen. A value\n * of any other type is left to the schema, which reports it as `invalid`.\n */\nexport function isUnwritten(value: unknown): boolean {\n return isUnset(value) || (typeof value === 'string' && value.trim() === '');\n}\n\n/** An id with nothing in it. Whitespace is an id the schema accepts, so it is one here too. */\nexport function isMissingId(value: unknown): boolean {\n return isUnset(value) || value === '';\n}\n\n/**\n * A whole number JavaScript holds exactly — what the schemas' `.int()` accepts.\n * `2 ** 53` is a whole number, and the schemas refuse it.\n */\nexport function isWholeNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value);\n}\n\n/** A whole number above what JavaScript holds exactly, so that a message can say so. */\nexport function isTooLarge(value: unknown): boolean {\n return typeof value === 'number' && value > Number.MAX_SAFE_INTEGER && Number.isInteger(value);\n}\n\n/**\n * The envelope, `id` and `title`, which every built-in activity has, and which\n * lead its issues. `schemaVersion` and `type` identify the payload rather than\n * say anything an author wrote, so a wrong or missing one is `invalid`.\n */\nexport function checkIdentity(draft: DraftFields, type: string): 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 createDraft has it.',\n ),\n );\n }\n if (draft.type !== type) {\n issues.push(issue('type_mismatch', ['type'], `The draft's type must be \"${type}\".`));\n }\n if (isMissingId(draft.id)) {\n issues.push(issue('id_required', ['id'], 'The activity has no id.'));\n }\n if (isUnwritten(draft.title)) {\n issues.push(issue('title_required', ['title'], 'Add a title.'));\n }\n return issues;\n}\n\n/** `scoringStrategy`, which both synchronously scored built-ins require. */\nexport function checkScoringStrategy(draft: DraftFields): DraftIssue[] {\n return isUnwritten(draft.scoringStrategy)\n ? [\n issue(\n 'scoring_strategy_required',\n ['scoringStrategy'],\n 'Choose how the question is scored.',\n ),\n ]\n : [];\n}\n\nconst DIFFICULTY_LEVELS: readonly unknown[] = [1, 2, 3, 4, 5];\n\n/**\n * The optional fields every built-in activity shares, checked after its own\n * fields. A `null` in any of them is left to `validateDraft`, which reports\n * `null_not_allowed` for every type alike.\n */\nexport function checkSharedOptional(draft: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n const threshold = draft.passThreshold;\n if (!isUnset(threshold) && !(typeof threshold === 'number' && threshold >= 0 && threshold <= 1)) {\n issues.push(\n issue(\n 'pass_threshold_invalid',\n ['passThreshold'],\n 'The pass threshold must be a number from 0 to 1.',\n ),\n );\n }\n if (!isUnset(draft.difficultyLevel) && !DIFFICULTY_LEVELS.includes(draft.difficultyLevel)) {\n issues.push(\n issue(\n 'difficulty_level_invalid',\n ['difficultyLevel'],\n 'The difficulty level must be a whole number from 1 to 5.',\n ),\n );\n }\n const feedback = draft.feedback;\n if (isRecord(feedback)) {\n for (const key of ['correct', 'incorrect'] as const) {\n const message = feedback[key];\n if (typeof message === 'string' && message.trim() === '') {\n issues.push(\n issue('feedback_empty', ['feedback', key], 'Write this feedback message, or remove it.'),\n );\n }\n }\n }\n // What `redact()` produces for a learner. Its answer key is gone, and the\n // components refuse it outright in `practice`, so it is never a draft.\n if (draft.redacted === true) {\n issues.push(\n issue(\n 'redacted_data',\n ['redacted'],\n 'This is a copy prepared for learners, with the answer key removed. Edit the original activity instead.',\n ),\n );\n }\n if (isRecord(draft.media)) {\n issues.push(...checkMedia(draft.media));\n }\n return issues;\n}\n\nconst URL_POLICY =\n 'Use an https:, http:, data: or blob: address, or a path on the same site that starts with a single \"/\".';\nconst EMBED_URL =\n \"An embed needs the provider's full http(s) embed address, such as https://www.youtube.com/embed/VIDEO_ID.\";\n\n/**\n * Media, checked through `MediaSchema` itself, so the URL and playback rules\n * live in one place. What this adds is the split: a kind, an address or a\n * description nobody has given yet is `incomplete`; one that is given and\n * refused is `invalid`.\n */\nfunction checkMedia(media: DraftFields): DraftIssue[] {\n const issues: DraftIssue[] = [];\n const parsed = MediaSchema.safeParse(media, { reportInput: true });\n // A refused `null` inside the media block is `validateDraft`'s to report, as\n // `null_not_allowed` — unless a check below reads it as a field not set yet.\n const schemaIssues = parsed.success\n ? []\n : parsed.error.issues.filter((found) => !refusesEmpty(media, found));\n const refusal = (field: string) => schemaIssues.find((found) => found.path[0] === field);\n\n const typeUnset = isUnwritten(media.type);\n if (typeUnset) {\n issues.push(\n issue('media_type_required', ['media', 'type'], 'Choose what kind of media this is.'),\n );\n }\n\n if (isUnwritten(media.url)) {\n issues.push(\n issue('media_url_required', ['media', 'url'], 'Add the address of the media file.'),\n );\n } else {\n const refused = refusal('url');\n if (refused !== undefined) {\n // The only refinement on `url` is the embed rule; every other refusal is\n // the address policy itself, which zod reports only as \"Invalid input\".\n issues.push(\n issue(\n 'media_url_invalid',\n ['media', 'url'],\n refused.code === 'custom' ? EMBED_URL : URL_POLICY,\n ),\n );\n }\n }\n\n const needsAlt = media.type === 'image' || media.type === 'embed';\n const alt = media.alt;\n if ((needsAlt && isUnwritten(alt)) || (typeof alt === 'string' && alt.trim() === '')) {\n issues.push(\n issue('media_alt_required', ['media', 'alt'], 'Add a text description of the media.'),\n );\n }\n\n const captions = media.captionsUrl;\n if (typeof captions === 'string' && captions.trim() === '') {\n // Optional, and left blank: unfinished, as a blank description is.\n issues.push(\n issue(\n 'media_url_required',\n ['media', 'captionsUrl'],\n 'Add the address of the captions file, or remove the captions.',\n ),\n );\n } else if (refusal('captionsUrl') !== undefined) {\n issues.push(issue('media_url_invalid', ['media', 'captionsUrl'], URL_POLICY));\n }\n\n for (const schemaIssue of schemaIssues) {\n const field = schemaIssue.path[0];\n if (\n field === 'url' ||\n field === 'alt' ||\n field === 'captionsUrl' ||\n (field === 'type' && typeUnset)\n ) {\n continue;\n }\n issues.push(\n issue(\n field === 'playback' ? 'media_playback_invalid' : 'media_invalid',\n ['media', ...schemaIssue.path.map(String)],\n schemaIssue.message,\n ),\n );\n }\n return issues;\n}\n","import type { ActivityTypeAuthoring } from '../registry/registry.js';\nimport { PLACEHOLDER_RE, TextMatchPolicySchema } from '../schemas/fill-in-the-blanks.js';\nimport type { FillInTheBlanksData } from '../types/activity.js';\nimport type { DraftIssue } from '../types/authoring.js';\nimport {\n checkIdentity,\n checkScoringStrategy,\n checkSharedOptional,\n type DraftFields,\n isMissingId,\n isRecord,\n issue,\n isTooLarge,\n isUnset,\n isUnwritten,\n isWholeNumber,\n refusesEmpty,\n} from './issues.js';\n\n/**\n * Draft support for `fill-in-the-blanks`.\n *\n * A new draft has an empty passage and no blanks, and `scoringStrategy` starts\n * at `all-or-nothing`, as for multiple choice: partial credit is the author's\n * call.\n *\n * The passage and the blanks must pair up one to one. When they do not, the\n * issue says which way. A placeholder with no blank, or a blank with no\n * placeholder, is something still to be written (`incomplete`). The same\n * placeholder twice, or two blanks sharing an id, cannot be fixed by writing\n * more (`invalid`). All of them are reported at `passage`, which is where the\n * schema reports the pairing.\n */\nexport const fillInTheBlanksAuthoring: ActivityTypeAuthoring<FillInTheBlanksData> = {\n createDraft: ({ newId }) => ({\n schemaVersion: '1.0',\n type: 'fill-in-the-blanks',\n id: newId(),\n title: '',\n passage: '',\n blanks: [],\n scoringStrategy: 'all-or-nothing',\n }),\n checkDraft: checkFillInTheBlanksDraft,\n};\n\nfunction checkFillInTheBlanksDraft(draft: DraftFields): DraftIssue[] {\n const issues = checkIdentity(draft, 'fill-in-the-blanks');\n const passage = draft.passage;\n if (isUnwritten(passage)) {\n issues.push(issue('fib_passage_required', ['passage'], 'Write the passage.'));\n }\n issues.push(...checkScoringStrategy(draft));\n\n const blanks = isUnset(draft.blanks) ? [] : draft.blanks;\n if (Array.isArray(blanks)) {\n if (blanks.length === 0) {\n issues.push(\n issue(\n 'fib_blanks_required',\n ['blanks'],\n 'Add at least one blank, and mark where it goes in the passage with {{id}}.',\n ),\n );\n }\n const ids: string[] = [];\n for (const [index, blank] of blanks.entries()) {\n if (!isRecord(blank)) {\n continue;\n }\n const name = typeof blank.id === 'string' && blank.id !== '' ? `\"${blank.id}\"` : index + 1;\n if (isMissingId(blank.id)) {\n issues.push(\n issue('fib_blank_id_required', ['blanks', index, 'id'], `Blank ${index + 1} has no id.`),\n );\n } else if (typeof blank.id === 'string') {\n ids.push(blank.id);\n }\n\n const answers = isUnset(blank.acceptedAnswers) ? [] : blank.acceptedAnswers;\n if (Array.isArray(answers)) {\n if (answers.length === 0) {\n issues.push(\n issue(\n 'fib_accepted_answers_required',\n ['blanks', index, 'acceptedAnswers'],\n `Add an accepted answer for blank ${name}.`,\n ),\n );\n }\n for (const [position, answer] of answers.entries()) {\n // A `null` entry is `validateDraft`'s to report, as `null_not_allowed`.\n if (typeof answer === 'string' && answer.trim() === '') {\n issues.push(\n issue(\n 'fib_accepted_answer_empty',\n ['blanks', index, 'acceptedAnswers', position],\n `An accepted answer for blank ${name} is empty. Fill it in or remove it.`,\n ),\n );\n }\n }\n }\n\n if (isRecord(blank.match)) {\n issues.push(...checkMatch(blank.match, index));\n }\n }\n // An unwritten passage is already reported, and pairing blanks against it\n // would only restate that every blank is missing from it.\n if (typeof passage === 'string' && passage.trim() !== '') {\n issues.push(...checkPairing(passage, blanks, ids));\n }\n }\n\n issues.push(...checkSharedOptional(draft));\n return issues;\n}\n\n/**\n * A blank's matching tolerances, checked through `TextMatchPolicySchema` so its\n * rules live in one place, plus the one thing the schema cannot see: a locale\n * the runtime refuses. `matchText` hands a non-empty `locale` to\n * `toLocaleLowerCase`, which throws on a tag that is not a language tag, so a\n * draft holding one would be \"complete\" and still crash the moment it was\n * scored.\n */\nfunction checkMatch(match: Readonly<Record<string, unknown>>, index: number): DraftIssue[] {\n const issues: DraftIssue[] = [];\n const at = (...rest: (string | number)[]) => ['blanks', index, 'match', ...rest];\n\n const tolerance = match.levenshtein;\n if (!isUnset(tolerance) && !(isWholeNumber(tolerance) && tolerance >= 0)) {\n issues.push(\n issue(\n 'fib_levenshtein_invalid',\n at('levenshtein'),\n isTooLarge(tolerance)\n ? 'Typo tolerance is too large.'\n : 'Typo tolerance must be a whole number, 0 or more.',\n ),\n );\n }\n\n const locale = match.locale;\n if (typeof locale === 'string' && locale !== '' && !isLanguageTag(locale)) {\n issues.push(\n issue(\n 'fib_match_locale_invalid',\n at('locale'),\n `\"${locale}\" is not a language tag. Use one such as \"tr\" or \"en-US\", or leave the locale out.`,\n ),\n );\n }\n\n const parsed = TextMatchPolicySchema.safeParse(match, { reportInput: true });\n if (!parsed.success) {\n for (const schemaIssue of parsed.error.issues) {\n // `levenshtein` has its own code above, and a refused `null` is\n // `validateDraft`'s to report, as `null_not_allowed`.\n if (schemaIssue.path[0] === 'levenshtein' || refusesEmpty(match, schemaIssue)) {\n continue;\n }\n issues.push(\n issue('fib_match_invalid', at(...schemaIssue.path.map(String)), schemaIssue.message),\n );\n }\n }\n return issues;\n}\n\n/** Whether the runtime accepts `tag` as a language tag — the same test `toLocaleLowerCase` applies. */\nfunction isLanguageTag(tag: string): boolean {\n try {\n Intl.getCanonicalLocales(tag);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction checkPairing(passage: string, blanks: readonly unknown[], ids: readonly string[]) {\n const issues: DraftIssue[] = [];\n const placeholders = new Map<string, number>();\n for (const match of passage.matchAll(PLACEHOLDER_RE)) {\n const id = match[1] as string;\n placeholders.set(id, (placeholders.get(id) ?? 0) + 1);\n }\n const blankIds = new Map<string, number>();\n for (const id of ids) {\n blankIds.set(id, (blankIds.get(id) ?? 0) + 1);\n }\n\n for (const [id, count] of blankIds) {\n if (count > 1) {\n issues.push(\n issue('fib_blank_id_duplicate', ['passage'], `More than one blank has the id \"${id}\".`),\n );\n }\n }\n for (const [id, count] of placeholders) {\n if (count > 1) {\n issues.push(\n issue(\n 'fib_placeholder_duplicate',\n ['passage'],\n `{{${id}}} appears more than once in the passage. Each blank goes in one place.`,\n ),\n );\n }\n if (!blankIds.has(id)) {\n issues.push(\n issue(\n 'fib_blank_missing',\n ['passage'],\n `The passage has {{${id}}}, but there is no blank with that id.`,\n ),\n );\n }\n }\n for (const id of blankIds.keys()) {\n if (!placeholders.has(id)) {\n issues.push(\n issue(\n 'fib_placeholder_missing',\n ['passage'],\n `Blank \"${id}\" is not in the passage. Put {{${id}}} where it goes.`,\n ),\n );\n }\n }\n\n // The schema's own pairing rule, stated exactly as the schema states it. Each\n // code above is one specific way of breaking it. If it is broken in a way none\n // of them names — a blank with no usable id, for one — this says so, rather\n // than leaving the schema's message to be reported as a second failure.\n if (issues.length === 0 && !pairsOneToOne(placeholders, blanks)) {\n issues.push(\n issue(\n 'fib_blanks_mismatch',\n ['passage'],\n 'The blanks and the {{id}} placeholders in the passage do not pair up one to one.',\n ),\n );\n }\n return issues;\n}\n\n/**\n * `FillInTheBlanksDataSchema`'s pairing refinement, over a draft's raw blanks.\n * An entry that is not an object is reported on its own, and the schema never\n * reaches its refinement past one, so it takes no part in the pairing.\n */\nfunction pairsOneToOne(placeholders: ReadonlyMap<string, number>, blanks: readonly unknown[]) {\n const blankIds = blanks.filter(isRecord).map((blank) => blank.id);\n if (new Set(blankIds).size !== blankIds.length) {\n return false;\n }\n if (placeholders.size !== blankIds.length) {\n return false;\n }\n return blankIds.every((id) => typeof id === 'string' && placeholders.get(id) === 1);\n}\n","import type { ActivityTypeAuthoring } from '../registry/registry.js';\nimport type { MultipleChoiceData } from '../types/activity.js';\nimport type { DraftIssue } from '../types/authoring.js';\nimport {\n checkIdentity,\n checkScoringStrategy,\n checkSharedOptional,\n type DraftFields,\n isMissingId,\n isRecord,\n issue,\n isUnset,\n isUnwritten,\n} from './issues.js';\n\n/** Mirrors `MultipleChoiceDataSchema`: `options` is `.min(2).max(26)`. */\nconst MIN_OPTIONS = 2;\nconst MAX_OPTIONS = 26;\n\n/**\n * Draft support for `multiple-choice`.\n *\n * A new draft has two empty options and NO option marked correct. Pre-marking\n * one is the obvious convenience, and it is a trap: an author writes both\n * options, never touches the correctness control, and holds a `complete`\n * question whose answer key is whichever option happened to be marked by\n * default. Leaving it unmarked keeps the question `incomplete` until somebody\n * says which answer is right.\n *\n * `scoringStrategy` starts at `all-or-nothing`, the less generous strategy:\n * partial credit is something an author chooses to give.\n */\nexport const multipleChoiceAuthoring: ActivityTypeAuthoring<MultipleChoiceData> = {\n createDraft: ({ newId }) => ({\n schemaVersion: '1.0',\n type: 'multiple-choice',\n id: newId(),\n title: '',\n question: '',\n mode: 'single',\n scoringStrategy: 'all-or-nothing',\n options: [\n { id: newId(), text: '', isCorrect: false },\n { id: newId(), text: '', isCorrect: false },\n ],\n }),\n checkDraft: checkMultipleChoiceDraft,\n};\n\nfunction checkMultipleChoiceDraft(draft: DraftFields): DraftIssue[] {\n const issues = checkIdentity(draft, 'multiple-choice');\n if (isUnwritten(draft.question)) {\n issues.push(issue('mc_question_required', ['question'], 'Write the question.'));\n }\n if (isUnwritten(draft.mode)) {\n issues.push(\n issue('mc_mode_required', ['mode'], 'Choose whether learners select one option or several.'),\n );\n }\n issues.push(...checkScoringStrategy(draft));\n\n const options = isUnset(draft.options) ? [] : draft.options;\n if (Array.isArray(options)) {\n // Every option-set rule is reported at `options`, where the schema reports\n // its refinements, so none of them is repeated as a second failure.\n if (options.length < MIN_OPTIONS) {\n issues.push(issue('mc_options_too_few', ['options'], 'Add at least two options.'));\n }\n if (options.length > MAX_OPTIONS) {\n issues.push(\n issue('mc_options_too_many', ['options'], `Use no more than ${MAX_OPTIONS} options.`),\n );\n }\n const seen = new Set<string>();\n const repeated = new Set<string>();\n let correct = 0;\n for (const [index, option] of options.entries()) {\n if (!isRecord(option)) {\n continue;\n }\n const ordinal = index + 1;\n if (isMissingId(option.id)) {\n issues.push(\n issue('mc_option_id_required', ['options', index, 'id'], `Option ${ordinal} has no id.`),\n );\n } else if (typeof option.id === 'string') {\n if (seen.has(option.id)) {\n repeated.add(option.id);\n }\n seen.add(option.id);\n }\n if (isUnwritten(option.text)) {\n issues.push(\n issue(\n 'mc_option_text_required',\n ['options', index, 'text'],\n `Write the text of option ${ordinal}.`,\n ),\n );\n }\n // The schema requires the flag on every option. An editor that has not\n // asked yet — or one that stores only the options marked correct — leaves\n // it unset, which is a decision still to make, not a wrong one.\n if (isUnset(option.isCorrect)) {\n issues.push(\n issue(\n 'mc_option_correctness_required',\n ['options', index, 'isCorrect'],\n `Say whether option ${ordinal} is correct.`,\n ),\n );\n }\n if (option.isCorrect === true) {\n correct += 1;\n }\n }\n for (const id of repeated) {\n issues.push(\n issue('mc_option_id_duplicate', ['options'], `More than one option has the id \"${id}\".`),\n );\n }\n if (correct === 0) {\n issues.push(\n issue(\n 'mc_correct_option_required',\n ['options'],\n draft.mode === 'multi'\n ? 'Mark at least one option as correct.'\n : 'Mark the correct option.',\n ),\n );\n } else if (draft.mode === 'single' && correct > 1) {\n issues.push(\n issue(\n 'mc_single_mode_one_correct',\n ['options'],\n 'Only one option can be marked correct when learners select one option.',\n ),\n );\n }\n }\n\n issues.push(...checkSharedOptional(draft));\n return issues;\n}\n","import type { ActivityTypeAuthoring } from '../registry/registry.js';\nimport type { WrittenResponseData } from '../types/activity.js';\nimport type { DraftIssue } from '../types/authoring.js';\nimport {\n checkIdentity,\n checkSharedOptional,\n type DraftFields,\n isRecord,\n issue,\n isTooLarge,\n isUnset,\n isUnwritten,\n isWholeNumber,\n} from './issues.js';\n\n/**\n * Draft support for `written-response`.\n *\n * A new draft has no prompt, no rubric, `minWords: 0` and `maxWords: 0`. The\n * SDK picks no word limits and no rubric criteria: those are teaching decisions.\n *\n * - `minWords: 0` is a real setting — no lower limit, which `<WrittenResponse>`\n * renders as \"up to N words\" — so it is never reported.\n * - `maxWords: 0` is not. The schema requires at least 1, and 0 is what a\n * cleared number field produces, so it reads as \"not set yet\" (`incomplete`)\n * rather than as a wrong value.\n *\n * Stricter than the schema in four places:\n *\n * - A blank `prompt` is `incomplete` even when `promptHtml` is set. The plain\n * prompt is what `<WrittenResponse>` renders when no sanitiser is supplied, so\n * a rich-text-only prompt shows the learner nothing there.\n * - A rubric criterion whose name is only whitespace is `incomplete`.\n * - A rubric whose weights are all 0 is `incomplete`: `gradeFromRubric` cannot\n * compute a weighted total from them.\n * - A rubric whose weights add up to more than a number can hold is `invalid`,\n * for the same reason.\n */\nexport const writtenResponseAuthoring: ActivityTypeAuthoring<WrittenResponseData> = {\n createDraft: ({ newId }) => ({\n schemaVersion: '1.0',\n type: 'written-response',\n id: newId(),\n title: '',\n prompt: '',\n minWords: 0,\n maxWords: 0,\n }),\n checkDraft: checkWrittenResponseDraft,\n};\n\nfunction checkWrittenResponseDraft(draft: DraftFields): DraftIssue[] {\n const issues = checkIdentity(draft, 'written-response');\n if (isUnwritten(draft.prompt)) {\n issues.push(\n issue(\n 'wr_prompt_required',\n ['prompt'],\n isUnwritten(draft.promptHtml)\n ? 'Write the prompt.'\n : 'Write the prompt as plain text too. The rich-text prompt is shown only where a sanitiser is supplied; the plain text is shown everywhere else.',\n ),\n );\n }\n\n const min = draft.minWords;\n const max = draft.maxWords;\n if (isUnset(min)) {\n issues.push(\n issue(\n 'wr_min_words_required',\n ['minWords'],\n 'Set the minimum number of words. Use 0 for no minimum.',\n ),\n );\n } else if (!(isWholeNumber(min) && min >= 0)) {\n issues.push(\n issue(\n 'wr_min_words_invalid',\n ['minWords'],\n isTooLarge(min)\n ? 'The minimum word count is too large.'\n : 'The minimum word count must be a whole number, 0 or more.',\n ),\n );\n }\n if (isUnset(max) || max === 0) {\n issues.push(issue('wr_max_words_required', ['maxWords'], 'Set the maximum number of words.'));\n } else if (!(isWholeNumber(max) && max >= 1)) {\n issues.push(\n issue(\n 'wr_max_words_invalid',\n ['maxWords'],\n isTooLarge(max)\n ? 'The maximum word count is too large.'\n : 'The maximum word count must be a whole number, 1 or more.',\n ),\n );\n } else if (typeof min === 'number' && max < min) {\n // Reported at `maxWords`, where the schema reports the same rule.\n issues.push(\n issue(\n 'wr_word_bounds_order',\n ['maxWords'],\n 'The maximum word count cannot be lower than the minimum.',\n ),\n );\n }\n\n const rubric = draft.rubric;\n if (isRecord(rubric)) {\n const criteria = isUnset(rubric.criteria) ? [] : rubric.criteria;\n if (Array.isArray(criteria)) {\n issues.push(...checkCriteria(criteria));\n }\n }\n\n issues.push(...checkSharedOptional(draft));\n return issues;\n}\n\nfunction checkCriteria(criteria: readonly unknown[]): DraftIssue[] {\n const issues: DraftIssue[] = [];\n if (criteria.length === 0) {\n issues.push(\n issue(\n 'wr_rubric_criteria_required',\n ['rubric', 'criteria'],\n 'Add at least one rubric criterion, or remove the rubric.',\n ),\n );\n return issues;\n }\n let totalWeight = 0;\n let everyWeightUsable = true;\n for (const [index, criterion] of criteria.entries()) {\n if (!isRecord(criterion)) {\n everyWeightUsable = false;\n continue;\n }\n const ordinal = index + 1;\n const path = ['rubric', 'criteria', index];\n if (isUnwritten(criterion.name)) {\n issues.push(\n issue('wr_criterion_name_required', [...path, 'name'], `Name rubric criterion ${ordinal}.`),\n );\n }\n const weight = criterion.weight;\n if (isUnset(weight)) {\n everyWeightUsable = false;\n issues.push(\n issue(\n 'wr_criterion_weight_required',\n [...path, 'weight'],\n `Give rubric criterion ${ordinal} a weight.`,\n ),\n );\n } else if (!(typeof weight === 'number' && Number.isFinite(weight) && weight >= 0)) {\n everyWeightUsable = false;\n issues.push(\n issue(\n 'wr_criterion_weight_invalid',\n [...path, 'weight'],\n 'A rubric weight must be a number, 0 or more.',\n ),\n );\n } else {\n totalWeight += weight;\n }\n }\n if (everyWeightUsable && totalWeight === 0) {\n issues.push(\n issue(\n 'wr_rubric_weights_zero',\n ['rubric', 'criteria'],\n 'Give at least one rubric criterion a weight above 0. With every weight at 0, no weighted total can be computed.',\n ),\n );\n } else if (totalWeight === Number.POSITIVE_INFINITY) {\n // Each weight is finite, and their sum still overflows: `gradeFromRubric`\n // would divide by Infinity and produce no grade. No weight is negative, so\n // the sum stays overflowed whatever a weight not yet set turns out to be.\n issues.push(\n issue(\n 'wr_rubric_weights_too_large',\n ['rubric', 'criteria'],\n 'The rubric weights add up to more than can be calculated with. Use smaller weights.',\n ),\n );\n }\n return issues;\n}\n","/**\n * All-or-nothing scoring: full credit only when every item is correct.\n *\n * @param correctItems - per-item correctness flags for the relevant items\n * @returns `1` if every item is correct (or the list is empty), otherwise `0`\n */\nexport function allOrNothingStrategy(correctItems: boolean[]): number {\n return correctItems.every((isCorrect) => isCorrect) ? 1 : 0;\n}\n","/**\n * Partial-credit scoring for Multiple Choice — balanced/symmetric scheme.\n *\n * Reward and penalty are each normalised by their own pool: the fraction of\n * correct options found, minus the fraction of distractors wrongly chosen.\n * This is fairer than normalising the penalty by the correct-option count —\n * under that older form a single wrong pick could zero an otherwise-correct\n * response when there was only one correct answer.\n *\n * Result is always in [0, 1]: `reward ∈ [0,1]` and `penalty ∈ [0,1]`, so\n * `reward - penalty ∈ [-1,1]` and `max(0, …)` floors it at 0. Selecting every\n * option yields `1 - 1 = 0`; selecting exactly the correct set yields `1`.\n *\n * @param correctSelected - number of selected options that are correct\n * @param incorrectSelected - number of selected options that are incorrect\n * @param totalCorrect - total correct options; the `MultipleChoiceDataSchema`\n * \"≥1 correct\" guard guarantees this is ≥ 1, so the reward term cannot\n * divide by zero for schema-validated data\n * @param totalIncorrect - total incorrect options (distractors); when `0`\n * (every option is correct) the penalty term is defined as `0`\n */\nexport function partialStrategy(\n correctSelected: number,\n incorrectSelected: number,\n totalCorrect: number,\n totalIncorrect: number,\n): number {\n const reward = correctSelected / totalCorrect;\n const penalty = totalIncorrect === 0 ? 0 : incorrectSelected / totalIncorrect;\n return Math.max(0, reward - penalty);\n}\n\n/**\n * Partial-credit scoring for Fill-in-the-Blanks: fraction of blanks answered\n * correctly. Each blank is independently right or wrong, so a plain proportion\n * is already fair — no penalty term applies.\n *\n * @param correctBlanks - number of blanks answered correctly\n * @param totalBlanks - total number of blanks; the `FillInTheBlanksDataSchema`\n * `blanks.min(1)` constraint guarantees this is ≥ 1, so division by zero\n * cannot occur for schema-validated data\n */\nexport function partialBlankStrategy(correctBlanks: number, totalBlanks: number): number {\n return correctBlanks / totalBlanks;\n}\n","import type {\n BlankConfig,\n FillInTheBlanksData,\n FillInTheBlanksLearnerResponse,\n ScoringDetail,\n} from '../../types/activity.js';\nimport { allOrNothingStrategy } from '../strategies/all-or-nothing.js';\nimport { partialBlankStrategy } from '../strategies/partial.js';\nimport { matchText, type TextMatchPolicy } from '../text-match.js';\nimport type { PartialScoringResult } from './multiple-choice.js';\n\n/**\n * Resolves the effective match policy for a blank. The legacy\n * `caseSensitive` / `trimWhitespace` flags map onto the baseline policy\n * fields; an explicit `blank.match` policy takes precedence field-by-field.\n * With neither present, the result is the v1 semantics exactly.\n */\nfunction policyFor(blank: BlankConfig): TextMatchPolicy {\n return {\n ...(blank.caseSensitive !== undefined ? { caseSensitive: blank.caseSensitive } : {}),\n ...(blank.trimWhitespace !== undefined ? { trim: blank.trimWhitespace } : {}),\n ...blank.match,\n };\n}\n\n/**\n * Scores a Fill-in-the-Blanks response. Each blank is evaluated independently\n * via {@link matchText} under the blank's resolved policy; a missing answer\n * key is treated as empty input and scored incorrect.\n */\nexport function scoreFillInTheBlanks(\n data: FillInTheBlanksData,\n response: FillInTheBlanksLearnerResponse,\n): PartialScoringResult {\n const details: ScoringDetail[] = [];\n const perBlankCorrect: boolean[] = [];\n\n for (const blank of data.blanks) {\n const rawInput = response.answers[blank.id];\n const input = typeof rawInput === 'string' ? rawInput : '';\n const matched = matchText(input, blank.acceptedAnswers, policyFor(blank)).matched;\n\n perBlankCorrect.push(matched);\n details.push({\n itemId: blank.id,\n correct: matched,\n outcome: matched ? 'correct' : 'incorrect',\n learnerResponse: [input],\n correctResponse: [...blank.acceptedAnswers],\n weight: 1,\n });\n }\n\n const correctBlanks = perBlankCorrect.filter(Boolean).length;\n const scoreValue =\n data.scoringStrategy === 'all-or-nothing'\n ? allOrNothingStrategy(perBlankCorrect)\n : partialBlankStrategy(correctBlanks, data.blanks.length);\n\n return { score: scoreValue, maxScore: 1, feedback: null, details };\n}\n","import type { PartialScoringResult } from '../../registry/registry.js';\nimport type {\n MultipleChoiceData,\n MultipleChoiceLearnerResponse,\n ScoringDetail,\n} from '../../types/activity.js';\nimport { partialStrategy } from '../strategies/partial.js';\n\nexport type { PartialScoringResult } from '../../registry/registry.js';\n\n/**\n * Scores a Multiple Choice response. Pure; trusts its typed inputs (validation\n * is the component boundary's job). Options are looked up by id; an unknown\n * selected id is treated as an incorrect selection.\n */\nexport function scoreMultipleChoice(\n data: MultipleChoiceData,\n response: MultipleChoiceLearnerResponse,\n): PartialScoringResult {\n const optionById = new Map(data.options.map((option) => [option.id, option]));\n const selected = new Set(response.selectedOptionIds);\n\n const totalCorrect = data.options.filter((option) => option.isCorrect).length;\n const totalIncorrect = data.options.length - totalCorrect;\n\n let scoreValue: number;\n\n if (data.scoringStrategy === 'all-or-nothing') {\n if (data.mode === 'single') {\n scoreValue =\n response.selectedOptionIds.length === 1 &&\n optionById.get(response.selectedOptionIds[0])?.isCorrect === true\n ? 1\n : 0;\n } else {\n const correctIds = data.options.filter((o) => o.isCorrect).map((o) => o.id);\n const allCorrectSelected = correctIds.every((id) => selected.has(id));\n scoreValue = selected.size === correctIds.length && allCorrectSelected ? 1 : 0;\n }\n } else {\n let correctSelected = 0;\n let incorrectSelected = 0;\n for (const id of selected) {\n const option = optionById.get(id);\n if (option?.isCorrect) {\n correctSelected += 1;\n } else {\n incorrectSelected += 1;\n }\n }\n scoreValue = partialStrategy(correctSelected, incorrectSelected, totalCorrect, totalIncorrect);\n }\n\n const details: ScoringDetail[] = data.options.map((option) => {\n const wasSelected = selected.has(option.id);\n const outcome = wasSelected\n ? option.isCorrect\n ? 'correct'\n : 'incorrect'\n : option.isCorrect\n ? 'incorrect-omission'\n : 'correct-omission';\n return {\n itemId: option.id,\n correct: wasSelected === option.isCorrect,\n outcome,\n learnerResponse: [wasSelected ? 'selected' : 'not-selected'],\n correctResponse: [option.isCorrect ? 'selected' : 'not-selected'],\n weight: 1,\n };\n });\n\n return { score: scoreValue, maxScore: 1, feedback: null, details };\n}\n","import type { z } from 'zod/v4';\nimport { fillInTheBlanksAuthoring } from '../authoring/fill-in-the-blanks.js';\nimport { multipleChoiceAuthoring } from '../authoring/multiple-choice.js';\nimport { writtenResponseAuthoring } from '../authoring/written-response.js';\nimport { countWords } from '../count-words.js';\nimport { FillInTheBlanksDataSchema } from '../schemas/fill-in-the-blanks.js';\nimport { MultipleChoiceDataSchema } from '../schemas/multiple-choice.js';\nimport {\n RedactedFillInTheBlanksDataSchema,\n RedactedMultipleChoiceDataSchema,\n RedactedWrittenResponseDataSchema,\n} from '../schemas/redacted.js';\nimport { WrittenResponseDataSchema } from '../schemas/written-response.js';\nimport { scoreFillInTheBlanks } from '../scoring/activity-scorers/fill-in-the-blanks.js';\nimport { scoreMultipleChoice } from '../scoring/activity-scorers/multiple-choice.js';\nimport type {\n FillInTheBlanksData,\n FillInTheBlanksLearnerResponse,\n MultipleChoiceData,\n MultipleChoiceLearnerResponse,\n WrittenResponseData,\n WrittenResponseLearnerResponse,\n} from '../types/activity.js';\nimport { defineActivityType, type FieldPolicy, registerActivityType } from './registry.js';\n\n/**\n * Field-sensitivity policies for the built-in types (R7). Fail-closed:\n * anything not listed here is dropped by `redact()`. `scoringStrategy` is\n * answer-key everywhere — MC `partial` penalises wrong selections while\n * `all-or-nothing` does not, so the strategy reveals whether guessing is\n * free. Authored feedback is answer-key (it may quote or hint the answer).\n * Rubrics are PUBLIC: a rubric tells the learner what they are assessed on,\n * and a deployment that wants it hidden tightens it per call — see the\n * `rubric` entry in the written-response policy below.\n */\n/**\n * `media` classified field by field, not as one opaque leaf.\n *\n * A scalar `Sensitivity` classifies the WHOLE field, so `media: 'public'`\n * returned the author's object by reference without recursing — and an\n * unclassified key nested under it (`media.secretAnswerHint`) survived\n * `redact()` AND passed `assertRedacted()`. The fail-closed contract the SDK\n * documents (\"a field the policy does not classify is removed\") stopped at the\n * media boundary. It no longer does.\n *\n * Everything here is public by necessity: the client is the thing that renders\n * and enforces the policy, and \"1 play remaining\" is text the learner has to\n * read. None of it is an answer key — a listening paper's answer key is\n * `stimulus.transcript`, which stays `author-only`.\n */\nexport const MEDIA_FIELD_POLICY: FieldPolicy = {\n type: 'public',\n url: 'public',\n alt: 'public',\n captionsUrl: 'public',\n playback: {\n controls: 'public',\n maxPlays: 'public',\n seek: 'public',\n rate: 'public',\n nativeControlHints: 'public',\n },\n};\n\nconst SHARED_PUBLIC_FIELDS: FieldPolicy = {\n schemaVersion: 'public',\n type: 'public',\n id: 'public',\n // Assembly metadata, not content: it names the slot this item occupies in a\n // paper. It has to survive redaction, or the exam client derives positional\n // slot ids while the server's stored plan holds keyed ones, and the\n // responses cannot be matched back to the attempt.\n slotKey: 'public',\n title: 'public',\n media: MEDIA_FIELD_POLICY,\n passThreshold: 'public',\n locale: 'public',\n learningObjectives: 'public',\n difficultyLevel: 'public',\n};\n\n/**\n * Activity-level feedback, classified field by field.\n *\n * The third object leaf to need this, after `media` and `rubric`, and the same\n * defect each time: a scalar classification assigns the author's object by\n * reference without recursing, so under `reveal: 'after-submit'` an\n * unclassified key nested inside it — a grader note, an internal cost — was\n * forwarded to the learner along with the answer key, and `redact()` handed\n * back an alias of the caller's object. `FeedbackSchema` is loose, so anything\n * can be parked there.\n *\n * Both fields stay `answer-key`: activity feedback IS the answer key's\n * commentary, so `reveal: 'none'` still drops the whole object.\n */\nexport const FEEDBACK_FIELD_POLICY: FieldPolicy = {\n correct: 'answer-key',\n incorrect: 'answer-key',\n};\n\n/**\n * A blank's matching tolerances, classified key by key.\n *\n * Same reasoning as {@link FEEDBACK_FIELD_POLICY}: `TextMatchPolicy` is a\n * documented set of knobs, and a consumer's private tuning parked beside them\n * is not part of what an after-submit reveal promises to show.\n */\nexport const TEXT_MATCH_FIELD_POLICY: FieldPolicy = {\n caseSensitive: 'answer-key',\n trim: 'answer-key',\n normalize: 'answer-key',\n foldDiacritics: 'answer-key',\n collapseInnerWhitespace: 'answer-key',\n ignorePunctuation: 'answer-key',\n levenshtein: 'answer-key',\n locale: 'answer-key',\n};\n\nconst MULTIPLE_CHOICE_FIELD_POLICY: FieldPolicy = {\n ...SHARED_PUBLIC_FIELDS,\n question: 'public',\n questionHtml: 'public',\n mode: 'public',\n shuffle: 'public',\n scoringStrategy: 'answer-key',\n feedback: FEEDBACK_FIELD_POLICY,\n options: {\n id: 'public',\n text: 'public',\n isCorrect: 'answer-key',\n feedback: 'answer-key',\n },\n};\n\nconst FILL_IN_THE_BLANKS_FIELD_POLICY: FieldPolicy = {\n ...SHARED_PUBLIC_FIELDS,\n passage: 'public',\n passageHtml: 'public',\n scoringStrategy: 'answer-key',\n feedback: FEEDBACK_FIELD_POLICY,\n blanks: {\n id: 'public',\n hint: 'public',\n acceptedAnswers: 'answer-key',\n caseSensitive: 'answer-key',\n trimWhitespace: 'answer-key',\n match: TEXT_MATCH_FIELD_POLICY,\n feedback: 'answer-key',\n },\n};\n\n/**\n * The rubric classified field by field, not as one opaque leaf.\n *\n * A scalar `Sensitivity` classifies the WHOLE field, so `rubric: 'public'`\n * returned the author's object by reference without recursing — and an\n * unclassified key nested under it survived `redact()` AND passed\n * `assertRedacted()`. A grader's `modelAnswer` or `aiModel` stashed on the\n * rubric went straight to the exam client. Same defect as the one `media` had,\n * one field along: \"the rubric is public\" has to mean its documented fields\n * are public, not that anything anyone parks under it is.\n */\nexport const RUBRIC_FIELD_POLICY: FieldPolicy = {\n label: 'public',\n // Applies to every element of the array.\n criteria: {\n name: 'public',\n description: 'public',\n weight: 'public',\n },\n};\n\nconst WRITTEN_RESPONSE_FIELD_POLICY: FieldPolicy = {\n ...SHARED_PUBLIC_FIELDS,\n prompt: 'public',\n promptHtml: 'public',\n minWords: 'public',\n maxWords: 'public',\n languageTarget: 'public',\n feedback: FEEDBACK_FIELD_POLICY,\n // A rubric is a LEARNER affordance, not a grader secret: it tells the\n // learner what they are being graded on, which is pedagogically the point\n // of publishing one. (Classifying it author-only broke real deployments\n // that render a rubric panel during the attempt.) A deployment that wants\n // it hidden can tighten this per call via `redact(data, { policy })`.\n // Classified field by field so that stays true of the rubric's DOCUMENTED\n // fields only — see {@link RUBRIC_FIELD_POLICY}.\n rubric: RUBRIC_FIELD_POLICY,\n};\n\n/** Built-in Multiple Choice descriptor. */\nexport const multipleChoiceType = defineActivityType<\n MultipleChoiceData,\n MultipleChoiceLearnerResponse\n>({\n type: 'multiple-choice',\n // zod4 optional outputs are `T | undefined`; the hand-written wire types use\n // exact optionals. Structurally identical at runtime — cast is type-level only.\n schema: MultipleChoiceDataSchema as unknown as z.ZodType<MultipleChoiceData>,\n scoring: { kind: 'sync', score: scoreMultipleChoice },\n isAnswered: (response) => (response?.selectedOptionIds.length ?? 0) > 0,\n fieldPolicy: MULTIPLE_CHOICE_FIELD_POLICY,\n redactedSchema: RedactedMultipleChoiceDataSchema,\n interop: {\n xapiActivityTypeIri: 'http://adlnet.gov/expapi/activities/cmi.interaction',\n xapiInteractionType: 'choice',\n correctResponsesPattern: (data) => [\n data.options\n .filter((option) => option.isCorrect)\n .map((option) => option.id)\n .join('[,]'),\n ],\n },\n interactions: ['option-selected', 'option-deselected', 'submitted'],\n authoring: multipleChoiceAuthoring,\n});\n\n/** Built-in Fill-in-the-Blanks descriptor. */\nexport const fillInTheBlanksType = defineActivityType<\n FillInTheBlanksData,\n FillInTheBlanksLearnerResponse\n>({\n type: 'fill-in-the-blanks',\n schema: FillInTheBlanksDataSchema as unknown as z.ZodType<FillInTheBlanksData>,\n scoring: { kind: 'sync', score: scoreFillInTheBlanks },\n isAnswered: (response) =>\n Object.values(response?.answers ?? {}).some((answer) => answer.trim().length > 0),\n fieldPolicy: FILL_IN_THE_BLANKS_FIELD_POLICY,\n redactedSchema: RedactedFillInTheBlanksDataSchema,\n interop: {\n xapiActivityTypeIri: 'http://adlnet.gov/expapi/activities/cmi.interaction',\n xapiInteractionType: 'fill-in',\n // xAPI fill-in pattern: blank answers joined with \"[,]\". Only the first\n // accepted answer per blank is emitted (full alternates would explode\n // combinatorially); the complete key lives in the activity data.\n correctResponsesPattern: (data) => [\n data.blanks.map((blank) => blank.acceptedAnswers[0] ?? '').join('[,]'),\n ],\n },\n interactions: ['blank-filled', 'hint-requested', 'submitted'],\n authoring: fillInTheBlanksAuthoring,\n});\n\n/**\n * Built-in Written Response descriptor. Grading is DEFERRED: submissions are\n * graded asynchronously (AI or human) by the consumer; the synchronous\n * outcome reports only word-count facts. `wordCount` is recomputed from the\n * submitted text with the canonical `countWords()` — the client-supplied\n * count is informational, never trusted.\n */\nexport const writtenResponseType = defineActivityType<\n WrittenResponseData,\n WrittenResponseLearnerResponse\n>({\n type: 'written-response',\n schema: WrittenResponseDataSchema as unknown as z.ZodType<WrittenResponseData>,\n scoring: {\n kind: 'deferred',\n reason: 'requires_async_grading',\n partial: (data, response) => {\n const wordCount = countWords(response?.text ?? '');\n return {\n withinWordBounds:\n response !== undefined && wordCount >= data.minWords && wordCount <= data.maxWords,\n wordCount,\n };\n },\n },\n isAnswered: (response) => (response?.text.trim().length ?? 0) > 0,\n fieldPolicy: WRITTEN_RESPONSE_FIELD_POLICY,\n redactedSchema: RedactedWrittenResponseDataSchema,\n interop: {\n xapiActivityTypeIri: 'http://adlnet.gov/expapi/activities/cmi.interaction',\n xapiInteractionType: 'long-fill-in',\n correctResponsesPattern: () => [],\n },\n interactions: ['text-changed', 'submitted'],\n authoring: writtenResponseAuthoring,\n});\n\nregisterActivityType(multipleChoiceType);\nregisterActivityType(fillInTheBlanksType);\nregisterActivityType(writtenResponseType);\n"],"mappings":";AAGO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACkB,cACA,QAChB;AACA,UAAM,mCAAmC,YAAY,GAAG;AAHxC;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAAA,EACA;AAKpB;AAGO,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YAA4B,cAAsB;AAChD,UAAM,kBAAkB,YAAY,qBAAqB;AAD/B;AAE1B,SAAK,OAAO;AAAA,EACd;AAAA,EAH4B;AAI9B;AAUO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAA4B,cAAsB;AAChD;AAAA,MACE,sBAAsB,YAAY;AAAA,IAEpC;AAJ0B;AAK1B,SAAK,OAAO;AAAA,EACd;AAAA,EAN4B;AAO9B;AASO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAA4B,cAAsB;AAChD;AAAA,MACE,kBAAkB,YAAY;AAAA,IAEhC;AAJ0B;AAK1B,SAAK,OAAO;AAAA,EACd;AAAA,EAN4B;AAO9B;;;ACtDA,SAAS,SAAS;AAOX,IAAM,iBAAiB,EAAE,YAAY;AAAA,EAC1C,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACpC,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AACxC,CAAC;;;ACVD,SAAS,KAAAA,UAAS;AA0BX,IAA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