@intellectif/lk-core 0.11.0 → 0.13.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.
- package/CHANGELOG.md +38 -0
- package/README.md +2 -1
- package/dist/{activity-B2QxK15j.d.cts → activity-DfAmJ1sl.d.cts} +134 -7
- package/dist/{activity-B2QxK15j.d.ts → activity-DfAmJ1sl.d.ts} +134 -7
- package/dist/{chunk-3FEAEO3D.cjs → chunk-DQKJUMUW.cjs} +38 -15
- package/dist/chunk-DQKJUMUW.cjs.map +1 -0
- package/dist/{chunk-ZTY4UIUD.js → chunk-FGN4LLSP.js} +50 -6
- package/dist/chunk-FGN4LLSP.js.map +1 -0
- package/dist/{chunk-VTTRXGDD.cjs → chunk-FT7SAC3X.cjs} +4 -4
- package/dist/{chunk-VTTRXGDD.cjs.map → chunk-FT7SAC3X.cjs.map} +1 -1
- package/dist/{chunk-IXXMYJI7.js → chunk-PYP3HCRQ.js} +2 -2
- package/dist/{chunk-VBM5H6P5.cjs → chunk-UHQVIC3P.cjs} +58 -14
- package/dist/chunk-UHQVIC3P.cjs.map +1 -0
- package/dist/{chunk-FIS5KBCE.js → chunk-XKKKWKRH.js} +1973 -179
- package/dist/chunk-XKKKWKRH.js.map +1 -0
- package/dist/{chunk-7ODQRNR4.cjs → chunk-XONKWL6D.cjs} +1812 -18
- package/dist/chunk-XONKWL6D.cjs.map +1 -0
- package/dist/{chunk-XGCTAQSS.js → chunk-Y36S3X3L.js} +26 -3
- package/dist/chunk-Y36S3X3L.js.map +1 -0
- package/dist/{index-CRKtWP5G.d.ts → index-Bz9wUigA.d.cts} +181 -4
- package/dist/{index-B_scInLM.d.cts → index-CJbbVE9o.d.ts} +181 -4
- package/dist/index.cjs +349 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -6
- package/dist/index.d.ts +48 -6
- package/dist/index.js +322 -11
- package/dist/index.js.map +1 -1
- package/dist/schemas.cjs +17 -3
- package/dist/schemas.cjs.map +1 -1
- package/dist/schemas.d.cts +2 -2
- package/dist/schemas.d.ts +2 -2
- package/dist/schemas.js +16 -2
- package/dist/scoring.cjs +19 -3
- package/dist/scoring.cjs.map +1 -1
- package/dist/scoring.d.cts +150 -5
- package/dist/scoring.d.ts +150 -5
- package/dist/scoring.js +18 -2
- package/dist/xapi.cjs +3 -3
- package/dist/xapi.d.cts +1 -1
- package/dist/xapi.d.ts +1 -1
- package/dist/xapi.js +2 -2
- package/package.json +1 -1
- package/vectors/README.md +9 -1
- package/vectors/scoring.json +12023 -1
- package/dist/chunk-3FEAEO3D.cjs.map +0 -1
- package/dist/chunk-7ODQRNR4.cjs.map +0 -1
- package/dist/chunk-FIS5KBCE.js.map +0 -1
- package/dist/chunk-VBM5H6P5.cjs.map +0 -1
- package/dist/chunk-XGCTAQSS.js.map +0 -1
- package/dist/chunk-ZTY4UIUD.js.map +0 -1
- /package/dist/{chunk-IXXMYJI7.js.map → chunk-PYP3HCRQ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/chunk-DQKJUMUW.cjs","../src/schemas/item-group.ts","../src/schemas/json-schema.ts","../src/schemas/index.ts"],"names":["z"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACdA,4BAAkB;AAiBlB,IAAM,cAAA,EAAgB,KAAA,CACnB,MAAA,CAAO,CAAA,CACP,GAAA,CAAI,CAAC,CAAA,CACL,MAAA,CAAO,CAAC,GAAA,EAAA,GAAQ,CAAC,GAAA,CAAI,QAAA,CAAS,GAAG,CAAA,EAAG;AAAA,EACnC,KAAA,EACE;AACJ,CAAC,CAAA;AAEH,SAAS,OAAA,CAAQ,QAAA,EAAkD;AACjE,EAAA,OAAO,OAAO,QAAA,CAAS,KAAA,IAAS,SAAA,GAAY,QAAA,CAAS,IAAA,CAAK,IAA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;AAIzE;AFsFA;AACA;AGtFO,SAAS,gBAAA,CACd,IAAA,EACA,IAAA,EACsC;AACtC,EAAA,MAAM,WAAA,EAAa,yDAAA,IAA8B,CAAA;AACjD,EAAA,GAAA,CAAI,WAAA,IAAe,KAAA,CAAA,EAAW;AAC5B,IAAA,MAAM,IAAI,+CAAA,CAAyB,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,EACjD;AAEA,EAAA,MAAM,OAAA,EAAS,UAAA,CAAW,MAAA,CAAO,SAAA,CAAU,IAAI,CAAA;AAE/C,EAAA,GAAA,CAAI,MAAA,CAAO,OAAA,EAAS;AAClB,IAAA,OAAO,EAAE,OAAA,EAAS,IAAA,EAAM,IAAA,EAAM,MAAA,CAAO,KAA2B,CAAA;AAAA,EAClE;AAEA,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,MAAA,EAAQ,MAAA,CAAO,KAAA,CAAM,MAAA,CAAO,GAAA,CAAI,CAAC,KAAA,EAAA,GAAA,CAAW;AAAA,MAC1C,IAAA,EAAM,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,MAAM,CAAA;AAAA,MAC3B,OAAA,EAAS,KAAA,CAAM,OAAA;AAAA,MACf,IAAA,EAAM,KAAA,CAAM;AAAA,IACd,CAAA,CAAE;AAAA,EACJ,CAAA;AACF;AHkFA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,+sBAAC","file":"/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/chunk-DQKJUMUW.cjs","sourcesContent":[null,"import { z } from 'zod/v4';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ActivityData, ValidationError, ValidationResult } from '../types/activity.js';\nimport type { ItemGroup, StimulusKind } from '../types/item-group.js';\nimport { GROUP_CAPTIONS_REVEAL_DICTATION, groupCaptionsRevealDictation } from './dictation.js';\nimport { MediaSchema, RedactedMediaSchema } from './media.js';\n\n/**\n * An authored slot key.\n *\n * A `.` is rejected here, not at render time: `flattenSequence` uses the first\n * `.` to separate a group from its item, so a key containing one would produce\n * an ambiguous slot id. `keyOf` already threw on it — this moves the rejection\n * to `validateItemGroup`, where an author finds it, instead of leaving it to\n * surface when a learner opens the paper. Content that would newly fail\n * validation already threw at flatten time, so it can never have been sat.\n */\nconst SlotKeySchema = z\n .string()\n .min(1)\n .refine((key) => !key.includes('.'), {\n error:\n 'slotKey must not contain \".\" — that character separates a group from its item in a slot id, so a key containing one would make the slot ambiguous.',\n });\n\nfunction hasBody(stimulus: { body?: string | undefined }): boolean {\n return typeof stimulus.body === 'string' && stimulus.body.trim().length > 0;\n}\n\n/** Which media types can carry a stimulus of each kind. `text`/`mixed` accept any. */\nfunction mediaFits(kind: StimulusKind, mediaType: string | undefined): boolean {\n switch (kind) {\n case 'audio':\n return mediaType === 'audio';\n case 'video':\n return mediaType === 'video' || mediaType === 'embed';\n case 'image':\n return mediaType === 'image';\n default:\n return true;\n }\n}\n\n/**\n * Zod schema for a {@link Stimulus}. Loose: unknown keys preserved.\n *\n * The semantic guards exist because a stimulus that does not carry what its\n * `kind` promises is an authoring error that must not reach an exam: an\n * \"audio\" stimulus with no recording renders as a blank panel above six\n * listening questions. Unrepresentable in JSON Schema; dropped from\n * `stimulusJsonSchema` by design.\n */\nexport const StimulusSchema = z\n .looseObject({\n id: z.string().min(1),\n kind: z.enum(['text', 'audio', 'video', 'image', 'mixed']),\n title: z.string().optional(),\n body: z.string().optional(),\n bodyHtml: z.string().optional(),\n media: MediaSchema.optional(),\n transcript: z.string().optional(),\n locale: z.string().optional(),\n attribution: z.string().optional(),\n })\n .refine((stimulus) => stimulus.bodyHtml === undefined || hasBody(stimulus), {\n error:\n 'bodyHtml requires a plain-text body: it is the accessible fallback rendered when no sanitiser is supplied.',\n path: ['body'],\n })\n .refine(\n (stimulus) => (stimulus.kind !== 'text' && stimulus.kind !== 'mixed') || hasBody(stimulus),\n {\n error: 'A text or mixed stimulus needs a non-empty body.',\n path: ['body'],\n },\n )\n .refine((stimulus) => stimulus.kind === 'text' || stimulus.media !== undefined, {\n error: 'An audio, video, image or mixed stimulus needs media.',\n path: ['media'],\n })\n .refine(\n (stimulus) => stimulus.media === undefined || mediaFits(stimulus.kind, stimulus.media.type),\n {\n error:\n 'media.type does not fit the stimulus kind: audio needs audio; video needs video or embed; image needs image.',\n path: ['media', 'type'],\n },\n );\n\n/**\n * The structural minimum of an item as seen by the CONTAINER schema. Each\n * item's own contract is checked against its registered schema by\n * {@link validateItemGroup} — a zod schema cannot dispatch on a registry\n * that consumers extend at runtime.\n */\nconst ItemShapeSchema = z.looseObject({\n type: z.string().min(1),\n id: z.string().min(1),\n slotKey: SlotKeySchema.optional(),\n});\n\n/**\n * Zod schema for an {@link ItemGroup} CONTAINER. Loose: unknown keys\n * preserved. Validates the group's own fields and the stimulus in full, and\n * each item only structurally (`type` and `id`); use {@link validateItemGroup}\n * to validate the items against their registered schemas as well.\n */\nexport const ItemGroupSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('item-group'),\n id: z.string().min(1),\n title: z.string().optional(),\n slotKey: SlotKeySchema.optional(),\n stimulus: StimulusSchema,\n items: z.array(ItemShapeSchema).min(1),\n shuffle: z.enum(['none', 'within-group']).optional(),\n })\n .refine((group) => group.items.every((item) => item.type !== 'item-group'), {\n error: 'Item groups do not nest: every item must be an activity.',\n path: ['items'],\n })\n .refine((group) => new Set(group.items.map((item) => item.id)).size === group.items.length, {\n error: 'Item ids must be unique within a group.',\n path: ['items'],\n });\n\n/** The learner-safe shape of a stimulus, derived from the strict schema below. */\nexport type RedactedStimulus = z.infer<typeof RedactedStimulusSchema>;\n\n/** Strict learner-safe stimulus: everything but the author-only `transcript`. */\nexport const RedactedStimulusSchema = z.strictObject({\n id: z.string().min(1),\n kind: z.enum(['text', 'audio', 'video', 'image', 'mixed']),\n title: z.string().optional(),\n body: z.string().optional(),\n bodyHtml: z.string().optional(),\n media: RedactedMediaSchema.optional(),\n locale: z.string().optional(),\n attribution: z.string().optional(),\n});\n\n/**\n * Strict learner-safe item group. Items are left opaque here — each is proven\n * learner-safe by `assertRedacted` against its OWN type's redacted schema,\n * which is the only place that knowledge lives. The one exception is the one\n * rule that spans the container and an item: a captioned stimulus recording\n * played to a dictation is not learner-safe, because the captions are the\n * dictation's answer.\n */\nexport const RedactedItemGroupSchema = z\n .strictObject({\n redacted: z.literal(true),\n schemaVersion: z.literal('1.0'),\n type: z.literal('item-group'),\n id: z.string().min(1),\n title: z.string().optional(),\n slotKey: SlotKeySchema.optional(),\n stimulus: RedactedStimulusSchema,\n items: z.array(z.unknown()).min(1),\n shuffle: z.enum(['none', 'within-group']).optional(),\n })\n .check((ctx) => {\n if (groupCaptionsRevealDictation(ctx.value)) {\n ctx.issues.push({\n code: 'custom',\n input: ctx.value.stimulus.media?.captionsUrl,\n message: GROUP_CAPTIONS_REVEAL_DICTATION,\n path: ['stimulus', 'media', 'captionsUrl'],\n });\n }\n });\n\nfunction toValidationErrors(\n issues: readonly { path: PropertyKey[]; message: string; code: string }[],\n prefix: string[],\n): ValidationError[] {\n return issues.map((issue) => ({\n path: [...prefix, ...issue.path.map(String)],\n message: issue.message,\n code: issue.code,\n }));\n}\n\n/**\n * Validates an item group in full: the container and stimulus against\n * {@link ItemGroupSchema}, then every item against the schema registered for\n * its `type`. Errors from items are reported at `items.<index>.…`.\n *\n * Unlike `validateActivity`, an item whose type is not registered is REPORTED\n * (code `unknown_activity_type`) rather than thrown: a group is validated as\n * a whole, and an author fixing a six-item group wants every problem listed,\n * not the first one that happened to throw.\n */\nexport function validateItemGroup(data: unknown): ValidationResult<ItemGroup> {\n const container = ItemGroupSchema.safeParse(data);\n if (!container.success) {\n return { success: false, errors: toValidationErrors(container.error.issues, []) };\n }\n\n const errors: ValidationError[] = [];\n const items: ActivityData[] = [];\n container.data.items.forEach((item, index) => {\n const descriptor = getActivityTypeDescriptor(item.type);\n if (descriptor === undefined) {\n errors.push({\n path: ['items', String(index), 'type'],\n message: `Activity type \"${item.type}\" is not registered`,\n code: 'unknown_activity_type',\n });\n return;\n }\n const parsed = descriptor.schema.safeParse(item);\n if (!parsed.success) {\n errors.push(...toValidationErrors(parsed.error.issues, ['items', String(index)]));\n return;\n }\n items.push(parsed.data as ActivityData);\n });\n if (groupCaptionsRevealDictation(container.data)) {\n errors.push({\n path: ['stimulus', 'media', 'captionsUrl'],\n message: GROUP_CAPTIONS_REVEAL_DICTATION,\n code: 'custom',\n });\n }\n\n if (errors.length > 0) {\n return { success: false, errors };\n }\n // zod4 optional outputs are `T | undefined`; the wire type uses exact\n // optionals. Structurally identical at runtime — the cast is type-level.\n return { success: true, data: { ...container.data, items } as unknown as ItemGroup };\n}\n","import { z } from 'zod/v4';\nimport { UnknownActivityTypeError } from '../errors.js';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport { DictationDataSchema } from './dictation.js';\nimport { FillInTheBlanksDataSchema } from './fill-in-the-blanks.js';\nimport { GapSelectDataSchema } from './gap-select.js';\nimport { ItemGroupSchema, StimulusSchema } from './item-group.js';\nimport { MultipleChoiceDataSchema } from './multiple-choice.js';\nimport { WrittenResponseDataSchema } from './written-response.js';\n\n/**\n * JSON Schema (Draft 7) for a `Stimulus`. Structural contract only — the\n * kind/media/body consistency guards are Zod-only.\n */\nexport const stimulusJsonSchema = z.toJSONSchema(StimulusSchema, { target: 'draft-7' });\n\n/**\n * JSON Schema (Draft 7) for an `ItemGroup` CONTAINER. Items appear as objects\n * with `type` and `id` only; each item's own contract is `jsonSchemaFor(type)`.\n * For an AI generation pipeline, ask for the group and each item separately\n * rather than a single nested schema — that keeps the per-type schema the\n * registry's, not a copy.\n */\nexport const itemGroupJsonSchema = z.toJSONSchema(ItemGroupSchema, { target: 'draft-7' });\n\n/**\n * JSON Schema (Draft 7) representation of the Multiple Choice activity data\n * contract, generated natively by Zod 4. Draft 7 is mandated by Requirement\n * 2.2 for the widest AI-prompt / OpenAPI tooling compatibility. The semantic\n * `.refine()` guards are not representable in JSON Schema and are\n * intentionally omitted — the export captures the *structural* contract only.\n * Since v0.3 the source schemas are loose, so these no longer emit\n * `additionalProperties: false` — the JSON Schema and `validateActivity` now\n * agree on unknown-key handling.\n */\n/**\n * JSON Schema (Draft 7) representation of the Gap Select activity data\n * contract. Structural contract only: the six semantic guards — the\n * passage/gap bijection, id uniqueness, the one-choice-source rule, and an\n * answer key that names a choice the gap offers — are Zod-only, as they are\n * for the other types.\n */\nexport const gapSelectJsonSchema = z.toJSONSchema(GapSelectDataSchema, {\n target: 'draft-7',\n});\n\n/**\n * JSON Schema (Draft 7) representation of the Dictation activity data\n * contract. Structural contract, plus the raw length caps JSON Schema can\n * state in code points as zod counts them — `maxLength` 2000 on a transcript\n * and an accepted transcript, 200 on a rule's `from` and `to`. The twelve\n * semantic guards — a transcript that survives normalisation, the caps after\n * equivalences are applied, distinct candidates, audio only, the\n * slow-recording rules, no captions, no transcript in the title — are\n * Zod-only, as they are for the other types.\n */\nexport const dictationJsonSchema = z.toJSONSchema(DictationDataSchema, {\n target: 'draft-7',\n});\n\nexport const multipleChoiceJsonSchema = z.toJSONSchema(MultipleChoiceDataSchema, {\n target: 'draft-7',\n});\n\n/**\n * JSON Schema (Draft 7) representation of the Fill-in-the-Blanks activity data\n * contract, generated natively by Zod 4. Structural contract only (semantic\n * `.refine()` guards are Zod-only and not representable in JSON Schema).\n */\nexport const fillInTheBlanksJsonSchema = z.toJSONSchema(FillInTheBlanksDataSchema, {\n target: 'draft-7',\n});\n\n/**\n * JSON Schema (Draft 7) representation of the Written Response activity data\n * contract. Structural contract only.\n */\nexport const writtenResponseJsonSchema = z.toJSONSchema(WrittenResponseDataSchema, {\n target: 'draft-7',\n});\n\n/**\n * Derives the JSON Schema (Draft 7) for any REGISTERED activity type — the\n * live, registry-backed replacement for the static per-type exports above,\n * and the building block for AI generation pipelines (R6.1): pass the result\n * as a structured-output schema so a model can only emit valid items.\n *\n * @throws UnknownActivityTypeError when `type` has no registered descriptor.\n */\nexport function jsonSchemaFor(type: string): Record<string, unknown> {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(type);\n }\n return z.toJSONSchema(descriptor.schema as never, { target: 'draft-7' }) as Record<\n string,\n unknown\n >;\n}\n","import { UnknownActivityTypeError } from '../errors.js';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ActivityDataMap, ActivityType, ValidationResult } from '../types/activity.js';\n\nexport {\n DictationDataSchema,\n DictationEquivalenceSchema,\n DictationSlowMediaSchema,\n DictationToleranceSchema,\n} from './dictation.js';\nexport { FeedbackSchema } from './feedback.js';\nexport {\n BlankConfigSchema,\n FillInTheBlanksDataSchema,\n TextMatchPolicySchema,\n} from './fill-in-the-blanks.js';\nexport {\n GapSelectBankSchema,\n GapSelectChoiceSchema,\n GapSelectDataSchema,\n GapSelectGapSchema,\n} from './gap-select.js';\nexport type { RedactedStimulus } from './item-group.js';\nexport {\n ItemGroupSchema,\n RedactedItemGroupSchema,\n RedactedStimulusSchema,\n StimulusSchema,\n validateItemGroup,\n} from './item-group.js';\nexport {\n dictationJsonSchema,\n fillInTheBlanksJsonSchema,\n gapSelectJsonSchema,\n itemGroupJsonSchema,\n jsonSchemaFor,\n multipleChoiceJsonSchema,\n stimulusJsonSchema,\n writtenResponseJsonSchema,\n} from './json-schema.js';\nexport {\n MediaPlaybackSchema,\n MediaSchema,\n MediaUrlSchema,\n NativeControlHintSchema,\n RedactedMediaSchema,\n} from './media.js';\nexport {\n MultipleChoiceDataSchema,\n MultipleChoiceOptionMediaSchema,\n MultipleChoiceOptionSchema,\n} from './multiple-choice.js';\nexport type {\n RedactedActivity,\n RedactedBlankConfig,\n RedactedDictationData,\n RedactedDictationSlowMedia,\n RedactedFillInTheBlanksData,\n RedactedGapSelectBank,\n RedactedGapSelectChoice,\n RedactedGapSelectData,\n RedactedGapSelectGap,\n RedactedMultipleChoiceData,\n RedactedMultipleChoiceOption,\n RedactedMultipleChoiceOptionMedia,\n RedactedWrittenResponseData,\n} from './redacted.js';\nexport {\n RedactedBlankConfigSchema,\n RedactedDictationDataSchema,\n RedactedDictationSlowMediaSchema,\n RedactedFillInTheBlanksDataSchema,\n RedactedGapSelectBankSchema,\n RedactedGapSelectChoiceSchema,\n RedactedGapSelectDataSchema,\n RedactedGapSelectGapSchema,\n RedactedMultipleChoiceDataSchema,\n RedactedMultipleChoiceOptionMediaSchema,\n RedactedMultipleChoiceOptionSchema,\n RedactedWrittenResponseDataSchema,\n} from './redacted.js';\nexport {\n WrittenResponseDataSchema,\n WrittenResponseRubricCriterionSchema,\n WrittenResponseRubricSchema,\n} from './written-response.js';\n\n/**\n * Validates raw activity data against the schema registered for the given\n * activity type (built-in or consumer-registered via `registerActivityType`).\n *\n * Unknown keys are PRESERVED, not stripped: every built-in schema is loose,\n * so consumer sidecar fields and forward-version fields survive validation\n * verbatim in the returned `data`.\n *\n * @returns `{ success: true, data }` with the typed, validated data, or\n * `{ success: false, errors }` with one entry per failed constraint.\n * @throws UnknownActivityTypeError when `type` has no registered descriptor.\n */\nexport function validateActivity<T extends ActivityType>(\n type: T,\n data: unknown,\n): ValidationResult<ActivityDataMap[T]> {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(type));\n }\n\n const result = descriptor.schema.safeParse(data);\n\n if (result.success) {\n return { success: true, data: result.data as ActivityDataMap[T] };\n }\n\n return {\n success: false,\n errors: result.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n };\n}\n"]}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DeferredScoringError,
|
|
3
3
|
RedactedScoringError,
|
|
4
|
+
STEP,
|
|
4
5
|
UnknownActivityTypeError,
|
|
6
|
+
alignSequences,
|
|
5
7
|
getActivityTypeDescriptor
|
|
6
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-XKKKWKRH.js";
|
|
7
9
|
|
|
8
10
|
// src/scoring/rounding.ts
|
|
9
11
|
var EPSILON = 1e-9;
|
|
@@ -248,8 +250,47 @@ function composeAssessmentScore(sections, policy) {
|
|
|
248
250
|
};
|
|
249
251
|
}
|
|
250
252
|
|
|
253
|
+
// src/scoring/dictation/chars.ts
|
|
254
|
+
function diffDictationChars(reference, attempt) {
|
|
255
|
+
const referencePoints = Array.from(reference);
|
|
256
|
+
const attemptPoints = Array.from(attempt);
|
|
257
|
+
return alignSequences(referencePoints, attemptPoints).map(
|
|
258
|
+
({ step, referenceIndex, attemptIndex }) => {
|
|
259
|
+
if (step === STEP.missing) {
|
|
260
|
+
return { op: "missing", reference: referencePoints[referenceIndex], attempt: "" };
|
|
261
|
+
}
|
|
262
|
+
if (step === STEP.extra) {
|
|
263
|
+
return { op: "extra", reference: "", attempt: attemptPoints[attemptIndex] };
|
|
264
|
+
}
|
|
265
|
+
const referencePoint = referencePoints[referenceIndex];
|
|
266
|
+
const attemptPoint = attemptPoints[attemptIndex];
|
|
267
|
+
return {
|
|
268
|
+
op: referencePoint === attemptPoint ? "equal" : "substitute",
|
|
269
|
+
reference: referencePoint,
|
|
270
|
+
attempt: attemptPoint
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
|
|
251
276
|
// src/scoring/index.ts
|
|
252
277
|
var DEFAULT_PASS_THRESHOLD = 0.7;
|
|
278
|
+
var ROUNDING_MODES = ["half-up", "half-even", "floor", "ceil"];
|
|
279
|
+
var MAX_ROUNDING_DP = 15;
|
|
280
|
+
function roundingOf(options) {
|
|
281
|
+
const rounding = options?.rounding;
|
|
282
|
+
if (rounding === void 0 || rounding === null) {
|
|
283
|
+
return void 0;
|
|
284
|
+
}
|
|
285
|
+
const { mode, dp } = rounding;
|
|
286
|
+
if (!ROUNDING_MODES.includes(mode) || typeof dp !== "number" || !Number.isInteger(dp) || dp < 0 || dp > MAX_ROUNDING_DP) {
|
|
287
|
+
const describe = (value) => typeof value === "string" ? JSON.stringify(value) : typeof value === "number" || value === void 0 ? String(value) : typeof value === "object" ? "an object" : `a ${typeof value}`;
|
|
288
|
+
throw new RangeError(
|
|
289
|
+
`Invalid rounding policy (mode ${describe(mode)}, dp ${describe(dp)}): expected { mode: 'half-up' | 'half-even' | 'floor' | 'ceil', dp: a whole number from 0 to ${MAX_ROUNDING_DP} }.`
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
return { mode, dp };
|
|
293
|
+
}
|
|
253
294
|
function computePassThreshold(activityData, score2, rounding) {
|
|
254
295
|
const threshold = activityData.passThreshold ?? DEFAULT_PASS_THRESHOLD;
|
|
255
296
|
return rounding === void 0 ? score2 >= threshold : gte(score2, threshold, rounding);
|
|
@@ -264,7 +305,8 @@ function selectFeedback(activityData, passed) {
|
|
|
264
305
|
}
|
|
265
306
|
return (passed ? feedback.correct : feedback.incorrect) ?? null;
|
|
266
307
|
}
|
|
267
|
-
function score(activityType, activityData, learnerResponse) {
|
|
308
|
+
function score(activityType, activityData, learnerResponse, options) {
|
|
309
|
+
const rounding = roundingOf(options);
|
|
268
310
|
const descriptor = getActivityTypeDescriptor(activityType);
|
|
269
311
|
if (descriptor === void 0) {
|
|
270
312
|
throw new UnknownActivityTypeError(String(activityType));
|
|
@@ -279,10 +321,11 @@ function score(activityType, activityData, learnerResponse) {
|
|
|
279
321
|
if (!Number.isFinite(result.score)) {
|
|
280
322
|
throw new RedactedScoringError(descriptor.type);
|
|
281
323
|
}
|
|
282
|
-
const passed = computePassThreshold(activityData, result.score);
|
|
324
|
+
const passed = computePassThreshold(activityData, result.score, rounding);
|
|
283
325
|
return { ...result, passed, feedback: result.feedback ?? selectFeedback(activityData, passed) };
|
|
284
326
|
}
|
|
285
|
-
function evaluate(data, response) {
|
|
327
|
+
function evaluate(data, response, options) {
|
|
328
|
+
const rounding = roundingOf(options);
|
|
286
329
|
const type = data.type;
|
|
287
330
|
const descriptor = typeof type === "string" ? getActivityTypeDescriptor(type) : void 0;
|
|
288
331
|
if (descriptor === void 0) {
|
|
@@ -316,7 +359,7 @@ function evaluate(data, response) {
|
|
|
316
359
|
maxScore: result.maxScore
|
|
317
360
|
};
|
|
318
361
|
}
|
|
319
|
-
const passed = computePassThreshold(data, result.score);
|
|
362
|
+
const passed = computePassThreshold(data, result.score, rounding);
|
|
320
363
|
return {
|
|
321
364
|
status: "scored",
|
|
322
365
|
score: result.score,
|
|
@@ -332,6 +375,7 @@ export {
|
|
|
332
375
|
gte,
|
|
333
376
|
classifyBand,
|
|
334
377
|
composeAssessmentScore,
|
|
378
|
+
diffDictationChars,
|
|
335
379
|
DEFAULT_PASS_THRESHOLD,
|
|
336
380
|
computePassThreshold,
|
|
337
381
|
score,
|
|
@@ -340,4 +384,4 @@ export {
|
|
|
340
384
|
outcomeFromGrade,
|
|
341
385
|
hasGrade
|
|
342
386
|
};
|
|
343
|
-
//# sourceMappingURL=chunk-
|
|
387
|
+
//# sourceMappingURL=chunk-FGN4LLSP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/scoring/rounding.ts","../src/grading.ts","../src/scoring/compose.ts","../src/scoring/dictation/chars.ts","../src/scoring/index.ts"],"sourcesContent":["/**\n * Rounding for assessment scores.\n *\n * Rounding is **two different operations** that must not share one policy, and\n * conflating them silently inverts one of them:\n *\n * - **Grade rounding** decides the number a learner is shown and recorded\n * against. It rounds to a fixed number of decimal places, conventionally\n * half-up, so a learner shown \"70%\" is not recorded as a fail at 69.6.\n * - **Band / level classification** decides which level someone is placed in.\n * It deliberately **floors**: placing a learner above their real level is\n * the more harmful error, so a band boundary must not be reached by\n * rounding up.\n *\n * There is therefore no default `RoundingPolicy` anywhere in this SDK, and\n * `dp` has no default either — an integrator's deliberate choice must never be\n * supplied by us.\n */\n\n/** How a value is rounded to `dp` decimal places. */\nexport type RoundingMode = 'half-up' | 'half-even' | 'floor' | 'ceil';\n\n/** A rounding policy. Both fields are required — the SDK never guesses either. */\nexport interface RoundingPolicy {\n mode: RoundingMode;\n /** Decimal places. Load-bearing: `dp: 2` is what stops 69.6 becoming a fail at 70. */\n dp: number;\n}\n\n/**\n * Float-noise guard. Binary floating point makes `1.005 * 100` come out as\n * `100.49999999999999` and `0.29 * 100` come out as `28.999999999999996`;\n * without an allowance both would move a learner's grade a step. It is applied\n * in the direction each mode needs — see {@link roundGrade}.\n */\nconst EPSILON = 1e-9;\n\n/**\n * Tolerance for deciding \"is this exactly halfway?\" in half-even mode.\n * Deliberately much larger than {@link EPSILON}: if the tie test shared the\n * nudge's tolerance, the nudge would decide its own outcome. Safe for grades,\n * which live on a [0,1] scale where representation error is far below this.\n */\nconst TIE_TOLERANCE = 1e-6;\n\nfunction scaled(value: number, dp: number): number {\n return value * 10 ** dp;\n}\n\n/**\n * Normalises `-0` to `0` without touching anything else. `-0` JSON-serialises\n * as `0` but fails `Object.is(-0, 0)`, which surprises a strict-equality\n * gradebook comparison. Deliberately NOT `|| 0`: that also swallowed `NaN`\n * (reachable with an absurd `dp`, where `10 ** dp` overflows to Infinity) and\n * turned a visible failure into a plausible-looking grade of zero.\n */\nfunction noNegZero(value: number): number {\n return Object.is(value, -0) ? 0 : value;\n}\n\n/**\n * Rounds `value` to `policy.dp` places under `policy.mode`.\n *\n * Idempotent for every mode: rounding an already-rounded value returns it\n * unchanged. That matters because a composed score is rounded once and then\n * compared through {@link gte}, which rounds again.\n */\nexport function roundGrade(value: number, policy: RoundingPolicy): number {\n if (!Number.isFinite(value)) {\n return value;\n }\n const factor = 10 ** policy.dp;\n const raw = scaled(value, policy.dp);\n\n // The nudge must oppose the mode, never point uniformly away from zero.\n // `Math.ceil` on a value that is ALREADY exact at `dp` jumps a whole\n // quantum if you add epsilon first: 0.7 became 0.71, a true 0 became 0.01,\n // and the operation stopped being idempotent (0.7 -> 0.71 -> 0.72). So\n // `ceil` nudges down and `floor` nudges up — just far enough to absorb\n // representation error (0.29 * 100 is 28.999999999999996, which must still\n // floor to 29) without ever moving a value that was already exact.\n // Half modes keep the sign-aware nudge, which is what makes a .5 tie land\n // away from zero.\n switch (policy.mode) {\n case 'floor':\n return noNegZero(Math.floor(raw + EPSILON) / factor);\n case 'ceil':\n return noNegZero(Math.ceil(raw - EPSILON) / factor);\n case 'half-even': {\n // Detect the tie on the RAW value, and with a tolerance decoupled from\n // (and far larger than) the nudge epsilon. Testing the NUDGED value\n // against EPSILON let the nudge itself decide whether a tie was seen:\n // 0.375 was detected but 0.125 was not, so half-even silently degraded\n // to half-up for some exact ties — and only ever in the direction that\n // rounds a learner UP, the opposite of what this mode is chosen for.\n const floored = Math.floor(raw);\n if (Math.abs(raw - floored - 0.5) > TIE_TOLERANCE) {\n return noNegZero(halfAway(raw) / factor);\n }\n // Exactly halfway: pick the even neighbour (banker's rounding).\n const even = floored % 2 === 0 ? floored : floored + 1;\n return noNegZero(even / factor);\n }\n default:\n return noNegZero(halfAway(raw) / factor);\n }\n}\n\n/**\n * Half-up on a scaled value, with the sign-aware float-noise nudge.\n * `Math.round` breaks .5 ties toward +Infinity, so negatives are mirrored to\n * keep the tie breaking away from zero in both directions.\n */\nfunction halfAway(raw: number): number {\n const nudged = raw >= 0 ? raw + EPSILON : raw - EPSILON;\n return raw >= 0 ? Math.round(nudged) : -Math.round(-nudged);\n}\n\n/**\n * Threshold comparison that rounds **both sides** before comparing.\n *\n * Comparing a raw float against a rounded threshold is how a learner ends up\n * shown one number and recorded against another. Rounding both sides — and\n * allowing an epsilon — makes \"what the learner sees\" and \"what the gradebook\n * decides\" the same comparison.\n */\nexport function gte(value: number, threshold: number, policy: RoundingPolicy): boolean {\n return roundGrade(value, policy) >= roundGrade(threshold, policy) - EPSILON;\n}\n\n/** A named band with an inclusive lower bound, e.g. `{ name: 'B1', min: 0.6 }`. */\nexport interface Band {\n name: string;\n /** Inclusive lower bound on the same scale as the value being classified. */\n min: number;\n}\n\n/**\n * Classifies a value into a band by **flooring**: the highest band whose `min`\n * the value actually reaches. Deliberately does NOT round up to a boundary —\n * over-placement is the more harmful error, so a learner just below a boundary\n * stays below it.\n *\n * Returns `null` when the value reaches no band's minimum.\n */\nexport function classifyBand(value: number, bands: readonly Band[]): Band | null {\n let best: Band | null = null;\n for (const band of bands) {\n if (value >= band.min - EPSILON && (best === null || band.min > best.min)) {\n best = band;\n }\n }\n return best;\n}\n","import { computePassThreshold } from './scoring/index.js';\nimport type { ActivityData, ItemOutcome } from './types/activity.js';\nimport type { CriterionScore, GradeRecord } from './types/grading.js';\n\nexport type {\n CriterionScore,\n GradeRecord,\n Grader,\n GraderKind,\n GraderUsage,\n GradingState,\n InlineCorrection,\n} from './types/grading.js';\n\n/** Options for {@link gradeFromRubric}. */\nexport interface GradeFromRubricOptions {\n /**\n * Scaled score [0,1] required to pass. Defaults to the activity's\n * `passThreshold`, or {@link DEFAULT_PASS_THRESHOLD} when absent.\n */\n passThreshold?: number;\n /** Narrative feedback for the learner, carried onto the record verbatim. */\n feedback?: string | null;\n}\n\n/**\n * Computes the weighted total from per-criterion scores — the arithmetic that\n * must NOT be delegated to a language model.\n *\n * A grader is asked for judgement (how good is this criterion?), not for\n * mental arithmetic. Asking a model to also produce the weighted total makes\n * the final grade unverifiable and unreproducible: two runs can return\n * different totals for identical criterion scores. This function makes the\n * total a pure function of the judgements, so a grade can be recomputed and\n * audited years later.\n *\n * Weights are normalised by their sum, so they need not add to 1. Criteria\n * marked `notApplicable`, and those carrying no numeric `score` (a purely\n * banded judgement), are excluded from both numerator and denominator. When\n * nothing scoreable remains the result is `unscorable`, never a zero.\n *\n * Scores need not be in [0,1]: set `maxScore` on a criterion to declare what\n * its score is out of, and each is normalised before weighting. A grader\n * working out of 100 says so and is done:\n *\n * ```ts\n * gradeFromRubric([\n * { name: 'Task achievement', score: 82, maxScore: 100, weight: 2 },\n * { name: 'Range', score: 7, maxScore: 9, weight: 1 },\n * ]);\n * ```\n *\n * The returned `GradeRecord.score` is always scaled [0,1] against\n * `maxScore: 1`, like every other score in the SDK.\n */\nexport function gradeFromRubric(\n criteria: readonly CriterionScore[],\n activityData?: ActivityData,\n options: GradeFromRubricOptions = {},\n): GradeRecord | { unscorable: true; reason: string } {\n // A corrupt score is an ERROR, not an exclusion. Exclusions (`notApplicable`,\n // and band-only criteria with no numeric score) are deliberate authoring\n // decisions; a NaN or Infinity is a broken grader. Silently dropping it\n // would regrade the learner on fewer criteria — with different effective\n // weights — and nobody would know.\n const corrupt = criteria.find(\n (criterion) =>\n criterion.notApplicable !== true &&\n criterion.score !== undefined &&\n !Number.isFinite(criterion.score),\n );\n if (corrupt !== undefined) {\n return {\n unscorable: true,\n reason: `Criterion \"${corrupt.name}\" has a non-finite score (${String(corrupt.score)}). A grade cannot be computed from it.`,\n };\n }\n\n // A `maxScore` that is absent means 1 (the scaled convention). One that is\n // present must be a positive finite number: dividing by 0, a negative, or a\n // NaN would produce a grade nobody can defend.\n const badMax = criteria.find(\n (criterion) =>\n criterion.notApplicable !== true &&\n criterion.maxScore !== undefined &&\n !(Number.isFinite(criterion.maxScore) && criterion.maxScore > 0),\n );\n if (badMax !== undefined) {\n return {\n unscorable: true,\n reason: `Criterion \"${badMax.name}\" declares maxScore ${String(badMax.maxScore)}; it must be a positive, finite number.`,\n };\n }\n\n const scoreable = criteria.filter(\n (criterion) => criterion.notApplicable !== true && typeof criterion.score === 'number',\n );\n\n /** The criterion's score as a ratio in [0,1]. `maxScore` defaults to 1. */\n const ratioOf = (criterion: CriterionScore): number =>\n (criterion.score as number) / (criterion.maxScore ?? 1);\n\n // A grader that returns raw points (4 out of 5) without declaring\n // `maxScore: 5` would otherwise yield `{ score: 4, maxScore: 1 }` and pass\n // every threshold. Reject rather than clamp: silently rescaling someone's\n // grader is worse than telling them it is out of contract. A hair outside\n // the range is float noise and is clamped further down.\n const EPSILON = 1e-9;\n const outOfRange = scoreable.find(\n (criterion) => ratioOf(criterion) < -EPSILON || ratioOf(criterion) > 1 + EPSILON,\n );\n if (outOfRange !== undefined) {\n return {\n unscorable: true,\n reason:\n `Criterion \"${outOfRange.name}\" has score ${outOfRange.score} out of ${outOfRange.maxScore ?? 1}, ` +\n 'which is outside the [0,1] range once scaled. Set `maxScore` on the criterion to declare what the ' +\n 'score is out of (e.g. `maxScore: 100` for a 0–100 grader).',\n };\n }\n\n if (scoreable.length === 0) {\n return {\n unscorable: true,\n reason: 'No criterion carried a numeric score, so no weighted total can be computed.',\n };\n }\n\n const totalWeight = scoreable.reduce((sum, criterion) => sum + (criterion.weight ?? 1), 0);\n if (!(totalWeight > 0)) {\n return {\n unscorable: true,\n reason:\n 'Criterion weights do not sum to a positive number, so the weighted total is undefined.',\n };\n }\n\n const weighted = scoreable.reduce(\n (sum, criterion) => sum + ratioOf(criterion) * (criterion.weight ?? 1),\n 0,\n );\n const rawScore = weighted / totalWeight;\n if (!Number.isFinite(rawScore)) {\n return {\n unscorable: true,\n reason: 'The weighted total is not a finite number, so no grade can be produced.',\n };\n }\n // Clamp the float-noise band only; anything genuinely out of range was\n // already rejected above.\n const score = Math.min(1, Math.max(0, rawScore));\n\n const passed =\n options.passThreshold !== undefined\n ? score >= options.passThreshold\n : activityData !== undefined\n ? computePassThreshold(activityData, score)\n : score >= 0.7;\n\n return {\n score,\n maxScore: 1,\n passed,\n feedback: options.feedback ?? null,\n criteria: [...criteria],\n };\n}\n\n/**\n * Lifts a {@link GradeRecord} into the `graded` arm of {@link ItemOutcome}, so\n * a grade that arrived asynchronously renders through the same path as a\n * synchronously scored item. The score/passed/feedback fields are mirrored\n * onto the outcome for uniform reads; `grade` carries the full record.\n */\nexport function outcomeFromGrade(grade: GradeRecord): ItemOutcome {\n return {\n status: 'graded',\n grade,\n score: grade.score,\n maxScore: grade.maxScore,\n passed: grade.passed,\n feedback: grade.feedback,\n };\n}\n\n/**\n * True when an outcome carries a real grade — either the SDK scored it\n * synchronously or a grader returned one. Use this instead of testing\n * `status === 'scored'`, which silently misses asynchronously graded work.\n */\nexport function hasGrade(\n outcome: ItemOutcome,\n): outcome is Extract<ItemOutcome, { status: 'scored' | 'graded' }> {\n return outcome.status === 'scored' || outcome.status === 'graded';\n}\n","import { hasGrade } from '../grading.js';\nimport type { ItemOutcome } from '../types/activity.js';\nimport { gte, type RoundingPolicy, roundGrade } from './rounding.js';\n\n/**\n * Sectioned assessment scoring — weights, per-section thresholds, and an\n * explicit reason when an attempt fails.\n *\n * This exists because the formula is invariably implemented twice: once on the\n * server that records the grade, and again on the client that shows a learner\n * their grade breakdown. Two implementations of one formula is exactly the\n * duplication an SDK should remove, and they drift — usually in the scale\n * (0–1 vs 0–100) or in whether a section override is honoured.\n */\n\n/** One item's contribution to a section. */\nexport interface ScoredItem {\n /**\n * Identity of the SLOT, not the activity. The same activity can legitimately\n * appear in two sections; keying on the activity id collapses them into one\n * and silently scores the second occurrence as zero.\n */\n slotId: string;\n /** The activity that filled this slot, for reporting. */\n activityId?: string;\n /** Maximum points this slot is worth. */\n points: number;\n /** What the learner achieved, or why there is no grade yet. */\n outcome: ItemOutcome;\n}\n\n/** A weighted section of an assessment. */\nexport interface AssessmentSectionInput {\n id: string;\n title?: string;\n /** Relative weight. Weights are normalised by their sum, so they need not total 1. */\n weight: number;\n /** Overrides the assessment-wide section threshold for this section only. */\n passThresholdOverride?: number;\n items: ScoredItem[];\n}\n\n/** Policy for {@link composeAssessmentScore}. */\nexport interface CompositionPolicy {\n /** Scaled [0,1] overall score required to pass. */\n passThreshold: number;\n /** Scaled [0,1] score each section must reach, when sections gate the pass. */\n sectionThreshold?: number;\n /**\n * How grades are rounded. Required, with no default: see `RoundingPolicy` —\n * grade rounding and band classification are different operations and the\n * SDK must not choose either for you.\n */\n rounding: RoundingPolicy;\n}\n\n/** Per-section result. */\nexport interface SectionScore {\n id: string;\n title?: string;\n /** The authored weight, verbatim. */\n weight: number;\n /**\n * The weight ACTUALLY used in the total, so a client can rebuild the grade\n * from `sections[]` and agree with the record:\n *\n * ```ts\n * roundGrade(\n * sections.reduce((sum, s) => sum + s.score * s.normalizedWeight, 0),\n * policy.rounding,\n * ) === result.score // exact, by construction\n * ```\n *\n * Apply the same final rounding: the raw weighted sum of already-rounded\n * section scores is not itself a rounded value (0.85 and 1.00 at equal\n * weights sum to 0.925 against a recorded 0.93), so comparing it unrounded\n * is off by up to half a quantum.\n *\n * Sections with nothing graded carry `0` here, because they contribute\n * nothing; the remaining weights are renormalised among themselves.\n */\n normalizedWeight: number;\n earnedPoints: number;\n /** Points that are currently gradable — excludes items still awaiting a grade. */\n gradedMaxPoints: number;\n /** Every point in the section, whether graded yet or not. */\n maxPoints: number;\n /** Scaled [0,1] over the GRADED points, rounded once. */\n score: number;\n passed: boolean;\n /** Threshold this section was judged against, after any override. */\n appliedThreshold: number | null;\n /** Slots still awaiting a grade. */\n pendingSlotIds: string[];\n /** Slots that can never be graded, excluded from the denominator. */\n unscorableSlotIds: string[];\n}\n\n/** Why an attempt failed, or `null` when it passed. */\nexport type PassFailureReason =\n | 'overall_below_threshold'\n | 'section_below_threshold'\n | 'both'\n | null;\n\n/** Result of composing an assessment. */\nexport interface AssessmentScore {\n sections: SectionScore[];\n /** Weighted total, scaled [0,1], rounded once. */\n score: number;\n /**\n * Whether the attempt passed — `null` while `status` is `provisional`,\n * because an attempt with work still ungraded has not passed OR failed yet.\n * Returning `false` there would let a UI keyed on `passed` show a fail for\n * an essay nobody has marked.\n */\n passed: boolean | null;\n /** `null` while provisional, for the same reason as {@link passed}. */\n passFailureReason: PassFailureReason;\n /**\n * `provisional` while any item is still awaiting a grade — the total is\n * computed over what HAS been graded, so it can still move. Do not record a\n * provisional score as final. Items that can NEVER be graded\n * (`unscorableSlotIds`) do not hold the result provisional.\n */\n status: 'final' | 'provisional';\n pendingSlotIds: string[];\n /** Slots that can never be graded. Excluded from the denominator. */\n unscorableSlotIds: string[];\n}\n\n/**\n * What one item contributes. THREE states, not two — collapsing the last two\n * into a single \"no points\" answer is what made an unscorable item block an\n * attempt from ever becoming final:\n *\n * - `graded` — real points, counted.\n * - `pending` — a grade is coming (deferred). Excluded from the denominator,\n * and the assessment stays `provisional` until it arrives.\n * - `unscorable` — a grade is never coming (unregistered type, redacted data,\n * incomplete key). Also excluded from the denominator, but it must NOT keep\n * the result provisional forever: `evaluate()` returns this precisely so a\n * mixed-version content bank does not crash an exam, and an attempt that\n * contains one still has to be recordable.\n */\ntype ItemContribution =\n | { state: 'graded'; points: number }\n | { state: 'pending' }\n | { state: 'unscorable' };\n\nfunction earned(item: ScoredItem): ItemContribution {\n const { outcome } = item;\n if (hasGrade(outcome)) {\n const max = outcome.maxScore > 0 ? outcome.maxScore : 1;\n return { state: 'graded', points: (outcome.score / max) * item.points };\n }\n if (outcome.status === 'deferred') {\n return { state: 'pending' };\n }\n return { state: 'unscorable' };\n}\n\n/**\n * Composes per-item outcomes into a sectioned assessment score.\n *\n * Weights are normalised by their sum. Each section's score is computed over\n * the points that are actually gradable and rounded ONCE, before any threshold\n * comparison, so the number a learner is shown is the number that decides the\n * outcome. Items still awaiting a grade are excluded from the denominator\n * rather than counted as zero, and the result is reported as `provisional`\n * until every item has a grade.\n */\nexport function composeAssessmentScore(\n sections: readonly AssessmentSectionInput[],\n policy: CompositionPolicy,\n): AssessmentScore {\n const pendingAll: string[] = [];\n const unscorableAll: string[] = [];\n\n // Pass 1 — score each section over the points that are actually gradable.\n const partials = sections.map((section) => {\n let earnedPoints = 0;\n let gradedMaxPoints = 0;\n let maxPoints = 0;\n const pendingSlotIds: string[] = [];\n const unscorableSlotIds: string[] = [];\n\n for (const item of section.items) {\n maxPoints += item.points;\n const contribution = earned(item);\n if (contribution.state === 'pending') {\n pendingSlotIds.push(item.slotId);\n pendingAll.push(item.slotId);\n continue;\n }\n if (contribution.state === 'unscorable') {\n unscorableSlotIds.push(item.slotId);\n unscorableAll.push(item.slotId);\n continue;\n }\n earnedPoints += contribution.points;\n gradedMaxPoints += item.points;\n }\n\n const raw = gradedMaxPoints > 0 ? earnedPoints / gradedMaxPoints : 0;\n const appliedThreshold = section.passThresholdOverride ?? policy.sectionThreshold ?? null;\n\n return {\n section,\n earnedPoints,\n gradedMaxPoints,\n maxPoints,\n score: roundGrade(raw, policy.rounding),\n appliedThreshold,\n pendingSlotIds,\n unscorableSlotIds,\n };\n });\n\n // Pass 2 — the LIVE weights. Only sections with something graded contribute,\n // and their weights are renormalised among themselves. A section whose items\n // are all still ungraded must not contribute a zero: that is the \"live\n // denominator\" bug, where a midterm reads 50% only because the essay has not\n // been marked and a learner sees a fail for work nobody has looked at.\n // These are the weights reported on each section, so that\n // `sum(score * normalizedWeight) === result.score` holds and a client\n // rendering the breakdown cannot disagree with the recorded grade.\n const contributingWeight = partials.reduce(\n (sum, partial) => sum + (partial.gradedMaxPoints > 0 ? partial.section.weight : 0),\n 0,\n );\n\n const scored: SectionScore[] = partials.map((partial) => ({\n id: partial.section.id,\n ...(partial.section.title !== undefined ? { title: partial.section.title } : {}),\n weight: partial.section.weight,\n normalizedWeight:\n partial.gradedMaxPoints > 0 && contributingWeight > 0\n ? partial.section.weight / contributingWeight\n : 0,\n earnedPoints: partial.earnedPoints,\n gradedMaxPoints: partial.gradedMaxPoints,\n maxPoints: partial.maxPoints,\n score: partial.score,\n // A section with nothing graded yet cannot be said to have failed.\n passed:\n partial.appliedThreshold === null || partial.gradedMaxPoints === 0\n ? true\n : gte(partial.score, partial.appliedThreshold, policy.rounding),\n appliedThreshold: partial.appliedThreshold,\n pendingSlotIds: partial.pendingSlotIds,\n unscorableSlotIds: partial.unscorableSlotIds,\n }));\n\n const weightedRaw = scored.reduce(\n (sum, section) => sum + section.score * section.normalizedWeight,\n 0,\n );\n const score = roundGrade(weightedRaw, policy.rounding);\n\n // Only work that is still COMING keeps the result provisional. Work that can\n // never be graded is excluded from the denominator but must not block the\n // attempt from being recorded.\n const status: 'final' | 'provisional' = pendingAll.length > 0 ? 'provisional' : 'final';\n\n if (status === 'provisional') {\n // Not passed and not failed: undetermined. Saying `false` here would let a\n // UI keyed on `passed` show a fail for unmarked work.\n return {\n sections: scored,\n score,\n passed: null,\n passFailureReason: null,\n status,\n pendingSlotIds: pendingAll,\n unscorableSlotIds: unscorableAll,\n };\n }\n\n // Nothing was gradable at all — every item unscorable, or an assessment with\n // no items. There is no evidence either way, so there is no verdict: a hard\n // `false` here records a fail at 0% for a learner whose work was never\n // gradable, which is the same fabricated-failure this module exists to\n // avoid, just reached through the other door.\n if (scored.every((section) => section.gradedMaxPoints === 0)) {\n return {\n sections: scored,\n score,\n passed: null,\n passFailureReason: null,\n status,\n pendingSlotIds: pendingAll,\n unscorableSlotIds: unscorableAll,\n };\n }\n\n const overallOk = gte(score, policy.passThreshold, policy.rounding);\n const sectionsOk = scored.every((section) => section.passed);\n const passed = overallOk && sectionsOk;\n\n const passFailureReason: PassFailureReason = passed\n ? null\n : !overallOk && !sectionsOk\n ? 'both'\n : overallOk\n ? 'section_below_threshold'\n : 'overall_below_threshold';\n\n return {\n sections: scored,\n score,\n passed,\n passFailureReason,\n status,\n pendingSlotIds: pendingAll,\n unscorableSlotIds: unscorableAll,\n };\n}\n","import { alignSequences, STEP } from './align.js';\n\n/** One code-point edit between a reference string and an attempt. */\nexport interface DictationCharOp {\n op: 'equal' | 'substitute' | 'missing' | 'extra';\n /** One code point of the reference, or `''` for an extra character. */\n reference: string;\n /** One code point of the attempt, or `''` for a missing character. */\n attempt: string;\n}\n\n/**\n * The code-point edit operations between two NORMALISED strings — the\n * `reference` and `attempt` of a `DictationAlignment`, or one word pair from\n * it — for a marked display: a character the learner typed right, typed\n * wrong, left out, or added. Ties are broken preferring an equal or substituted\n * pair, then a missing character, then an extra one, from the end of both\n * strings; the number of non-`equal` ops is the edit distance.\n *\n * Decoration, never grading: it needs O(|reference|·|attempt|) memory, so the\n * scorer does not call it, and a display computes it once per result.\n */\nexport function diffDictationChars(reference: string, attempt: string): DictationCharOp[] {\n const referencePoints = Array.from(reference);\n const attemptPoints = Array.from(attempt);\n return alignSequences(referencePoints, attemptPoints).map(\n ({ step, referenceIndex, attemptIndex }) => {\n if (step === STEP.missing) {\n return { op: 'missing', reference: referencePoints[referenceIndex] as string, attempt: '' };\n }\n if (step === STEP.extra) {\n return { op: 'extra', reference: '', attempt: attemptPoints[attemptIndex] as string };\n }\n const referencePoint = referencePoints[referenceIndex] as string;\n const attemptPoint = attemptPoints[attemptIndex] as string;\n return {\n op: referencePoint === attemptPoint ? 'equal' : 'substitute',\n reference: referencePoint,\n attempt: attemptPoint,\n };\n },\n );\n}\n","import { DeferredScoringError, RedactedScoringError, UnknownActivityTypeError } from '../errors.js';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport type {\n ActivityData,\n ActivityFeedback,\n ActivityType,\n ItemOutcome,\n LearnerResponse,\n ScoringResult,\n} from '../types/activity.js';\nimport { gte, type RoundingPolicy } from './rounding.js';\n\nexport type {\n AssessmentScore,\n AssessmentSectionInput,\n CompositionPolicy,\n PassFailureReason,\n ScoredItem,\n SectionScore,\n} from './compose.js';\nexport { composeAssessmentScore } from './compose.js';\nexport type {\n DictationAlignment,\n DictationCharOp,\n DictationReference,\n DictationWordAlignment,\n} from './dictation/index.js';\nexport {\n alignDictation,\n DICTATION_MAX_ACCEPTED_TRANSCRIPTS,\n DICTATION_MAX_EQUIVALENCE_LENGTH,\n DICTATION_MAX_EQUIVALENCES,\n DICTATION_MAX_TEXT_LENGTH,\n DICTATION_MAX_TRANSCRIPT_LENGTH,\n dictationReferenceWords,\n diffDictationChars,\n} from './dictation/index.js';\nexport type { Band, RoundingMode, RoundingPolicy } from './rounding.js';\nexport { classifyBand, gte, roundGrade } from './rounding.js';\nexport type { TextMatchPolicy, TextMatchResult } from './text-match.js';\nexport { levenshteinDistance, matchText } from './text-match.js';\n\n/** Default minimum scaled score required to pass when `passThreshold` is absent. */\nexport const DEFAULT_PASS_THRESHOLD = 0.7;\n\n/**\n * Options for {@link score} and {@link evaluate}. Additive: with none, both\n * behave exactly as they always have.\n */\nexport interface ScoringOptions {\n /**\n * Compare the pass line the way the score is displayed — both sides rounded,\n * via {@link computePassThreshold} — so an item shown as \"70%\" is not\n * recorded as a fail at 69.995. `passed` AND the authored feedback selected by\n * it follow the rounded comparison. Opt-in, for the reason\n * {@link computePassThreshold} gives: switching it on moves item-level\n * pass/fail for scores in the rounding band.\n *\n * Checked at the call: `null` reads as no policy, and a policy that cannot be\n * applied — an unknown `mode`, or a `dp` that is not a whole number from 0 to\n * 15 — throws a `RangeError` instead of quietly failing every comparison.\n */\n rounding?: RoundingPolicy;\n}\n\nconst ROUNDING_MODES: readonly unknown[] = ['half-up', 'half-even', 'floor', 'ceil'];\n/** The most decimal places a policy may round to: a scaled grade stays an integer a double holds exactly. */\nconst MAX_ROUNDING_DP = 15;\n\n/**\n * The rounding policy of `options`, or `undefined` for none. A malformed one\n * would reach {@link gte} as `10 ** undefined` and turn a perfect score into a\n * fail with no error, so it throws here instead.\n */\nfunction roundingOf(options: ScoringOptions | undefined): RoundingPolicy | undefined {\n const rounding: unknown = options?.rounding;\n if (rounding === undefined || rounding === null) {\n return undefined;\n }\n const { mode, dp } = rounding as { mode?: unknown; dp?: unknown };\n if (\n !ROUNDING_MODES.includes(mode) ||\n typeof dp !== 'number' ||\n !Number.isInteger(dp) ||\n dp < 0 ||\n dp > MAX_ROUNDING_DP\n ) {\n // Described field by field, never serialised: a policy holding a BigInt or\n // a reference to itself would make the message throw a TypeError first.\n const describe = (value: unknown): string =>\n typeof value === 'string'\n ? JSON.stringify(value)\n : typeof value === 'number' || value === undefined\n ? String(value)\n : typeof value === 'object'\n ? 'an object'\n : `a ${typeof value}`;\n throw new RangeError(\n `Invalid rounding policy (mode ${describe(mode)}, dp ${describe(dp)}): expected { mode: 'half-up' | 'half-even' | 'floor' | 'ceil', dp: a whole number from 0 to ${MAX_ROUNDING_DP} }.`,\n );\n }\n // The values just checked, not the object they came from: an accessor could\n // answer differently when the comparison reads it again.\n return { mode, dp } as RoundingPolicy;\n}\n\n/**\n * Returns `true` iff `score` meets or exceeds the activity's `passThreshold`,\n * defaulting to {@link DEFAULT_PASS_THRESHOLD} (0.7) when the field is absent.\n *\n * Pass a {@link RoundingPolicy} to compare the way an assessment total is\n * compared — both sides rounded, via {@link gte} — so an item shown as \"70%\"\n * cannot be recorded as a fail at 69.6. It is **opt-in** rather than the\n * default because switching it on changes item-level pass/fail for scores in\n * the rounding band, and this SDK does not alter historical grades without an\n * explicit decision. Absent, the comparison is the exact raw `>=` it has\n * always been.\n */\nexport function computePassThreshold(\n activityData: ActivityData,\n score: number,\n rounding?: RoundingPolicy,\n): boolean {\n const threshold = activityData.passThreshold ?? DEFAULT_PASS_THRESHOLD;\n return rounding === undefined ? score >= threshold : gte(score, threshold, rounding);\n}\n\n/**\n * True when `data` is a `redact()` projection rather than full activity data.\n * Scoring a redacted item is always a bug: the answer key is gone by design,\n * so any \"score\" computed from it is meaningless (it used to come out `NaN`).\n */\nfunction isRedacted(data: unknown): boolean {\n return (\n typeof data === 'object' && data !== null && (data as { redacted?: unknown }).redacted === true\n );\n}\n\n/**\n * Selects the authored overall feedback for a result: `feedback.correct` when\n * the learner passed, `feedback.incorrect` otherwise; `null` when no matching\n * message was authored. Mirrors the selection the lk-react components applied\n * (keyed on `passed`, per the `ActivityFeedback` contract).\n */\nfunction selectFeedback(activityData: ActivityData, passed: boolean): string | null {\n const feedback = (activityData as { feedback?: ActivityFeedback }).feedback;\n if (feedback === undefined) {\n return null;\n }\n return (passed ? feedback.correct : feedback.incorrect) ?? null;\n}\n\n/**\n * Scores a learner response against activity data and returns a full\n * {@link ScoringResult}.\n *\n * Pure and deterministic with no side effects. It does **not** re-validate\n * `activityData` — schema validation is the component boundary's\n * responsibility; this is a low-level scoring primitive that trusts its typed\n * inputs. Dispatch is registry-backed: consumer-registered types with `sync`\n * scoring work here too. An unregistered type throws\n * {@link UnknownActivityTypeError}; a type whose grading is deferred (e.g.\n * `written-response`) throws {@link DeferredScoringError} — use\n * {@link evaluate}, which can express \"not graded yet\".\n */\nexport function score(\n activityType: ActivityType,\n activityData: ActivityData,\n learnerResponse: LearnerResponse,\n options?: ScoringOptions,\n): ScoringResult {\n const rounding = roundingOf(options);\n const descriptor = getActivityTypeDescriptor(activityType);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(activityType));\n }\n if (descriptor.scoring.kind === 'deferred') {\n throw new DeferredScoringError(descriptor.type);\n }\n if (isRedacted(activityData)) {\n throw new RedactedScoringError(descriptor.type);\n }\n\n const result = descriptor.scoring.score(activityData, learnerResponse);\n if (!Number.isFinite(result.score)) {\n throw new RedactedScoringError(descriptor.type);\n }\n const passed = computePassThreshold(activityData, result.score, rounding);\n return { ...result, passed, feedback: result.feedback ?? selectFeedback(activityData, passed) };\n}\n\n/**\n * Evaluates a learner response against an activity and returns an\n * {@link ItemOutcome} — the resilient, forward-compatible alternative to\n * {@link score}:\n *\n * - Synchronously graded types return `{ status: 'scored', ... }` with the\n * same numbers `score()` produces.\n * - Asynchronously graded types (e.g. `written-response`) return\n * `{ status: 'deferred', reason, partial }` instead of a fake zero — \"not\n * graded yet\" is expressible in the type system, never conflated with\n * \"wrong\".\n * - An unregistered `data.type` returns `{ status: 'unscorable' }` rather\n * than throwing, so a mixed-version content bank cannot crash an exam run.\n *\n * The activity type is read from `data.type` — there is no separate type\n * parameter to disagree with the payload.\n */\nexport function evaluate(\n data: ActivityData,\n response: LearnerResponse,\n options?: ScoringOptions,\n): ItemOutcome {\n // A malformed option is the caller's configuration, not the content bank's:\n // it throws before any item is read, rather than grading every item wrong.\n const rounding = roundingOf(options);\n const type = (data as { type?: unknown }).type;\n const descriptor = typeof type === 'string' ? getActivityTypeDescriptor(type) : undefined;\n\n if (descriptor === undefined) {\n return {\n status: 'unscorable',\n reason: `Activity type \"${String(type)}\" is not registered`,\n maxScore: 1,\n };\n }\n\n if (descriptor.scoring.kind === 'deferred') {\n const partial = descriptor.scoring.partial?.(data, response);\n return {\n status: 'deferred',\n reason: descriptor.scoring.reason,\n maxScore: 1,\n ...(partial !== undefined ? { partial } : {}),\n };\n }\n\n if (isRedacted(data)) {\n return {\n status: 'unscorable',\n reason:\n 'Activity data is redacted (no answer key), so it cannot be scored on the client. Score against the full data server-side.',\n maxScore: 1,\n };\n }\n\n const result = descriptor.scoring.score(data, response);\n if (!Number.isFinite(result.score)) {\n // Defence in depth: incomplete data (a missing answer key, an empty\n // options array) used to divide by zero and surface as a real score of\n // NaN, which JSON-serializes to null in a grade column.\n return {\n status: 'unscorable',\n reason: `Scoring \"${descriptor.type}\" produced a non-finite score; the activity data is incomplete.`,\n maxScore: result.maxScore,\n };\n }\n const passed = computePassThreshold(data, result.score, rounding);\n return {\n status: 'scored',\n score: result.score,\n maxScore: result.maxScore,\n passed,\n feedback: result.feedback ?? selectFeedback(data, passed),\n details: result.details,\n };\n}\n"],"mappings":";;;;;;;;;;AAmCA,IAAM,UAAU;AAQhB,IAAM,gBAAgB;AAEtB,SAAS,OAAO,OAAe,IAAoB;AACjD,SAAO,QAAQ,MAAM;AACvB;AASA,SAAS,UAAU,OAAuB;AACxC,SAAO,OAAO,GAAG,OAAO,EAAE,IAAI,IAAI;AACpC;AASO,SAAS,WAAW,OAAe,QAAgC;AACxE,MAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC3B,WAAO;AAAA,EACT;AACA,QAAM,SAAS,MAAM,OAAO;AAC5B,QAAM,MAAM,OAAO,OAAO,OAAO,EAAE;AAWnC,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO,UAAU,KAAK,MAAM,MAAM,OAAO,IAAI,MAAM;AAAA,IACrD,KAAK;AACH,aAAO,UAAU,KAAK,KAAK,MAAM,OAAO,IAAI,MAAM;AAAA,IACpD,KAAK,aAAa;AAOhB,YAAM,UAAU,KAAK,MAAM,GAAG;AAC9B,UAAI,KAAK,IAAI,MAAM,UAAU,GAAG,IAAI,eAAe;AACjD,eAAO,UAAU,SAAS,GAAG,IAAI,MAAM;AAAA,MACzC;AAEA,YAAM,OAAO,UAAU,MAAM,IAAI,UAAU,UAAU;AACrD,aAAO,UAAU,OAAO,MAAM;AAAA,IAChC;AAAA,IACA;AACE,aAAO,UAAU,SAAS,GAAG,IAAI,MAAM;AAAA,EAC3C;AACF;AAOA,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C,UAAU,OAAO;AAAA,IACnB;AAAA,EACF;AACA,QAAM,SAAS,qBAAqB,MAAM,OAAO,OAAO,QAAQ;AAChE,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,OAAO,OAAO;AAAA,IACd,UAAU,OAAO;AAAA,IACjB;AAAA,IACA,UAAU,OAAO,YAAY,eAAe,MAAM,MAAM;AAAA,IACxD,SAAS,OAAO;AAAA,EAClB;AACF;","names":["EPSILON","score","score","score"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkXONKWL6Dcjs = require('./chunk-XONKWL6D.cjs');
|
|
5
5
|
|
|
6
6
|
// src/xapi/validators.ts
|
|
7
7
|
var _v4 = require('zod/v4');
|
|
@@ -83,7 +83,7 @@ function validateXAPIStatement(statement) {
|
|
|
83
83
|
console.warn("[learning-kit] Invalid xAPI statement (sent anyway):", errors);
|
|
84
84
|
return;
|
|
85
85
|
}
|
|
86
|
-
throw new (0,
|
|
86
|
+
throw new (0, _chunkXONKWL6Dcjs.ActivitySchemaError)("xAPIStatement", errors);
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
// src/xapi/verbs.ts
|
|
@@ -246,7 +246,7 @@ var xAPIBuilder = {
|
|
|
246
246
|
}
|
|
247
247
|
};
|
|
248
248
|
function xapiDefinitionFor(data) {
|
|
249
|
-
const descriptor =
|
|
249
|
+
const descriptor = _chunkXONKWL6Dcjs.getActivityTypeDescriptor.call(void 0, data.type);
|
|
250
250
|
const interop = _optionalChain([descriptor, 'optionalAccess', _6 => _6.interop]);
|
|
251
251
|
if (interop === void 0) {
|
|
252
252
|
return {};
|
|
@@ -266,4 +266,4 @@ function xapiDefinitionFor(data) {
|
|
|
266
266
|
|
|
267
267
|
|
|
268
268
|
exports.validateXAPIStatement = validateXAPIStatement; exports.XAPIVerb = XAPIVerb; exports.XAPI_VERB_DISPLAY = XAPI_VERB_DISPLAY; exports.xAPIBuilder = xAPIBuilder; exports.xapiDefinitionFor = xapiDefinitionFor;
|
|
269
|
-
//# sourceMappingURL=chunk-
|
|
269
|
+
//# sourceMappingURL=chunk-FT7SAC3X.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/chunk-VTTRXGDD.cjs","../src/xapi/validators.ts","../src/xapi/verbs.ts","../src/xapi/builder.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACLA,4BAAkB;AAKlB,IAAM,QAAA,EAAU,wEAAA;AAEhB,IAAM,IAAA,EAAM,sBAAA;AAEZ,IAAM,QAAA,EAAU,KAAA,CAAE,MAAA,CAAO,KAAA,CAAE,MAAA,CAAO,CAAA,EAAG,KAAA,CAAE,MAAA,CAAO,CAAC,CAAA;AAC/C,IAAM,WAAA,EAAa,KAAA,CAAE,MAAA,CAAO,KAAA,CAAE,MAAA,CAAO,CAAA,EAAG,KAAA,CAAE,OAAA,CAAQ,CAAC,CAAA;AAEnD,IAAM,YAAA,EAAc,KAAA,CACjB,MAAA,CAAO;AAAA,EACN,UAAA,EAAY,KAAA,CAAE,OAAA,CAAQ,OAAO,CAAA;AAAA,EAC7B,IAAA,EAAM,KAAA,CAAE,MAAA,CAAO,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EAC1B,IAAA,EAAM,KAAA,CACH,MAAA,CAAO,CAAA,CACP,KAAA,CAAM,UAAA,EAAY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;AACA,IAAA;AACA,IAAA;AACA,IAAA;AAGA,IAAA;AACN,EAAA;AACO,EAAA;AACL,IAAA;AACI,IAAA;AACA,IAAA;AACN,EAAA;AACF;AAMS;AAMA,EAAA;AACL,IAAA;AACA,IAAA;AACI,IAAA;AAEE,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACA,MAAA;AAED,IAAA;AACD,IAAA;AACA,IAAA;AACN,EAAA;AACF;AAOa;AACX,EAAA;AACQ,IAAA;AACA,MAAA;AACJ,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACF,MAAA;AACA,MAAA;AACI,MAAA;AACA,MAAA;AACJ,MAAA;AACA,MAAA;AACF,IAAA;AAGA,IAAA;AACA,IAAA;AACF,EAAA;AAEA,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACI,MAAA;AACL,IAAA;AACH,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACI,MAAA;AACL,IAAA;AACH,EAAA;AAEA,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACI,MAAA;AACL,IAAA;AACH,EAAA;AACF;AAgBgB;AACR,EAAA;AACA,EAAA;AACF,EAAA;AACF,IAAA;AACF,EAAA;AACM,EAAA;AACC,EAAA;AACD,IAAA;AACA,IAAA;AAGA,IAAA;AACN,EAAA;AACF;AHRU;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/chunk-VTTRXGDD.cjs","sourcesContent":[null,"import { z } from 'zod/v4';\nimport { ActivitySchemaError } from '../errors.js';\nimport type { ValidationError } from '../types/activity.js';\nimport type { XAPIStatement } from '../types/xapi.js';\n\nconst UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n// Minimal IRI/URI check: a scheme followed by ':'.\nconst IRI = /^[a-z][a-z0-9+.-]*:/i;\n\nconst langMap = z.record(z.string(), z.string());\nconst extensions = z.record(z.string(), z.unknown());\n\nconst actorSchema = z\n .object({\n objectType: z.literal('Agent'),\n name: z.string().optional(),\n mbox: z\n .string()\n .regex(/^mailto:/, 'mbox must be a mailto IRI')\n .optional(),\n account: z.object({ homePage: z.string(), name: z.string() }).optional(),\n })\n .refine((actor) => actor.mbox !== undefined || actor.account !== undefined, {\n error: 'actor must be identified by an mbox or an account',\n });\n\nconst statementSchema = z.object({\n id: z.string().regex(UUID_V4, 'id must be a UUID v4'),\n actor: actorSchema,\n verb: z.object({\n id: z.string().regex(IRI, 'verb.id must be an IRI'),\n display: langMap,\n }),\n object: z.object({\n objectType: z.literal('Activity'),\n id: z.string().regex(IRI, 'object.id must be an IRI'),\n definition: z\n .object({\n name: langMap.optional(),\n description: langMap.optional(),\n type: z.string().optional(),\n interactionType: z.string().optional(),\n correctResponsesPattern: z.array(z.string()).optional(),\n choices: z.array(z.object({ id: z.string(), description: langMap.optional() })).optional(),\n extensions: extensions.optional(),\n })\n .optional(),\n }),\n result: z\n .object({\n // xAPI 1.0.3 permits scaled in [-1, 1]; the SDK only emits [0, 1].\n score: z\n .object({\n scaled: z.number().min(-1).max(1),\n raw: z.number().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n })\n .optional(),\n success: z.boolean().optional(),\n completion: z.boolean().optional(),\n duration: z.string().regex(/^P/, 'duration must be an ISO 8601 duration').optional(),\n response: z.string().optional(),\n extensions: extensions.optional(),\n })\n .optional(),\n context: z\n .object({\n platform: z.string().optional(),\n language: z.string().optional(),\n contextActivities: z\n .object({\n parent: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n grouping: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n category: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n other: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n })\n .optional(),\n extensions: extensions.optional(),\n })\n .optional(),\n timestamp: z\n .string()\n .refine((value) => !Number.isNaN(Date.parse(value)), 'timestamp must be ISO 8601'),\n version: z.literal('1.0.3'),\n});\n\n/** True when running under `NODE_ENV=production`, safe in any environment. */\nfunction isProduction(): boolean {\n const g = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return g.process?.env?.NODE_ENV === 'production';\n}\n\n/**\n * Validates a constructed {@link XAPIStatement} against the xAPI 1.0.3\n * structural contract.\n *\n * In development a structural failure throws (caught early); in production it\n * logs a warning and returns (the statement is still sent — see the design's\n * Error Handling table). Uses a `zod/v4` schema rather than `ajv` + an\n * external JSON Schema to keep `lk-core` dependency-free.\n *\n * NOTE: `ActivitySchemaError` is reused here per the task spec; its\n * `activityType` field carries the sentinel `'xAPIStatement'`. A dedicated\n * `XAPIValidationError` would be semantically cleaner — flagged for review.\n */\nexport function validateXAPIStatement(statement: XAPIStatement): void {\n const result = statementSchema.safeParse(statement);\n if (result.success) {\n return;\n }\n\n const errors: ValidationError[] = result.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n }));\n\n if (isProduction()) {\n console.warn('[learning-kit] Invalid xAPI statement (sent anyway):', errors);\n return;\n }\n\n throw new ActivitySchemaError('xAPIStatement', errors);\n}\n","/**\n * The set of xAPI verbs emitted by SDK activities, keyed by a stable\n * identifier mapped to its canonical xAPI verb IRI (xAPI 1.0.3 / ADL registry).\n */\nexport const XAPIVerb = {\n ANSWERED: 'http://adlnet.gov/expapi/verbs/answered',\n COMPLETED: 'http://adlnet.gov/expapi/verbs/completed',\n EXPERIENCED: 'http://adlnet.gov/expapi/verbs/experienced',\n INTERACTED: 'http://adlnet.gov/expapi/verbs/interacted',\n ATTEMPTED: 'http://adlnet.gov/expapi/verbs/attempted',\n PASSED: 'http://adlnet.gov/expapi/verbs/passed',\n FAILED: 'http://adlnet.gov/expapi/verbs/failed',\n WATCHED: 'https://w3id.org/xapi/video/verbs/watched',\n /**\n * Emitted for deferred-grading submissions (e.g. written-response): the\n * learner has submitted work whose grade does not exist yet, so `answered`\n * (which implies a scored response) would be wrong. xAPI 1.0.3 defines no\n * canonical \"submit\" verb; the Activity Streams 1.0 IRI is the established\n * community choice (design decision recorded per Task 25.4).\n */\n SUBMITTED: 'http://activitystrea.ms/schema/1.0/submit',\n /**\n * Emitted when an asynchronous grader produces a grade for work that was\n * previously only SUBMITTED. Distinct from `answered`, which asserts the\n * grade existed at submission time — here the learner acted earlier and the\n * grade arrived later, often from a different actor (an AI or a teacher).\n */\n SCORED: 'http://adlnet.gov/expapi/verbs/scored',\n} as const;\n\n/** Union of the valid `XAPIVerb` keys. */\nexport type XAPIVerbKey = keyof typeof XAPIVerb;\n\n/**\n * Default `en-US` display label for each verb, used to populate\n * `XAPIVerbObject.display` when the builder resolves a verb key.\n */\nexport const XAPI_VERB_DISPLAY: Record<XAPIVerbKey, Record<string, string>> = {\n ANSWERED: { 'en-US': 'answered' },\n COMPLETED: { 'en-US': 'completed' },\n EXPERIENCED: { 'en-US': 'experienced' },\n INTERACTED: { 'en-US': 'interacted' },\n ATTEMPTED: { 'en-US': 'attempted' },\n PASSED: { 'en-US': 'passed' },\n FAILED: { 'en-US': 'failed' },\n WATCHED: { 'en-US': 'watched' },\n SUBMITTED: { 'en-US': 'submitted' },\n SCORED: { 'en-US': 'scored' },\n};\n","import { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ScoringResult } from '../types/activity.js';\nimport type {\n XAPIActor,\n XAPIContext,\n XAPIObject,\n XAPIResult,\n XAPIStatement,\n} from '../types/xapi.js';\nimport { validateXAPIStatement } from './validators.js';\nimport { XAPI_VERB_DISPLAY, XAPIVerb, type XAPIVerbKey } from './verbs.js';\n\n/** Caller-supplied activity object descriptor (mapped to an xAPI Activity). */\nexport interface XAPIObjectParams {\n /** Activity IRI. */\n id: string;\n name?: Record<string, string>;\n description?: Record<string, string>;\n /** Activity type IRI. */\n type?: string;\n /** xAPI cmi.interaction type (e.g. `choice`, `fill-in`, `long-fill-in`). */\n interactionType?: string;\n /** Correct-responses patterns, per the xAPI CRP format. */\n correctResponsesPattern?: string[];\n /** For choice-family interactions: the available components. */\n choices?: Array<{ id: string; description?: Record<string, string> }>;\n}\n\n/** Parameters for the generic {@link xAPIBuilder.buildStatement}. */\nexport interface XAPIStatementParams {\n actor: XAPIActor;\n verb: XAPIVerbKey;\n object: XAPIObjectParams;\n result?: XAPIResult;\n context?: XAPIContext;\n}\n\n/** Parameters for {@link xAPIBuilder.buildAnsweredStatement} (verb = ANSWERED). */\nexport interface AnsweredStatementParams {\n actor: XAPIActor;\n object: XAPIObjectParams;\n scoringResult: ScoringResult;\n timeSpentMs: number;\n /** Serialized learner response string. */\n response?: string;\n context?: XAPIContext;\n resultExtensions?: Record<string, unknown>;\n}\n\n/**\n * Parameters for {@link xAPIBuilder.buildSubmittedStatement} (verb =\n * SUBMITTED — deferred-grading submissions). Carries NO score, success, or\n * completion: the grade does not exist yet (Req 22.7).\n */\nexport interface SubmittedStatementParams {\n actor: XAPIActor;\n object: XAPIObjectParams;\n timeSpentMs: number;\n /** Serialized learner response string (e.g. the submitted text). */\n response?: string;\n context?: XAPIContext;\n resultExtensions?: Record<string, unknown>;\n}\n\n/** Parameters for {@link xAPIBuilder.buildCompletedStatement} (verb = COMPLETED). */\nexport interface CompletedStatementParams {\n actor: XAPIActor;\n object: XAPIObjectParams;\n scoringResult?: ScoringResult;\n timeSpentMs: number;\n context?: XAPIContext;\n resultExtensions?: Record<string, unknown>;\n}\n\n/**\n * Converts a millisecond duration to an ISO 8601 seconds string with\n * centisecond precision (`PT1.23S`), per the xAPI 1.0.3 recommendation of\n * 0.01-second accuracy. Sub-second durations are preserved (previously any\n * duration under 500 ms collapsed to `PT0S`). Negative inputs (clock skew)\n * clamp to zero — a negative ISO duration is invalid.\n */\nfunction msToIsoDuration(ms: number): string {\n return `PT${(Math.round(Math.max(0, ms) / 10) / 100).toFixed(2)}S`;\n}\n\n/**\n * UUID v4 that works outside secure contexts. `crypto.randomUUID` is\n * SecureContext-gated (undefined on plain-http LAN/staging origins), and a\n * statement is built at SUBMIT time — throwing here would lose the learner's\n * answer. `crypto.getRandomValues` is NOT gated, so the fallback still emits\n * a spec-valid v4 UUID (the statement validator enforces the v4 format).\n */\nfunction uuidv4(): string {\n const c = (\n globalThis as {\n crypto?: { randomUUID?: () => string; getRandomValues?: (a: Uint8Array) => Uint8Array };\n }\n ).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (c?.getRandomValues) {\n c.getRandomValues(bytes);\n } else {\n for (let i = 0; i < 16; i += 1) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** Builds the xAPI Activity object, including `definition` only when populated. */\nfunction buildObject(params: XAPIObjectParams): XAPIObject {\n const definition: NonNullable<XAPIObject['definition']> = {\n ...(params.name !== undefined ? { name: params.name } : {}),\n ...(params.description !== undefined ? { description: params.description } : {}),\n ...(params.type !== undefined ? { type: params.type } : {}),\n ...(params.interactionType !== undefined ? { interactionType: params.interactionType } : {}),\n ...(params.correctResponsesPattern !== undefined\n ? { correctResponsesPattern: params.correctResponsesPattern }\n : {}),\n ...(params.choices !== undefined ? { choices: params.choices } : {}),\n };\n return {\n objectType: 'Activity',\n id: params.id,\n ...(Object.keys(definition).length > 0 ? { definition } : {}),\n };\n}\n\n/**\n * Maps a {@link ScoringResult} + timing to an {@link XAPIResult} per the\n * normative mapping in the design document.\n */\nfunction buildResult(\n timeSpentMs: number,\n scoringResult: ScoringResult | undefined,\n resultExtensions: Record<string, unknown> | undefined,\n response: string | undefined,\n): XAPIResult {\n return {\n completion: true,\n duration: msToIsoDuration(timeSpentMs),\n ...(scoringResult !== undefined\n ? {\n score: {\n scaled: scoringResult.score,\n raw: scoringResult.score,\n min: 0,\n max: scoringResult.maxScore,\n },\n success: scoringResult.passed,\n }\n : {}),\n ...(response !== undefined ? { response } : {}),\n ...(resultExtensions !== undefined ? { extensions: resultExtensions } : {}),\n };\n}\n\n/**\n * Constructs xAPI 1.0.3 Statements. Every call stamps a fresh UUID v4 `id`,\n * an ISO 8601 `timestamp`, and `version: '1.0.3'`. Not pure by design —\n * statements are unique events.\n */\nexport const xAPIBuilder = {\n buildStatement(params: XAPIStatementParams): XAPIStatement {\n const statement: XAPIStatement = {\n id: uuidv4(),\n actor: params.actor,\n verb: {\n id: XAPIVerb[params.verb],\n display: XAPI_VERB_DISPLAY[params.verb],\n },\n object: buildObject(params.object),\n ...(params.result !== undefined ? { result: params.result } : {}),\n ...(params.context !== undefined ? { context: params.context } : {}),\n timestamp: new Date().toISOString(),\n version: '1.0.3',\n };\n // Design xAPIBuilder step 4: validate every statement (throws in dev,\n // warns in prod). All build*Statement helpers route through here.\n validateXAPIStatement(statement);\n return statement;\n },\n\n buildAnsweredStatement(params: AnsweredStatementParams): XAPIStatement {\n return this.buildStatement({\n actor: params.actor,\n verb: 'ANSWERED',\n object: params.object,\n result: buildResult(\n params.timeSpentMs,\n params.scoringResult,\n params.resultExtensions,\n params.response,\n ),\n ...(params.context !== undefined ? { context: params.context } : {}),\n });\n },\n\n /**\n * Builds a statement for a deferred-grading submission (e.g. a written\n * response). Verb is SUBMITTED and the result deliberately omits `score`,\n * `success`, and `completion` — none of them exist until the asynchronous\n * grader runs; only `duration`, `response`, and extensions are recorded.\n */\n buildSubmittedStatement(params: SubmittedStatementParams): XAPIStatement {\n return this.buildStatement({\n actor: params.actor,\n verb: 'SUBMITTED',\n object: params.object,\n result: {\n duration: msToIsoDuration(params.timeSpentMs),\n ...(params.response !== undefined ? { response: params.response } : {}),\n ...(params.resultExtensions !== undefined ? { extensions: params.resultExtensions } : {}),\n },\n ...(params.context !== undefined ? { context: params.context } : {}),\n });\n },\n\n buildCompletedStatement(params: CompletedStatementParams): XAPIStatement {\n return this.buildStatement({\n actor: params.actor,\n verb: 'COMPLETED',\n object: params.object,\n result: buildResult(\n params.timeSpentMs,\n params.scoringResult,\n params.resultExtensions,\n undefined,\n ),\n ...(params.context !== undefined ? { context: params.context } : {}),\n });\n },\n};\n\n/**\n * Builds the xAPI `object.definition` interop fields for an activity from its\n * REGISTERED descriptor, rather than having every renderer hand-roll them.\n *\n * `ActivityTypeDescriptor.interop` declares the activity-type IRI, the\n * cmi.interaction type and how to derive `correctResponsesPattern`; before\n * this, those fields had no reader anywhere and each component rebuilt the\n * same strings inline — the same \"declared but never used\" defect the SDK\n * fixed elsewhere. Reading them here also means a consumer-registered type\n * gets correct interop for free.\n *\n * Returns an empty object for an unregistered type or one that declares no\n * interop, so it is always safe to spread.\n */\nexport function xapiDefinitionFor(data: { type: string }): Partial<XAPIObjectParams> {\n const descriptor = getActivityTypeDescriptor(data.type);\n const interop = descriptor?.interop;\n if (interop === undefined) {\n return {};\n }\n const pattern = interop.correctResponsesPattern?.(data);\n return {\n ...(interop.xapiActivityTypeIri !== undefined ? { type: interop.xapiActivityTypeIri } : {}),\n ...(interop.xapiInteractionType !== undefined\n ? { interactionType: interop.xapiInteractionType }\n : {}),\n ...(pattern !== undefined && pattern.length > 0 ? { correctResponsesPattern: pattern } : {}),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/chunk-FT7SAC3X.cjs","../src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AAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACI,MAAA;AACL,IAAA;AACH,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACI,MAAA;AACL,IAAA;AACH,EAAA;AAEA,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACI,MAAA;AACL,IAAA;AACH,EAAA;AACF;AAgBgB;AACR,EAAA;AACA,EAAA;AACF,EAAA;AACF,IAAA;AACF,EAAA;AACM,EAAA;AACC,EAAA;AACD,IAAA;AACA,IAAA;AAGA,IAAA;AACN,EAAA;AACF;AHRU;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/learning-kit/learning-kit/packages/lk-core/dist/chunk-FT7SAC3X.cjs","sourcesContent":[null,"import { z } from 'zod/v4';\nimport { ActivitySchemaError } from '../errors.js';\nimport type { ValidationError } from '../types/activity.js';\nimport type { XAPIStatement } from '../types/xapi.js';\n\nconst UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n// Minimal IRI/URI check: a scheme followed by ':'.\nconst IRI = /^[a-z][a-z0-9+.-]*:/i;\n\nconst langMap = z.record(z.string(), z.string());\nconst extensions = z.record(z.string(), z.unknown());\n\nconst actorSchema = z\n .object({\n objectType: z.literal('Agent'),\n name: z.string().optional(),\n mbox: z\n .string()\n .regex(/^mailto:/, 'mbox must be a mailto IRI')\n .optional(),\n account: z.object({ homePage: z.string(), name: z.string() }).optional(),\n })\n .refine((actor) => actor.mbox !== undefined || actor.account !== undefined, {\n error: 'actor must be identified by an mbox or an account',\n });\n\nconst statementSchema = z.object({\n id: z.string().regex(UUID_V4, 'id must be a UUID v4'),\n actor: actorSchema,\n verb: z.object({\n id: z.string().regex(IRI, 'verb.id must be an IRI'),\n display: langMap,\n }),\n object: z.object({\n objectType: z.literal('Activity'),\n id: z.string().regex(IRI, 'object.id must be an IRI'),\n definition: z\n .object({\n name: langMap.optional(),\n description: langMap.optional(),\n type: z.string().optional(),\n interactionType: z.string().optional(),\n correctResponsesPattern: z.array(z.string()).optional(),\n choices: z.array(z.object({ id: z.string(), description: langMap.optional() })).optional(),\n extensions: extensions.optional(),\n })\n .optional(),\n }),\n result: z\n .object({\n // xAPI 1.0.3 permits scaled in [-1, 1]; the SDK only emits [0, 1].\n score: z\n .object({\n scaled: z.number().min(-1).max(1),\n raw: z.number().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n })\n .optional(),\n success: z.boolean().optional(),\n completion: z.boolean().optional(),\n duration: z.string().regex(/^P/, 'duration must be an ISO 8601 duration').optional(),\n response: z.string().optional(),\n extensions: extensions.optional(),\n })\n .optional(),\n context: z\n .object({\n platform: z.string().optional(),\n language: z.string().optional(),\n contextActivities: z\n .object({\n parent: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n grouping: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n category: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n other: z\n .array(z.object({ objectType: z.literal('Activity'), id: z.string() }))\n .optional(),\n })\n .optional(),\n extensions: extensions.optional(),\n })\n .optional(),\n timestamp: z\n .string()\n .refine((value) => !Number.isNaN(Date.parse(value)), 'timestamp must be ISO 8601'),\n version: z.literal('1.0.3'),\n});\n\n/** True when running under `NODE_ENV=production`, safe in any environment. */\nfunction isProduction(): boolean {\n const g = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return g.process?.env?.NODE_ENV === 'production';\n}\n\n/**\n * Validates a constructed {@link XAPIStatement} against the xAPI 1.0.3\n * structural contract.\n *\n * In development a structural failure throws (caught early); in production it\n * logs a warning and returns (the statement is still sent — see the design's\n * Error Handling table). Uses a `zod/v4` schema rather than `ajv` + an\n * external JSON Schema to keep `lk-core` dependency-free.\n *\n * NOTE: `ActivitySchemaError` is reused here per the task spec; its\n * `activityType` field carries the sentinel `'xAPIStatement'`. A dedicated\n * `XAPIValidationError` would be semantically cleaner — flagged for review.\n */\nexport function validateXAPIStatement(statement: XAPIStatement): void {\n const result = statementSchema.safeParse(statement);\n if (result.success) {\n return;\n }\n\n const errors: ValidationError[] = result.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n }));\n\n if (isProduction()) {\n console.warn('[learning-kit] Invalid xAPI statement (sent anyway):', errors);\n return;\n }\n\n throw new ActivitySchemaError('xAPIStatement', errors);\n}\n","/**\n * The set of xAPI verbs emitted by SDK activities, keyed by a stable\n * identifier mapped to its canonical xAPI verb IRI (xAPI 1.0.3 / ADL registry).\n */\nexport const XAPIVerb = {\n ANSWERED: 'http://adlnet.gov/expapi/verbs/answered',\n COMPLETED: 'http://adlnet.gov/expapi/verbs/completed',\n EXPERIENCED: 'http://adlnet.gov/expapi/verbs/experienced',\n INTERACTED: 'http://adlnet.gov/expapi/verbs/interacted',\n ATTEMPTED: 'http://adlnet.gov/expapi/verbs/attempted',\n PASSED: 'http://adlnet.gov/expapi/verbs/passed',\n FAILED: 'http://adlnet.gov/expapi/verbs/failed',\n WATCHED: 'https://w3id.org/xapi/video/verbs/watched',\n /**\n * Emitted for deferred-grading submissions (e.g. written-response): the\n * learner has submitted work whose grade does not exist yet, so `answered`\n * (which implies a scored response) would be wrong. xAPI 1.0.3 defines no\n * canonical \"submit\" verb; the Activity Streams 1.0 IRI is the established\n * community choice (design decision recorded per Task 25.4).\n */\n SUBMITTED: 'http://activitystrea.ms/schema/1.0/submit',\n /**\n * Emitted when an asynchronous grader produces a grade for work that was\n * previously only SUBMITTED. Distinct from `answered`, which asserts the\n * grade existed at submission time — here the learner acted earlier and the\n * grade arrived later, often from a different actor (an AI or a teacher).\n */\n SCORED: 'http://adlnet.gov/expapi/verbs/scored',\n} as const;\n\n/** Union of the valid `XAPIVerb` keys. */\nexport type XAPIVerbKey = keyof typeof XAPIVerb;\n\n/**\n * Default `en-US` display label for each verb, used to populate\n * `XAPIVerbObject.display` when the builder resolves a verb key.\n */\nexport const XAPI_VERB_DISPLAY: Record<XAPIVerbKey, Record<string, string>> = {\n ANSWERED: { 'en-US': 'answered' },\n COMPLETED: { 'en-US': 'completed' },\n EXPERIENCED: { 'en-US': 'experienced' },\n INTERACTED: { 'en-US': 'interacted' },\n ATTEMPTED: { 'en-US': 'attempted' },\n PASSED: { 'en-US': 'passed' },\n FAILED: { 'en-US': 'failed' },\n WATCHED: { 'en-US': 'watched' },\n SUBMITTED: { 'en-US': 'submitted' },\n SCORED: { 'en-US': 'scored' },\n};\n","import { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ScoringResult } from '../types/activity.js';\nimport type {\n XAPIActor,\n XAPIContext,\n XAPIObject,\n XAPIResult,\n XAPIStatement,\n} from '../types/xapi.js';\nimport { validateXAPIStatement } from './validators.js';\nimport { XAPI_VERB_DISPLAY, XAPIVerb, type XAPIVerbKey } from './verbs.js';\n\n/** Caller-supplied activity object descriptor (mapped to an xAPI Activity). */\nexport interface XAPIObjectParams {\n /** Activity IRI. */\n id: string;\n name?: Record<string, string>;\n description?: Record<string, string>;\n /** Activity type IRI. */\n type?: string;\n /** xAPI cmi.interaction type (e.g. `choice`, `fill-in`, `long-fill-in`). */\n interactionType?: string;\n /** Correct-responses patterns, per the xAPI CRP format. */\n correctResponsesPattern?: string[];\n /** For choice-family interactions: the available components. */\n choices?: Array<{ id: string; description?: Record<string, string> }>;\n}\n\n/** Parameters for the generic {@link xAPIBuilder.buildStatement}. */\nexport interface XAPIStatementParams {\n actor: XAPIActor;\n verb: XAPIVerbKey;\n object: XAPIObjectParams;\n result?: XAPIResult;\n context?: XAPIContext;\n}\n\n/** Parameters for {@link xAPIBuilder.buildAnsweredStatement} (verb = ANSWERED). */\nexport interface AnsweredStatementParams {\n actor: XAPIActor;\n object: XAPIObjectParams;\n scoringResult: ScoringResult;\n timeSpentMs: number;\n /** Serialized learner response string. */\n response?: string;\n context?: XAPIContext;\n resultExtensions?: Record<string, unknown>;\n}\n\n/**\n * Parameters for {@link xAPIBuilder.buildSubmittedStatement} (verb =\n * SUBMITTED — deferred-grading submissions). Carries NO score, success, or\n * completion: the grade does not exist yet (Req 22.7).\n */\nexport interface SubmittedStatementParams {\n actor: XAPIActor;\n object: XAPIObjectParams;\n timeSpentMs: number;\n /** Serialized learner response string (e.g. the submitted text). */\n response?: string;\n context?: XAPIContext;\n resultExtensions?: Record<string, unknown>;\n}\n\n/** Parameters for {@link xAPIBuilder.buildCompletedStatement} (verb = COMPLETED). */\nexport interface CompletedStatementParams {\n actor: XAPIActor;\n object: XAPIObjectParams;\n scoringResult?: ScoringResult;\n timeSpentMs: number;\n context?: XAPIContext;\n resultExtensions?: Record<string, unknown>;\n}\n\n/**\n * Converts a millisecond duration to an ISO 8601 seconds string with\n * centisecond precision (`PT1.23S`), per the xAPI 1.0.3 recommendation of\n * 0.01-second accuracy. Sub-second durations are preserved (previously any\n * duration under 500 ms collapsed to `PT0S`). Negative inputs (clock skew)\n * clamp to zero — a negative ISO duration is invalid.\n */\nfunction msToIsoDuration(ms: number): string {\n return `PT${(Math.round(Math.max(0, ms) / 10) / 100).toFixed(2)}S`;\n}\n\n/**\n * UUID v4 that works outside secure contexts. `crypto.randomUUID` is\n * SecureContext-gated (undefined on plain-http LAN/staging origins), and a\n * statement is built at SUBMIT time — throwing here would lose the learner's\n * answer. `crypto.getRandomValues` is NOT gated, so the fallback still emits\n * a spec-valid v4 UUID (the statement validator enforces the v4 format).\n */\nfunction uuidv4(): string {\n const c = (\n globalThis as {\n crypto?: { randomUUID?: () => string; getRandomValues?: (a: Uint8Array) => Uint8Array };\n }\n ).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (c?.getRandomValues) {\n c.getRandomValues(bytes);\n } else {\n for (let i = 0; i < 16; i += 1) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** Builds the xAPI Activity object, including `definition` only when populated. */\nfunction buildObject(params: XAPIObjectParams): XAPIObject {\n const definition: NonNullable<XAPIObject['definition']> = {\n ...(params.name !== undefined ? { name: params.name } : {}),\n ...(params.description !== undefined ? { description: params.description } : {}),\n ...(params.type !== undefined ? { type: params.type } : {}),\n ...(params.interactionType !== undefined ? { interactionType: params.interactionType } : {}),\n ...(params.correctResponsesPattern !== undefined\n ? { correctResponsesPattern: params.correctResponsesPattern }\n : {}),\n ...(params.choices !== undefined ? { choices: params.choices } : {}),\n };\n return {\n objectType: 'Activity',\n id: params.id,\n ...(Object.keys(definition).length > 0 ? { definition } : {}),\n };\n}\n\n/**\n * Maps a {@link ScoringResult} + timing to an {@link XAPIResult} per the\n * normative mapping in the design document.\n */\nfunction buildResult(\n timeSpentMs: number,\n scoringResult: ScoringResult | undefined,\n resultExtensions: Record<string, unknown> | undefined,\n response: string | undefined,\n): XAPIResult {\n return {\n completion: true,\n duration: msToIsoDuration(timeSpentMs),\n ...(scoringResult !== undefined\n ? {\n score: {\n scaled: scoringResult.score,\n raw: scoringResult.score,\n min: 0,\n max: scoringResult.maxScore,\n },\n success: scoringResult.passed,\n }\n : {}),\n ...(response !== undefined ? { response } : {}),\n ...(resultExtensions !== undefined ? { extensions: resultExtensions } : {}),\n };\n}\n\n/**\n * Constructs xAPI 1.0.3 Statements. Every call stamps a fresh UUID v4 `id`,\n * an ISO 8601 `timestamp`, and `version: '1.0.3'`. Not pure by design —\n * statements are unique events.\n */\nexport const xAPIBuilder = {\n buildStatement(params: XAPIStatementParams): XAPIStatement {\n const statement: XAPIStatement = {\n id: uuidv4(),\n actor: params.actor,\n verb: {\n id: XAPIVerb[params.verb],\n display: XAPI_VERB_DISPLAY[params.verb],\n },\n object: buildObject(params.object),\n ...(params.result !== undefined ? { result: params.result } : {}),\n ...(params.context !== undefined ? { context: params.context } : {}),\n timestamp: new Date().toISOString(),\n version: '1.0.3',\n };\n // Design xAPIBuilder step 4: validate every statement (throws in dev,\n // warns in prod). All build*Statement helpers route through here.\n validateXAPIStatement(statement);\n return statement;\n },\n\n buildAnsweredStatement(params: AnsweredStatementParams): XAPIStatement {\n return this.buildStatement({\n actor: params.actor,\n verb: 'ANSWERED',\n object: params.object,\n result: buildResult(\n params.timeSpentMs,\n params.scoringResult,\n params.resultExtensions,\n params.response,\n ),\n ...(params.context !== undefined ? { context: params.context } : {}),\n });\n },\n\n /**\n * Builds a statement for a deferred-grading submission (e.g. a written\n * response). Verb is SUBMITTED and the result deliberately omits `score`,\n * `success`, and `completion` — none of them exist until the asynchronous\n * grader runs; only `duration`, `response`, and extensions are recorded.\n */\n buildSubmittedStatement(params: SubmittedStatementParams): XAPIStatement {\n return this.buildStatement({\n actor: params.actor,\n verb: 'SUBMITTED',\n object: params.object,\n result: {\n duration: msToIsoDuration(params.timeSpentMs),\n ...(params.response !== undefined ? { response: params.response } : {}),\n ...(params.resultExtensions !== undefined ? { extensions: params.resultExtensions } : {}),\n },\n ...(params.context !== undefined ? { context: params.context } : {}),\n });\n },\n\n buildCompletedStatement(params: CompletedStatementParams): XAPIStatement {\n return this.buildStatement({\n actor: params.actor,\n verb: 'COMPLETED',\n object: params.object,\n result: buildResult(\n params.timeSpentMs,\n params.scoringResult,\n params.resultExtensions,\n undefined,\n ),\n ...(params.context !== undefined ? { context: params.context } : {}),\n });\n },\n};\n\n/**\n * Builds the xAPI `object.definition` interop fields for an activity from its\n * REGISTERED descriptor, rather than having every renderer hand-roll them.\n *\n * `ActivityTypeDescriptor.interop` declares the activity-type IRI, the\n * cmi.interaction type and how to derive `correctResponsesPattern`; before\n * this, those fields had no reader anywhere and each component rebuilt the\n * same strings inline — the same \"declared but never used\" defect the SDK\n * fixed elsewhere. Reading them here also means a consumer-registered type\n * gets correct interop for free.\n *\n * Returns an empty object for an unregistered type or one that declares no\n * interop, so it is always safe to spread.\n */\nexport function xapiDefinitionFor(data: { type: string }): Partial<XAPIObjectParams> {\n const descriptor = getActivityTypeDescriptor(data.type);\n const interop = descriptor?.interop;\n if (interop === undefined) {\n return {};\n }\n const pattern = interop.correctResponsesPattern?.(data);\n return {\n ...(interop.xapiActivityTypeIri !== undefined ? { type: interop.xapiActivityTypeIri } : {}),\n ...(interop.xapiInteractionType !== undefined\n ? { interactionType: interop.xapiInteractionType }\n : {}),\n ...(pattern !== undefined && pattern.length > 0 ? { correctResponsesPattern: pattern } : {}),\n };\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ActivitySchemaError,
|
|
3
3
|
getActivityTypeDescriptor
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-XKKKWKRH.js";
|
|
5
5
|
|
|
6
6
|
// src/xapi/validators.ts
|
|
7
7
|
import { z } from "zod/v4";
|
|
@@ -266,4 +266,4 @@ export {
|
|
|
266
266
|
xAPIBuilder,
|
|
267
267
|
xapiDefinitionFor
|
|
268
268
|
};
|
|
269
|
-
//# sourceMappingURL=chunk-
|
|
269
|
+
//# sourceMappingURL=chunk-PYP3HCRQ.js.map
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
var _chunkXONKWL6Dcjs = require('./chunk-XONKWL6D.cjs');
|
|
7
9
|
|
|
8
10
|
// src/scoring/rounding.ts
|
|
9
11
|
var EPSILON = 1e-9;
|
|
@@ -248,8 +250,47 @@ function composeAssessmentScore(sections, policy) {
|
|
|
248
250
|
};
|
|
249
251
|
}
|
|
250
252
|
|
|
253
|
+
// src/scoring/dictation/chars.ts
|
|
254
|
+
function diffDictationChars(reference, attempt) {
|
|
255
|
+
const referencePoints = Array.from(reference);
|
|
256
|
+
const attemptPoints = Array.from(attempt);
|
|
257
|
+
return _chunkXONKWL6Dcjs.alignSequences.call(void 0, referencePoints, attemptPoints).map(
|
|
258
|
+
({ step, referenceIndex, attemptIndex }) => {
|
|
259
|
+
if (step === _chunkXONKWL6Dcjs.STEP.missing) {
|
|
260
|
+
return { op: "missing", reference: referencePoints[referenceIndex], attempt: "" };
|
|
261
|
+
}
|
|
262
|
+
if (step === _chunkXONKWL6Dcjs.STEP.extra) {
|
|
263
|
+
return { op: "extra", reference: "", attempt: attemptPoints[attemptIndex] };
|
|
264
|
+
}
|
|
265
|
+
const referencePoint = referencePoints[referenceIndex];
|
|
266
|
+
const attemptPoint = attemptPoints[attemptIndex];
|
|
267
|
+
return {
|
|
268
|
+
op: referencePoint === attemptPoint ? "equal" : "substitute",
|
|
269
|
+
reference: referencePoint,
|
|
270
|
+
attempt: attemptPoint
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
|
|
251
276
|
// src/scoring/index.ts
|
|
252
277
|
var DEFAULT_PASS_THRESHOLD = 0.7;
|
|
278
|
+
var ROUNDING_MODES = ["half-up", "half-even", "floor", "ceil"];
|
|
279
|
+
var MAX_ROUNDING_DP = 15;
|
|
280
|
+
function roundingOf(options) {
|
|
281
|
+
const rounding = _optionalChain([options, 'optionalAccess', _ => _.rounding]);
|
|
282
|
+
if (rounding === void 0 || rounding === null) {
|
|
283
|
+
return void 0;
|
|
284
|
+
}
|
|
285
|
+
const { mode, dp } = rounding;
|
|
286
|
+
if (!ROUNDING_MODES.includes(mode) || typeof dp !== "number" || !Number.isInteger(dp) || dp < 0 || dp > MAX_ROUNDING_DP) {
|
|
287
|
+
const describe = (value) => typeof value === "string" ? JSON.stringify(value) : typeof value === "number" || value === void 0 ? String(value) : typeof value === "object" ? "an object" : `a ${typeof value}`;
|
|
288
|
+
throw new RangeError(
|
|
289
|
+
`Invalid rounding policy (mode ${describe(mode)}, dp ${describe(dp)}): expected { mode: 'half-up' | 'half-even' | 'floor' | 'ceil', dp: a whole number from 0 to ${MAX_ROUNDING_DP} }.`
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
return { mode, dp };
|
|
293
|
+
}
|
|
253
294
|
function computePassThreshold(activityData, score2, rounding) {
|
|
254
295
|
const threshold = _nullishCoalesce(activityData.passThreshold, () => ( DEFAULT_PASS_THRESHOLD));
|
|
255
296
|
return rounding === void 0 ? score2 >= threshold : gte(score2, threshold, rounding);
|
|
@@ -264,27 +305,29 @@ function selectFeedback(activityData, passed) {
|
|
|
264
305
|
}
|
|
265
306
|
return _nullishCoalesce((passed ? feedback.correct : feedback.incorrect), () => ( null));
|
|
266
307
|
}
|
|
267
|
-
function score(activityType, activityData, learnerResponse) {
|
|
268
|
-
const
|
|
308
|
+
function score(activityType, activityData, learnerResponse, options) {
|
|
309
|
+
const rounding = roundingOf(options);
|
|
310
|
+
const descriptor = _chunkXONKWL6Dcjs.getActivityTypeDescriptor.call(void 0, activityType);
|
|
269
311
|
if (descriptor === void 0) {
|
|
270
|
-
throw new (0,
|
|
312
|
+
throw new (0, _chunkXONKWL6Dcjs.UnknownActivityTypeError)(String(activityType));
|
|
271
313
|
}
|
|
272
314
|
if (descriptor.scoring.kind === "deferred") {
|
|
273
|
-
throw new (0,
|
|
315
|
+
throw new (0, _chunkXONKWL6Dcjs.DeferredScoringError)(descriptor.type);
|
|
274
316
|
}
|
|
275
317
|
if (isRedacted(activityData)) {
|
|
276
|
-
throw new (0,
|
|
318
|
+
throw new (0, _chunkXONKWL6Dcjs.RedactedScoringError)(descriptor.type);
|
|
277
319
|
}
|
|
278
320
|
const result = descriptor.scoring.score(activityData, learnerResponse);
|
|
279
321
|
if (!Number.isFinite(result.score)) {
|
|
280
|
-
throw new (0,
|
|
322
|
+
throw new (0, _chunkXONKWL6Dcjs.RedactedScoringError)(descriptor.type);
|
|
281
323
|
}
|
|
282
|
-
const passed = computePassThreshold(activityData, result.score);
|
|
324
|
+
const passed = computePassThreshold(activityData, result.score, rounding);
|
|
283
325
|
return { ...result, passed, feedback: _nullishCoalesce(result.feedback, () => ( selectFeedback(activityData, passed))) };
|
|
284
326
|
}
|
|
285
|
-
function evaluate(data, response) {
|
|
327
|
+
function evaluate(data, response, options) {
|
|
328
|
+
const rounding = roundingOf(options);
|
|
286
329
|
const type = data.type;
|
|
287
|
-
const descriptor = typeof type === "string" ?
|
|
330
|
+
const descriptor = typeof type === "string" ? _chunkXONKWL6Dcjs.getActivityTypeDescriptor.call(void 0, type) : void 0;
|
|
288
331
|
if (descriptor === void 0) {
|
|
289
332
|
return {
|
|
290
333
|
status: "unscorable",
|
|
@@ -293,7 +336,7 @@ function evaluate(data, response) {
|
|
|
293
336
|
};
|
|
294
337
|
}
|
|
295
338
|
if (descriptor.scoring.kind === "deferred") {
|
|
296
|
-
const partial = _optionalChain([descriptor, 'access',
|
|
339
|
+
const partial = _optionalChain([descriptor, 'access', _2 => _2.scoring, 'access', _3 => _3.partial, 'optionalCall', _4 => _4(data, response)]);
|
|
297
340
|
return {
|
|
298
341
|
status: "deferred",
|
|
299
342
|
reason: descriptor.scoring.reason,
|
|
@@ -316,7 +359,7 @@ function evaluate(data, response) {
|
|
|
316
359
|
maxScore: result.maxScore
|
|
317
360
|
};
|
|
318
361
|
}
|
|
319
|
-
const passed = computePassThreshold(data, result.score);
|
|
362
|
+
const passed = computePassThreshold(data, result.score, rounding);
|
|
320
363
|
return {
|
|
321
364
|
status: "scored",
|
|
322
365
|
score: result.score,
|
|
@@ -339,5 +382,6 @@ function evaluate(data, response) {
|
|
|
339
382
|
|
|
340
383
|
|
|
341
384
|
|
|
342
|
-
|
|
343
|
-
|
|
385
|
+
|
|
386
|
+
exports.roundGrade = roundGrade; exports.gte = gte; exports.classifyBand = classifyBand; exports.composeAssessmentScore = composeAssessmentScore; exports.diffDictationChars = diffDictationChars; exports.DEFAULT_PASS_THRESHOLD = DEFAULT_PASS_THRESHOLD; exports.computePassThreshold = computePassThreshold; exports.score = score; exports.evaluate = evaluate; exports.gradeFromRubric = gradeFromRubric; exports.outcomeFromGrade = outcomeFromGrade; exports.hasGrade = hasGrade;
|
|
387
|
+
//# sourceMappingURL=chunk-UHQVIC3P.cjs.map
|