@astl/engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +202 -0
  3. package/README.md +40 -2
  4. package/dist/analyse.d.ts +68 -0
  5. package/dist/analyse.d.ts.map +1 -0
  6. package/dist/analyse.js +1179 -0
  7. package/dist/analyse.js.map +1 -0
  8. package/dist/checker.d.ts +19 -0
  9. package/dist/checker.d.ts.map +1 -0
  10. package/dist/checker.js +103 -0
  11. package/dist/checker.js.map +1 -0
  12. package/dist/compile.d.ts +16 -0
  13. package/dist/compile.d.ts.map +1 -0
  14. package/dist/compile.js +329 -0
  15. package/dist/compile.js.map +1 -0
  16. package/dist/conformance.d.ts +35 -0
  17. package/dist/conformance.d.ts.map +1 -0
  18. package/dist/conformance.js +101 -0
  19. package/dist/conformance.js.map +1 -0
  20. package/dist/engine.d.ts +13 -0
  21. package/dist/engine.d.ts.map +1 -0
  22. package/dist/engine.js +231 -0
  23. package/dist/engine.js.map +1 -0
  24. package/dist/grade.d.ts +9 -0
  25. package/dist/grade.d.ts.map +1 -0
  26. package/dist/grade.js +192 -0
  27. package/dist/grade.js.map +1 -0
  28. package/dist/guard.d.ts +45 -0
  29. package/dist/guard.d.ts.map +1 -0
  30. package/dist/guard.js +327 -0
  31. package/dist/guard.js.map +1 -0
  32. package/dist/help.d.ts +32 -0
  33. package/dist/help.d.ts.map +1 -0
  34. package/dist/help.js +120 -0
  35. package/dist/help.js.map +1 -0
  36. package/dist/html.d.ts +31 -0
  37. package/dist/html.d.ts.map +1 -0
  38. package/dist/html.js +246 -0
  39. package/dist/html.js.map +1 -0
  40. package/dist/ids.d.ts +35 -0
  41. package/dist/ids.d.ts.map +1 -0
  42. package/dist/ids.js +126 -0
  43. package/dist/ids.js.map +1 -0
  44. package/dist/index.d.ts +13 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +10 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/kit/attributes.d.ts +6 -0
  49. package/dist/kit/attributes.d.ts.map +1 -0
  50. package/dist/kit/attributes.js +20 -0
  51. package/dist/kit/attributes.js.map +1 -0
  52. package/dist/kit/index.d.ts +43 -0
  53. package/dist/kit/index.d.ts.map +1 -0
  54. package/dist/kit/index.js +118 -0
  55. package/dist/kit/index.js.map +1 -0
  56. package/dist/limits.d.ts +17 -0
  57. package/dist/limits.d.ts.map +1 -0
  58. package/dist/limits.js +173 -0
  59. package/dist/limits.js.map +1 -0
  60. package/dist/messages/en.json +48 -0
  61. package/dist/messages/pl.json +48 -0
  62. package/dist/messages.d.ts +4 -0
  63. package/dist/messages.d.ts.map +1 -0
  64. package/dist/messages.js +9 -0
  65. package/dist/messages.js.map +1 -0
  66. package/dist/round.d.ts +3 -0
  67. package/dist/round.d.ts.map +1 -0
  68. package/dist/round.js +5 -0
  69. package/dist/round.js.map +1 -0
  70. package/dist/slot-kinds.d.ts +58 -0
  71. package/dist/slot-kinds.d.ts.map +1 -0
  72. package/dist/slot-kinds.js +151 -0
  73. package/dist/slot-kinds.js.map +1 -0
  74. package/dist/text.d.ts +23 -0
  75. package/dist/text.d.ts.map +1 -0
  76. package/dist/text.js +236 -0
  77. package/dist/text.js.map +1 -0
  78. package/package.json +39 -3
  79. package/src/analyse.ts +1396 -0
  80. package/src/checker.ts +132 -0
  81. package/src/compile.ts +394 -0
  82. package/src/conformance.ts +120 -0
  83. package/src/engine.ts +274 -0
  84. package/src/grade.ts +229 -0
  85. package/src/guard.ts +356 -0
  86. package/src/help.ts +141 -0
  87. package/src/html.ts +274 -0
  88. package/src/ids.ts +144 -0
  89. package/src/index.ts +12 -0
  90. package/src/kit/attributes.ts +21 -0
  91. package/src/kit/index.ts +140 -0
  92. package/src/limits.ts +153 -0
  93. package/src/messages/en.json +48 -0
  94. package/src/messages/pl.json +48 -0
  95. package/src/messages.ts +9 -0
  96. package/src/round.ts +4 -0
  97. package/src/slot-kinds.ts +212 -0
  98. package/src/text.ts +234 -0
package/src/guard.ts ADDED
@@ -0,0 +1,356 @@
1
+ /**
2
+ * The view guard. A definition's `toView` must return the manifest's public shape and nothing else, and must not carry
3
+ * the element's secrets. The built-in definitions satisfy it by construction; it exists because third-party
4
+ * definitions are code the engine does not control, and their bugs must not reach students.
5
+ */
6
+ import {
7
+ type AttributeSpec,
8
+ allAttributes,
9
+ BLOCK_TAGS,
10
+ CAPTION_TAG,
11
+ CONTENT_ATTRIBUTES,
12
+ type ComponentManifest,
13
+ type ElementNode,
14
+ FIGURE_TAG,
15
+ INLINE_TAGS,
16
+ isOpaqueId,
17
+ LANGUAGE_TAG_PATTERN,
18
+ type Node,
19
+ TAG_ATTRIBUTES,
20
+ URL_ATTRIBUTES,
21
+ type UrlPolicy,
22
+ } from '@astl/core';
23
+ import { cleanStyle } from '@astl/core/declarations';
24
+ import { isHtmlWhitespace } from './html.js';
25
+
26
+ export interface GuardContext {
27
+ /** The opaque id the view element must carry. */
28
+ readonly id: string;
29
+ readonly urlPolicy: UrlPolicy;
30
+ }
31
+
32
+ const DIRECTIONS: ReadonlySet<string> = new Set(['ltr', 'rtl', 'auto']);
33
+
34
+ /**
35
+ * Throws (a definition bug) unless `view` is an allowed public view of the sanitised `source`: `id` and `v` first,
36
+ * public and derived attributes only, declared public children only, rich inline text only inside `inline`
37
+ * children (a rich block: rich content with its declared children in it), text only where allowed, no event
38
+ * handlers, URLs through the URL policy, opaque ids only, and none of the element's private values.
39
+ */
40
+ export function guardView(
41
+ view: ElementNode,
42
+ source: ElementNode,
43
+ manifest: ComponentManifest,
44
+ ctx: GuardContext,
45
+ ): void {
46
+ const fail = (why: string): never => {
47
+ throw new Error(`Component definition ${manifest.tag}: toView ${why}`);
48
+ };
49
+ if (view?.type !== 'element' || view.tag !== manifest.tag) fail(`must return a <${manifest.tag}> element`);
50
+ const names = Object.keys(view.attrs);
51
+ if (names[0] !== 'id' || view.attrs.id !== ctx.id) fail('must write id = context.opaque() first');
52
+ if (names[1] !== 'v' || view.attrs.v !== String(manifest.version)) {
53
+ fail(`must write v="${manifest.version}" second`);
54
+ }
55
+ const checkAttributes = (el: ElementNode, specs: readonly AttributeSpec[], from: number): void => {
56
+ for (const [name, value] of Object.entries(el.attrs).slice(from)) {
57
+ const problem = attributeProblem(el.tag, name, value, find(specs, name), ctx.urlPolicy);
58
+ if (problem !== null) fail(problem);
59
+ }
60
+ };
61
+ checkAttributes(view, allAttributes(manifest), 2);
62
+ const checkChild = (child: ElementNode): void => {
63
+ const spec = manifest.children.find((c) => c.tag === child.tag);
64
+ if (spec === undefined) fail(`writes <${child.tag}>, which is not a declared child`);
65
+ else if (spec.visibility === 'private') fail(`keeps the private child <${child.tag}>`);
66
+ else {
67
+ checkAttributes(child, spec.attributes, 0);
68
+ if (spec.content === 'text') {
69
+ if (child.children.some((n) => n.type === 'element'))
70
+ fail(`writes elements inside text-only <${child.tag}>`);
71
+ } else {
72
+ const problem = contentProblem(child.children, ctx.urlPolicy);
73
+ if (problem !== null) fail(`${problem} inside <${child.tag}>`);
74
+ }
75
+ }
76
+ };
77
+ if (manifest.content === 'flow') {
78
+ // Rich content as the sanitiser keeps it, with the declared children as the only custom elements.
79
+ const problem = contentProblem(view.children, ctx.urlPolicy, { manifest, child: checkChild });
80
+ if (problem !== null) fail(problem);
81
+ } else {
82
+ for (const child of view.children) {
83
+ if (child.type === 'element') checkChild(child);
84
+ else if (!isHtmlWhitespace(child.value)) fail('writes text directly inside the element');
85
+ }
86
+ }
87
+ const [leak] = findLeaks(source, view, manifest);
88
+ if (leak !== undefined) fail(`puts private data (${leak.what}) into the view`);
89
+ }
90
+
91
+ function find(specs: readonly AttributeSpec[], name: string): AttributeSpec | undefined {
92
+ return specs.find((s) => s.name === name);
93
+ }
94
+
95
+ function attributeProblem(
96
+ tag: string,
97
+ name: string,
98
+ value: string,
99
+ spec: AttributeSpec | undefined,
100
+ urlPolicy: UrlPolicy,
101
+ ): string | null {
102
+ if (/^on/i.test(name)) return `writes the event handler ${name} on <${tag}>`;
103
+ if (name === 'style') {
104
+ return cleanStyle(value).removed.length === 0 ? null : `writes a style the format refuses on <${tag}>`;
105
+ }
106
+ if (CONTENT_ATTRIBUTES.has(name)) {
107
+ const valid = name === 'lang' ? LANGUAGE_TAG_PATTERN.test(value) : DIRECTIONS.has(value);
108
+ return valid ? null : `writes an invalid ${name} on <${tag}>`;
109
+ }
110
+ if (spec === undefined || spec.visibility === 'private') {
111
+ return `writes the attribute ${name} on <${tag}>, which is not public or derived`;
112
+ }
113
+ if (spec.type === 'id' && !isOpaqueId(value)) return `writes the source id ${value} on <${tag}>`;
114
+ if (spec.type === 'url' && !urlPolicy(value, { tag, attribute: name })) {
115
+ return `writes a blocked URL in ${name} on <${tag}>`;
116
+ }
117
+ return null;
118
+ }
119
+
120
+ /** A rich block's content: its type and how to check one of its declared (inline) children. */
121
+ interface Flow {
122
+ readonly manifest: ComponentManifest;
123
+ readonly child: (el: ElementNode) => void;
124
+ }
125
+
126
+ /**
127
+ * The rich-text allow-list as the sanitiser applies it (a picture keeps its `src` and `alt`): inline tags, and in a
128
+ * rich block's content (`flow`) also its declared children and, outside inline tags, blocks and figures.
129
+ */
130
+ function contentProblem(
131
+ nodes: readonly Node[],
132
+ urlPolicy: UrlPolicy,
133
+ flow?: Flow,
134
+ blocks: boolean = flow !== undefined,
135
+ ): string | null {
136
+ for (const node of nodes) {
137
+ if (node.type === 'text') continue;
138
+ if (flow?.manifest.children.some((c) => c.tag === node.tag)) {
139
+ flow.child(node);
140
+ continue;
141
+ }
142
+ const inline = INLINE_TAGS.has(node.tag);
143
+ const block = BLOCK_TAGS.has(node.tag) || node.tag === FIGURE_TAG || node.tag === CAPTION_TAG;
144
+ if (!inline && !(blocks && block)) return `writes <${node.tag}>`;
145
+ const extra = Object.hasOwn(TAG_ATTRIBUTES, node.tag) ? (TAG_ATTRIBUTES[node.tag] ?? []) : [];
146
+ for (const [name, value] of Object.entries(node.attrs)) {
147
+ if (/^on/i.test(name)) return `writes the event handler ${name} on <${node.tag}>`;
148
+ if (CONTENT_ATTRIBUTES.has(name)) {
149
+ const problem = attributeProblem(node.tag, name, value, undefined, urlPolicy);
150
+ if (problem !== null) return problem;
151
+ } else if (!extra.includes(name)) {
152
+ return `writes the attribute ${name} on <${node.tag}>`;
153
+ } else if (name === URL_ATTRIBUTES[node.tag] && !urlPolicy(value, { tag: node.tag, attribute: name })) {
154
+ return `writes a blocked URL in ${name} on <${node.tag}>`;
155
+ }
156
+ }
157
+ if (node.tag === 'img' && !(Object.hasOwn(node.attrs, 'src') && Object.hasOwn(node.attrs, 'alt'))) {
158
+ return 'writes <img> without src or alt';
159
+ }
160
+ const nested = contentProblem(node.children, urlPolicy, flow, blocks && !inline);
161
+ if (nested !== null) return nested;
162
+ }
163
+ return null;
164
+ }
165
+
166
+ export interface LeakFinding {
167
+ readonly kind: 'value' | 'attribute' | 'child';
168
+ /** What leaks: `@answer`, `astl-alt`, `astl-option@correct`. */
169
+ readonly what: string;
170
+ /** The leaked value, for value leaks. */
171
+ readonly value?: string;
172
+ }
173
+
174
+ /**
175
+ * Private data of one component found in its view element: private attributes or children that are present, and
176
+ * secret values (private strings and private child texts) that appear in the view's text or free-text attributes.
177
+ * A value the author also wrote in the element's public content is not a leak.
178
+ */
179
+ export function findLeaks(
180
+ source: ElementNode,
181
+ view: ElementNode,
182
+ manifest: ComponentManifest,
183
+ ): LeakFinding[] {
184
+ const findings: LeakFinding[] = [];
185
+ for (const spec of allAttributes(manifest)) {
186
+ if (spec.visibility === 'private' && Object.hasOwn(view.attrs, spec.name)) {
187
+ findings.push({ kind: 'attribute', what: `@${spec.name}` });
188
+ }
189
+ }
190
+ for (const el of descendants(view)) {
191
+ const spec = manifest.children.find((c) => c.tag === el.tag);
192
+ if (spec === undefined) continue;
193
+ if (spec.visibility === 'private') findings.push({ kind: 'child', what: el.tag });
194
+ for (const attr of spec.attributes) {
195
+ if (attr.visibility === 'private' && Object.hasOwn(el.attrs, attr.name)) {
196
+ findings.push({ kind: 'attribute', what: `${el.tag}@${attr.name}` });
197
+ }
198
+ }
199
+ }
200
+ const viewText = wordsOf([view]);
201
+ const viewValues = freeTextValues(view, manifest);
202
+ const publicText = wordsOf(publicContent(source, manifest));
203
+ const publicValues = freeTextValues(source, manifest, true);
204
+ for (const { what, value } of secretValues(source, manifest)) {
205
+ const inValues = viewValues.includes(value) && !publicValues.includes(value);
206
+ const inText = containsToken(viewText, value) && !containsToken(publicText, value);
207
+ if (inValues || inText) findings.push({ kind: 'value', what, value });
208
+ }
209
+ return findings;
210
+ }
211
+
212
+ const isChild = (node: Node, manifest: ComponentManifest, visibility: 'public' | 'private'): boolean =>
213
+ node.type === 'element' && manifest.children.some((c) => c.tag === node.tag && c.visibility === visibility);
214
+
215
+ /** What the author wrote for students: the public children, or a rich block's content without private children. */
216
+ function publicContent(source: ElementNode, manifest: ComponentManifest): Node[] {
217
+ if (manifest.content !== 'flow') return source.children.filter((c) => isChild(c, manifest, 'public'));
218
+ const strip = (nodes: readonly Node[]): Node[] =>
219
+ nodes.flatMap((n): Node[] =>
220
+ n.type === 'text'
221
+ ? [n]
222
+ : isChild(n, manifest, 'private')
223
+ ? []
224
+ : [{ ...n, children: strip(n.children) }],
225
+ );
226
+ return strip(source.children);
227
+ }
228
+
229
+ /** Element descendants, without recursion. */
230
+ export function descendants(el: ElementNode): ElementNode[] {
231
+ const out: ElementNode[] = [];
232
+ const stack: Node[] = [...el.children].reverse();
233
+ for (let node = stack.pop(); node !== undefined; node = stack.pop()) {
234
+ if (node.type !== 'element') continue;
235
+ out.push(node);
236
+ for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i] as Node);
237
+ }
238
+ return out;
239
+ }
240
+
241
+ /**
242
+ * All text of the nodes, one space between text nodes, so tokens never join across elements. A picture's `alt` is text
243
+ * too (screen readers read it out), and so are the addresses of pictures and links, as written and decoded: a picture
244
+ * loads by itself, so a value in its address reaches whoever serves it.
245
+ */
246
+ export function wordsOf(nodes: readonly Node[]): string {
247
+ const parts: string[] = [];
248
+ const stack: Node[] = [...nodes].reverse();
249
+ for (let node = stack.pop(); node !== undefined; node = stack.pop()) {
250
+ if (node.type === 'text') parts.push(node.value);
251
+ else {
252
+ if (node.tag === 'img' && Object.hasOwn(node.attrs, 'alt')) parts.push(node.attrs.alt ?? '');
253
+ const url = URL_ATTRIBUTES[node.tag];
254
+ if (url !== undefined && Object.hasOwn(node.attrs, url))
255
+ parts.push(...addressWords(node.attrs[url] ?? ''));
256
+ for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i] as Node);
257
+ }
258
+ }
259
+ return parts.join(' ');
260
+ }
261
+
262
+ /** An address as written and with its escapes decoded (`%63at` and `+` for a space), where it decodes. */
263
+ function addressWords(url: string): string[] {
264
+ try {
265
+ const decoded = decodeURIComponent(url.replace(/\+/g, ' '));
266
+ return decoded === url ? [url] : [url, decoded];
267
+ } catch {
268
+ return [url];
269
+ }
270
+ }
271
+
272
+ /** Values of free-text attributes (`string`, `url`) of an element and its declared children. */
273
+ function freeTextValues(el: ElementNode, manifest: ComponentManifest, publicOnly = false): string[] {
274
+ const keep = (spec: AttributeSpec | undefined) =>
275
+ spec !== undefined &&
276
+ (spec.type === 'string' || spec.type === 'url') &&
277
+ (publicOnly ? spec.visibility === 'public' : spec.visibility !== 'private');
278
+ const out: string[] = [];
279
+ const specs = allAttributes(manifest);
280
+ for (const [name, value] of Object.entries(el.attrs)) if (keep(find(specs, name))) out.push(value);
281
+ for (const child of descendants(el)) {
282
+ const spec = manifest.children.find((c) => c.tag === child.tag);
283
+ if (spec === undefined || (publicOnly && spec.visibility !== 'public')) continue;
284
+ for (const [name, value] of Object.entries(child.attrs))
285
+ if (keep(find(spec.attributes, name))) out.push(value);
286
+ }
287
+ return out;
288
+ }
289
+
290
+ /**
291
+ * Secrets of a source element: its type's private string attributes (answers) and private child texts
292
+ * (alternatives). Common settings (`scoring`, `points`) and private numbers, enums and booleans are not secrets,
293
+ * and short values such as `2` would match by chance.
294
+ */
295
+ function secretValues(el: ElementNode, manifest: ComponentManifest): { what: string; value: string }[] {
296
+ const out: { what: string; value: string }[] = [];
297
+ const add = (what: string, value: string | undefined): void => {
298
+ const v = value?.trim() ?? '';
299
+ if (v !== '') out.push({ what, value: v });
300
+ };
301
+ const secret = (spec: AttributeSpec) => spec.visibility === 'private' && spec.type === 'string';
302
+ for (const spec of manifest.attributes) {
303
+ if (secret(spec) && Object.hasOwn(el.attrs, spec.name)) add(`@${spec.name}`, el.attrs[spec.name]);
304
+ }
305
+ // Anywhere inside: a rich block's children sit in its text.
306
+ for (const child of descendants(el)) {
307
+ const spec = manifest.children.find((c) => c.tag === child.tag);
308
+ if (spec === undefined) continue;
309
+ if (spec.visibility === 'private') add(child.tag, wordsOf(child.children));
310
+ for (const attr of spec.attributes) {
311
+ if (secret(attr) && Object.hasOwn(child.attrs, attr.name)) {
312
+ add(`${child.tag}@${attr.name}`, child.attrs[attr.name]);
313
+ }
314
+ }
315
+ }
316
+ return out;
317
+ }
318
+
319
+ const WORD = /^[\p{L}\p{N}]$/u;
320
+
321
+ function isWordAt(text: string, index: number, before: boolean): boolean {
322
+ if (index < 0 || index >= text.length) return false;
323
+ let at = index;
324
+ // Step back to the start of a surrogate pair that ends at `index`.
325
+ const unit = text.charCodeAt(at);
326
+ if (before && unit >= 0xdc00 && unit <= 0xdfff && at > 0) {
327
+ const high = text.charCodeAt(at - 1);
328
+ if (high >= 0xd800 && high <= 0xdbff) at--;
329
+ }
330
+ return WORD.test(String.fromCodePoint(text.codePointAt(at) ?? 0));
331
+ }
332
+
333
+ /**
334
+ * Whether `needle` occurs in `haystack` as a whole token (not inside a longer word or number). Knuth-Morris-Pratt,
335
+ * so the time stays linear for any input; a regular expression would be quadratic on repetitive text.
336
+ */
337
+ export function containsToken(haystack: string, needle: string): boolean {
338
+ const m = needle.length;
339
+ if (m === 0 || m > haystack.length) return false;
340
+ const fail = new Int32Array(m);
341
+ for (let i = 1, k = 0; i < m; i++) {
342
+ while (k > 0 && needle[i] !== needle[k]) k = fail[k - 1] ?? 0;
343
+ if (needle[i] === needle[k]) k++;
344
+ fail[i] = k;
345
+ }
346
+ for (let i = 0, k = 0; i < haystack.length; i++) {
347
+ while (k > 0 && haystack[i] !== needle[k]) k = fail[k - 1] ?? 0;
348
+ if (haystack[i] === needle[k]) k++;
349
+ if (k === m) {
350
+ const start = i - m + 1;
351
+ if (!isWordAt(haystack, start - 1, true) && !isWordAt(haystack, i + 1, false)) return true;
352
+ k = fail[k - 1] ?? 0;
353
+ }
354
+ }
355
+ return false;
356
+ }
package/src/help.ts ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Help over an answer key: the feedback texts and explanations a result brings, and the next hint of an interaction
3
+ * or a page. Pure functions, shared by `localChecker` and the grading endpoint, so both answer the same.
4
+ */
5
+ import {
6
+ type AnswerKey,
7
+ type AttemptPolicy,
8
+ type ElementHelp,
9
+ type Feedback,
10
+ type FeedbackVariant,
11
+ type GradeResult,
12
+ type GroupVerdict,
13
+ type HelpMoment,
14
+ type HintResponse,
15
+ helpPolicy,
16
+ type KeyHelp,
17
+ type ResultHelp,
18
+ } from '@astl/core';
19
+
20
+ /**
21
+ * Whether a check or the hand-in brings feedback texts and explanations under a policy: after a check when the policy
22
+ * says `check`; at the hand-in when it says `check` or `submit`, and only with the answers (`reveal: 'answers'`), as a
23
+ * feedback text names the right answer as surely as a solution does.
24
+ */
25
+ export function helpShown(
26
+ policy: AttemptPolicy,
27
+ moment: 'check' | 'submit',
28
+ ): { readonly feedback: boolean; readonly explanations: boolean } {
29
+ const help = helpPolicy(policy);
30
+ const shown = (when: HelpMoment): boolean =>
31
+ moment === 'check' ? when === 'check' : when !== 'never' && policy.reveal === 'answers';
32
+ return { feedback: shown(help.feedback), explanations: shown(help.explanations) };
33
+ }
34
+
35
+ /** The view attributes (`HELP_ATTRIBUTES`) for what an element or page offers: only those with something to say. */
36
+ export function helpAttributes(help: ElementHelp): Record<string, string> {
37
+ const out: Record<string, string> = {};
38
+ if (help.hints.length > 0) out.hints = help.hints.map(String).join(' ');
39
+ if (help.explanation) out.explanation = '';
40
+ if (help.feedback.length > 0) out.feedback = help.feedback.join(' ');
41
+ return out;
42
+ }
43
+
44
+ const feedbackVariant = (verdict: GroupVerdict): FeedbackVariant =>
45
+ verdict === 'empty' ? 'omitted' : verdict;
46
+
47
+ const own = (key: AnswerKey, id: string): KeyHelp | undefined =>
48
+ key.help !== undefined && Object.hasOwn(key.help, id) ? key.help[id] : undefined;
49
+
50
+ /** The view element of every group (the component of its slots), by group id. */
51
+ function elementsOf(key: AnswerKey): Map<string, string> {
52
+ const out = new Map<string, string>();
53
+ for (const group of key.groups) {
54
+ const first = group.slots[0];
55
+ const element =
56
+ first !== undefined && Object.hasOwn(key.slots, first) ? key.slots[first]?.group : undefined;
57
+ if (element !== undefined) out.set(group.id, element);
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** Whether `id` is a graded view element of the key: what a check of one interaction may name. */
63
+ export function isGradedElement(key: AnswerKey, id: string): boolean {
64
+ return [...elementsOf(key).values()].includes(id);
65
+ }
66
+
67
+ /**
68
+ * One verdict for several groups (an element graded in parts, a page): nothing answered is `empty`, everything right
69
+ * `correct`, something right `partial`, else `incorrect`.
70
+ */
71
+ function overall(verdicts: readonly GroupVerdict[]): GroupVerdict {
72
+ if (verdicts.every((v) => v === 'empty')) return 'empty';
73
+ if (verdicts.every((v) => v === 'correct')) return 'correct';
74
+ return verdicts.some((v) => v === 'correct' || v === 'partial') ? 'partial' : 'incorrect';
75
+ }
76
+
77
+ /** The text for a verdict; a partial one without its own text gets the `incorrect` one. */
78
+ function feedbackFor(help: KeyHelp, verdict: GroupVerdict): Feedback | null {
79
+ const variant = feedbackVariant(verdict);
80
+ const html = help.feedback[variant] ?? (variant === 'partial' ? help.feedback.incorrect : undefined);
81
+ return typeof html === 'string' ? { variant, html } : null;
82
+ }
83
+
84
+ /**
85
+ * The help a result brings, for what it graded: each graded element's feedback for its verdict and its explanation,
86
+ * and, unless one element was checked (`element`), each graded page's own, its feedback picked by the page's overall
87
+ * verdict. `shown` says which of the two the policy gives now (`helpShown`). Empty parts are left out.
88
+ */
89
+ export function resultHelp(
90
+ key: AnswerKey,
91
+ result: GradeResult,
92
+ shown: { readonly feedback: boolean; readonly explanations: boolean },
93
+ element?: string,
94
+ ): ResultHelp {
95
+ if (key.help === undefined || (!shown.feedback && !shown.explanations)) return {};
96
+ const elements = elementsOf(key);
97
+ const pageOf = new Map(key.groups.map((g) => [g.id, g.page]));
98
+ const byElement = new Map<string, GroupVerdict[]>();
99
+ const byPage = new Map<string, GroupVerdict[]>();
100
+ for (const group of result.groups) {
101
+ const add = (map: Map<string, GroupVerdict[]>, id: string | undefined) => {
102
+ if (id !== undefined) map.set(id, [...(map.get(id) ?? []), group.verdict]);
103
+ };
104
+ add(byElement, elements.get(group.id));
105
+ add(byPage, pageOf.get(group.id));
106
+ }
107
+ const feedback: Record<string, Feedback> = {};
108
+ const explanations: Record<string, string> = {};
109
+ const give = (id: string, verdicts: readonly GroupVerdict[]) => {
110
+ const help = own(key, id);
111
+ if (help === undefined) return;
112
+ const text = shown.feedback ? feedbackFor(help, overall(verdicts)) : null;
113
+ if (text !== null) feedback[id] = text;
114
+ if (shown.explanations && typeof help.explanation === 'string') explanations[id] = help.explanation;
115
+ };
116
+ for (const [id, verdicts] of byElement) give(id, verdicts);
117
+ if (element === undefined) {
118
+ for (const page of Object.keys(result.pages)) {
119
+ const verdicts = byPage.get(page);
120
+ if (verdicts !== undefined) give(page, verdicts);
121
+ }
122
+ }
123
+ return {
124
+ ...(Object.keys(feedback).length === 0 ? {} : { feedback }),
125
+ ...(Object.keys(explanations).length === 0 ? {} : { explanations }),
126
+ };
127
+ }
128
+
129
+ /** How many hints an element or a page has. */
130
+ export function hintCount(key: AnswerKey, id: string): number {
131
+ const hints = own(key, id)?.hints;
132
+ return Array.isArray(hints) ? hints.length : 0;
133
+ }
134
+
135
+ /** The hint after the first `used` ones of an element or a page; null when there is none. */
136
+ export function nextHint(key: AnswerKey, id: string, used: number): HintResponse | null {
137
+ const hints = own(key, id)?.hints ?? [];
138
+ const hint = Number.isInteger(used) && used >= 0 ? hints[used] : undefined;
139
+ if (hint === undefined) return null;
140
+ return { html: hint.html, index: used, left: hints.length - used - 1, cost: hint.cost };
141
+ }