@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/dist/grade.js ADDED
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Grading: pure and synchronous. Answers are untrusted (malformed = unanswered); a malformed key is a host error and
3
+ * throws a TypeError.
4
+ */
5
+ import { FLAG_SELECTED, fitsAnswer, groupMax, isAnswerKey, SCORING_RULES, } from '@astl/core';
6
+ import { round6 } from './round.js';
7
+ function assertKey(key) {
8
+ const valid = isAnswerKey(key) &&
9
+ key.pages.every((p) => typeof p === 'string') &&
10
+ key.groups.every((g) => typeof g === 'object' &&
11
+ g !== null &&
12
+ typeof g.id === 'string' &&
13
+ typeof g.page === 'string' &&
14
+ SCORING_RULES.includes(g.rule) &&
15
+ typeof g.points === 'number' &&
16
+ Number.isFinite(g.points) &&
17
+ g.points >= 0 &&
18
+ Array.isArray(g.slots) &&
19
+ g.slots.every((s) => typeof s === 'string'));
20
+ if (!valid)
21
+ throw new TypeError('Invalid answer key');
22
+ }
23
+ function slotOf(key, id, kinds) {
24
+ const slot = Object.hasOwn(key.slots, id) ? key.slots[id] : undefined;
25
+ if (slot === undefined)
26
+ throw new TypeError(`Invalid answer key: unknown slot ${id}`);
27
+ const kind = kinds.get(slot.kind);
28
+ if (kind === undefined)
29
+ throw new TypeError(`Invalid answer key: slot kind "${slot.kind}" is not registered`);
30
+ // Only group slots get here: an open slot (an ungraded kind) is stored for the teacher and belongs to no group.
31
+ if (kind.graded === false)
32
+ throw new TypeError(`Invalid answer key: slot ${id} is of the ungraded kind "${slot.kind}"`);
33
+ if (typeof slot.key !== 'object' || slot.key === null || !kind.isKey(slot.key)) {
34
+ throw new TypeError(`Invalid answer key: slot ${id} has an invalid ${slot.kind} key`);
35
+ }
36
+ return { slot, kind };
37
+ }
38
+ /**
39
+ * The answer for a slot, or null when it is unanswered (missing, not a string, empty or longer than its kind allows,
40
+ * in code points).
41
+ */
42
+ function answerOf(answers, id, kind) {
43
+ const value = Object.hasOwn(answers, id) ? answers[id] : undefined;
44
+ return typeof value === 'string' && value !== '' && fitsAnswer(value, kind) ? value : null;
45
+ }
46
+ /** The view element a group belongs to: the component of its slots (`KeySlot.group`). */
47
+ function elementOf(key, group) {
48
+ const first = group.slots[0];
49
+ return first !== undefined && Object.hasOwn(key.slots, first) ? key.slots[first]?.group : undefined;
50
+ }
51
+ function groupsFor(key, options) {
52
+ const { page, element } = options;
53
+ return key.groups.filter((g) => (page === undefined || g.page === page) && (element === undefined || elementOf(key, g) === element));
54
+ }
55
+ /**
56
+ * The fraction of its maximum each group loses for the hints used (`GradeOptions.hintsUsed`): the costs of the first
57
+ * n hints of its element and of its page. Counts that are not positive integers use nothing.
58
+ */
59
+ function hintCosts(key, used) {
60
+ const spent = (id) => {
61
+ if (id === undefined || !Object.hasOwn(used, id))
62
+ return 0;
63
+ const n = used[id];
64
+ if (typeof n !== 'number' || !Number.isInteger(n) || n <= 0)
65
+ return 0;
66
+ const hints = key.help !== undefined && Object.hasOwn(key.help, id) ? key.help[id]?.hints : undefined;
67
+ if (hints === undefined)
68
+ return 0;
69
+ if (!Array.isArray(hints) || !hints.every((h) => isCost(h?.cost))) {
70
+ throw new TypeError(`Invalid answer key: the hints of ${id} have invalid costs`);
71
+ }
72
+ return hints.slice(0, n).reduce((sum, h) => sum + h.cost, 0);
73
+ };
74
+ return (group) => spent(elementOf(key, group)) + spent(group.page);
75
+ }
76
+ const isCost = (x) => typeof x === 'number' && x >= 0 && x <= 1;
77
+ function gradeGroup(group, key, answers, kinds) {
78
+ const n = group.slots.length;
79
+ let answered = 0;
80
+ let correct = 0;
81
+ const outcomes = [];
82
+ for (const id of group.slots) {
83
+ const { slot, kind } = slotOf(key, id, kinds);
84
+ const lang = typeof slot.key.lang === 'string' ? slot.key.lang : key.lang;
85
+ const answer = answerOf(answers, id, slot.kind);
86
+ let isAnswered;
87
+ let isCorrect;
88
+ if (kind.selection) {
89
+ // Selection slots: an unselected flag is right when it should stay unselected.
90
+ isAnswered = answer === FLAG_SELECTED;
91
+ isCorrect = isAnswered === kind.isCorrect(slot.key, FLAG_SELECTED, { lang });
92
+ }
93
+ else {
94
+ isAnswered = answer !== null;
95
+ isCorrect = answer !== null && kind.isCorrect(slot.key, answer, { lang });
96
+ }
97
+ if (isAnswered)
98
+ answered++;
99
+ if (isCorrect)
100
+ correct++;
101
+ outcomes.push({ id, answered: isAnswered, correct: isCorrect });
102
+ }
103
+ const points = group.points;
104
+ const max = groupMax(group.rule, points, n);
105
+ let score = 0;
106
+ let verdict;
107
+ if (answered === 0) {
108
+ verdict = 'empty';
109
+ }
110
+ else {
111
+ const all = correct === n;
112
+ if (group.rule === 'all-correct') {
113
+ score = all ? points : 0;
114
+ verdict = all ? 'correct' : 'incorrect';
115
+ }
116
+ else {
117
+ score = group.rule === 'per-slot' ? points * correct : (points * correct) / n;
118
+ verdict = all ? 'correct' : correct === 0 ? 'incorrect' : 'partial';
119
+ }
120
+ }
121
+ const visible = {};
122
+ // Multi-slot all-correct groups show only the group verdict, never which slot is wrong.
123
+ if (verdict !== 'empty' && !(group.rule === 'all-correct' && n > 1)) {
124
+ for (const o of outcomes)
125
+ if (o.answered)
126
+ visible[o.id] = o.correct ? 'correct' : 'incorrect';
127
+ }
128
+ return { result: { id: group.id, verdict, score, max }, visible };
129
+ }
130
+ export function gradeKey(key, answers, options, kinds) {
131
+ assertKey(key);
132
+ const input = typeof answers === 'object' && answers !== null ? answers : {};
133
+ const groups = groupsFor(key, options);
134
+ // A check of one element reports its page's score of that element only.
135
+ const graded = new Set(groups.map((g) => g.page));
136
+ const pageIds = options.element !== undefined
137
+ ? key.pages.filter((p) => graded.has(p))
138
+ : options.page === undefined
139
+ ? key.pages
140
+ : key.pages.filter((p) => p === options.page);
141
+ const costOf = options.hintsUsed === undefined ? null : hintCosts(key, options.hintsUsed);
142
+ const pageTotals = new Map(pageIds.map((p) => [p, { score: 0, max: 0 }]));
143
+ const slots = {};
144
+ const results = [];
145
+ const counts = { correct: 0, partial: 0, incorrect: 0, empty: 0 };
146
+ let score = 0;
147
+ let max = 0;
148
+ for (const group of groups) {
149
+ const outcome = gradeGroup(group, key, input, kinds);
150
+ const cost = costOf?.(group) ?? 0;
151
+ // Hints lower the score, never the verdict: the answer is still right.
152
+ const lowered = round6(Math.max(0, outcome.result.score - cost * outcome.result.max));
153
+ const result = cost > 0 ? { ...outcome.result, score: lowered } : outcome.result;
154
+ const visible = outcome.visible;
155
+ results.push(result);
156
+ Object.assign(slots, visible);
157
+ counts[result.verdict]++;
158
+ score += result.score;
159
+ max += result.max;
160
+ const total = pageTotals.get(group.page);
161
+ if (total !== undefined) {
162
+ total.score += result.score;
163
+ total.max += result.max;
164
+ }
165
+ }
166
+ const pages = {};
167
+ for (const [id, total] of pageTotals)
168
+ pages[id] = { score: round6(total.score), max: round6(total.max) };
169
+ return {
170
+ score: round6(score),
171
+ max: round6(max),
172
+ correct: groups.length > 0 && counts.correct === groups.length,
173
+ slots,
174
+ groups: results,
175
+ pages,
176
+ counts: { ...counts, total: groups.length },
177
+ };
178
+ }
179
+ export function solutionOf(key, options, kinds) {
180
+ assertKey(key);
181
+ const out = {};
182
+ for (const group of groupsFor(key, options)) {
183
+ for (const id of group.slots) {
184
+ const { slot, kind } = slotOf(key, id, kinds);
185
+ const value = kind.solution(slot.key);
186
+ if (value !== '')
187
+ out[id] = value;
188
+ }
189
+ }
190
+ return out;
191
+ }
192
+ //# sourceMappingURL=grade.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grade.js","sourceRoot":"","sources":["../src/grade.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAGL,aAAa,EACb,UAAU,EAKV,QAAQ,EACR,WAAW,EAEX,aAAa,GAMd,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAIpC,SAAS,SAAS,CAAC,GAAc;IAC/B,MAAM,KAAK,GACT,WAAW,CAAC,GAAG,CAAC;QAChB,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,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;QAChB,OAAO,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,KAAK,MAAM,CAAC,MAAM;QAC9D,KAAK;QACL,MAAM,EAAE,OAAO;QACf,KAAK;QACL,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE;KAC5C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,GAAc,EAAE,OAAqB,EAAE,KAAgB;IAChF,SAAS,CAAC,GAAG,CAAC,CAAC;IACf,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,KAAK,IAAI,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,EAAE,CAAC;QAC5C,KAAK,MAAM,EAAE,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YAC7B,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;YAC9C,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtC,IAAI,KAAK,KAAK,EAAE;gBAAE,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC;QACpC,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,45 @@
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 { type ComponentManifest, type ElementNode, type Node, type UrlPolicy } from '@astl/core';
7
+ export interface GuardContext {
8
+ /** The opaque id the view element must carry. */
9
+ readonly id: string;
10
+ readonly urlPolicy: UrlPolicy;
11
+ }
12
+ /**
13
+ * Throws (a definition bug) unless `view` is an allowed public view of the sanitised `source`: `id` and `v` first,
14
+ * public and derived attributes only, declared public children only, rich inline text only inside `inline`
15
+ * children (a rich block: rich content with its declared children in it), text only where allowed, no event
16
+ * handlers, URLs through the URL policy, opaque ids only, and none of the element's private values.
17
+ */
18
+ export declare function guardView(view: ElementNode, source: ElementNode, manifest: ComponentManifest, ctx: GuardContext): void;
19
+ export interface LeakFinding {
20
+ readonly kind: 'value' | 'attribute' | 'child';
21
+ /** What leaks: `@answer`, `astl-alt`, `astl-option@correct`. */
22
+ readonly what: string;
23
+ /** The leaked value, for value leaks. */
24
+ readonly value?: string;
25
+ }
26
+ /**
27
+ * Private data of one component found in its view element: private attributes or children that are present, and
28
+ * secret values (private strings and private child texts) that appear in the view's text or free-text attributes.
29
+ * A value the author also wrote in the element's public content is not a leak.
30
+ */
31
+ export declare function findLeaks(source: ElementNode, view: ElementNode, manifest: ComponentManifest): LeakFinding[];
32
+ /** Element descendants, without recursion. */
33
+ export declare function descendants(el: ElementNode): ElementNode[];
34
+ /**
35
+ * All text of the nodes, one space between text nodes, so tokens never join across elements. A picture's `alt` is text
36
+ * too (screen readers read it out), and so are the addresses of pictures and links, as written and decoded: a picture
37
+ * loads by itself, so a value in its address reaches whoever serves it.
38
+ */
39
+ export declare function wordsOf(nodes: readonly Node[]): string;
40
+ /**
41
+ * Whether `needle` occurs in `haystack` as a whole token (not inside a longer word or number). Knuth-Morris-Pratt,
42
+ * so the time stays linear for any input; a regular expression would be quadratic on repetitive text.
43
+ */
44
+ export declare function containsToken(haystack: string, needle: string): boolean;
45
+ //# sourceMappingURL=guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard.d.ts","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAML,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAKhB,KAAK,IAAI,EAGT,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAIpB,MAAM,WAAW,YAAY;IAC3B,iDAAiD;IACjD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;CAC/B;AAID;;;;;GAKG;AACH,wBAAgB,SAAS,CACvB,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,iBAAiB,EAC3B,GAAG,EAAE,YAAY,GAChB,IAAI,CA4CN;AA6ED,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,OAAO,GAAG,WAAW,GAAG,OAAO,CAAC;IAC/C,gEAAgE;IAChE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,yCAAyC;IACzC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CACvB,MAAM,EAAE,WAAW,EACnB,IAAI,EAAE,WAAW,EACjB,QAAQ,EAAE,iBAAiB,GAC1B,WAAW,EAAE,CA2Bf;AAmBD,8CAA8C;AAC9C,wBAAgB,WAAW,CAAC,EAAE,EAAE,WAAW,GAAG,WAAW,EAAE,CAS1D;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,MAAM,CActD;AAyED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAmBvE"}
package/dist/guard.js ADDED
@@ -0,0 +1,327 @@
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 { allAttributes, BLOCK_TAGS, CAPTION_TAG, CONTENT_ATTRIBUTES, FIGURE_TAG, INLINE_TAGS, isOpaqueId, LANGUAGE_TAG_PATTERN, TAG_ATTRIBUTES, URL_ATTRIBUTES, } from '@astl/core';
7
+ import { cleanStyle } from '@astl/core/declarations';
8
+ import { isHtmlWhitespace } from './html.js';
9
+ const DIRECTIONS = new Set(['ltr', 'rtl', 'auto']);
10
+ /**
11
+ * Throws (a definition bug) unless `view` is an allowed public view of the sanitised `source`: `id` and `v` first,
12
+ * public and derived attributes only, declared public children only, rich inline text only inside `inline`
13
+ * children (a rich block: rich content with its declared children in it), text only where allowed, no event
14
+ * handlers, URLs through the URL policy, opaque ids only, and none of the element's private values.
15
+ */
16
+ export function guardView(view, source, manifest, ctx) {
17
+ const fail = (why) => {
18
+ throw new Error(`Component definition ${manifest.tag}: toView ${why}`);
19
+ };
20
+ if (view?.type !== 'element' || view.tag !== manifest.tag)
21
+ fail(`must return a <${manifest.tag}> element`);
22
+ const names = Object.keys(view.attrs);
23
+ if (names[0] !== 'id' || view.attrs.id !== ctx.id)
24
+ fail('must write id = context.opaque() first');
25
+ if (names[1] !== 'v' || view.attrs.v !== String(manifest.version)) {
26
+ fail(`must write v="${manifest.version}" second`);
27
+ }
28
+ const checkAttributes = (el, specs, from) => {
29
+ for (const [name, value] of Object.entries(el.attrs).slice(from)) {
30
+ const problem = attributeProblem(el.tag, name, value, find(specs, name), ctx.urlPolicy);
31
+ if (problem !== null)
32
+ fail(problem);
33
+ }
34
+ };
35
+ checkAttributes(view, allAttributes(manifest), 2);
36
+ const checkChild = (child) => {
37
+ const spec = manifest.children.find((c) => c.tag === child.tag);
38
+ if (spec === undefined)
39
+ fail(`writes <${child.tag}>, which is not a declared child`);
40
+ else if (spec.visibility === 'private')
41
+ fail(`keeps the private child <${child.tag}>`);
42
+ else {
43
+ checkAttributes(child, spec.attributes, 0);
44
+ if (spec.content === 'text') {
45
+ if (child.children.some((n) => n.type === 'element'))
46
+ fail(`writes elements inside text-only <${child.tag}>`);
47
+ }
48
+ else {
49
+ const problem = contentProblem(child.children, ctx.urlPolicy);
50
+ if (problem !== null)
51
+ fail(`${problem} inside <${child.tag}>`);
52
+ }
53
+ }
54
+ };
55
+ if (manifest.content === 'flow') {
56
+ // Rich content as the sanitiser keeps it, with the declared children as the only custom elements.
57
+ const problem = contentProblem(view.children, ctx.urlPolicy, { manifest, child: checkChild });
58
+ if (problem !== null)
59
+ fail(problem);
60
+ }
61
+ else {
62
+ for (const child of view.children) {
63
+ if (child.type === 'element')
64
+ checkChild(child);
65
+ else if (!isHtmlWhitespace(child.value))
66
+ fail('writes text directly inside the element');
67
+ }
68
+ }
69
+ const [leak] = findLeaks(source, view, manifest);
70
+ if (leak !== undefined)
71
+ fail(`puts private data (${leak.what}) into the view`);
72
+ }
73
+ function find(specs, name) {
74
+ return specs.find((s) => s.name === name);
75
+ }
76
+ function attributeProblem(tag, name, value, spec, urlPolicy) {
77
+ if (/^on/i.test(name))
78
+ return `writes the event handler ${name} on <${tag}>`;
79
+ if (name === 'style') {
80
+ return cleanStyle(value).removed.length === 0 ? null : `writes a style the format refuses on <${tag}>`;
81
+ }
82
+ if (CONTENT_ATTRIBUTES.has(name)) {
83
+ const valid = name === 'lang' ? LANGUAGE_TAG_PATTERN.test(value) : DIRECTIONS.has(value);
84
+ return valid ? null : `writes an invalid ${name} on <${tag}>`;
85
+ }
86
+ if (spec === undefined || spec.visibility === 'private') {
87
+ return `writes the attribute ${name} on <${tag}>, which is not public or derived`;
88
+ }
89
+ if (spec.type === 'id' && !isOpaqueId(value))
90
+ return `writes the source id ${value} on <${tag}>`;
91
+ if (spec.type === 'url' && !urlPolicy(value, { tag, attribute: name })) {
92
+ return `writes a blocked URL in ${name} on <${tag}>`;
93
+ }
94
+ return null;
95
+ }
96
+ /**
97
+ * The rich-text allow-list as the sanitiser applies it (a picture keeps its `src` and `alt`): inline tags, and in a
98
+ * rich block's content (`flow`) also its declared children and, outside inline tags, blocks and figures.
99
+ */
100
+ function contentProblem(nodes, urlPolicy, flow, blocks = flow !== undefined) {
101
+ for (const node of nodes) {
102
+ if (node.type === 'text')
103
+ continue;
104
+ if (flow?.manifest.children.some((c) => c.tag === node.tag)) {
105
+ flow.child(node);
106
+ continue;
107
+ }
108
+ const inline = INLINE_TAGS.has(node.tag);
109
+ const block = BLOCK_TAGS.has(node.tag) || node.tag === FIGURE_TAG || node.tag === CAPTION_TAG;
110
+ if (!inline && !(blocks && block))
111
+ return `writes <${node.tag}>`;
112
+ const extra = Object.hasOwn(TAG_ATTRIBUTES, node.tag) ? (TAG_ATTRIBUTES[node.tag] ?? []) : [];
113
+ for (const [name, value] of Object.entries(node.attrs)) {
114
+ if (/^on/i.test(name))
115
+ return `writes the event handler ${name} on <${node.tag}>`;
116
+ if (CONTENT_ATTRIBUTES.has(name)) {
117
+ const problem = attributeProblem(node.tag, name, value, undefined, urlPolicy);
118
+ if (problem !== null)
119
+ return problem;
120
+ }
121
+ else if (!extra.includes(name)) {
122
+ return `writes the attribute ${name} on <${node.tag}>`;
123
+ }
124
+ else if (name === URL_ATTRIBUTES[node.tag] && !urlPolicy(value, { tag: node.tag, attribute: name })) {
125
+ return `writes a blocked URL in ${name} on <${node.tag}>`;
126
+ }
127
+ }
128
+ if (node.tag === 'img' && !(Object.hasOwn(node.attrs, 'src') && Object.hasOwn(node.attrs, 'alt'))) {
129
+ return 'writes <img> without src or alt';
130
+ }
131
+ const nested = contentProblem(node.children, urlPolicy, flow, blocks && !inline);
132
+ if (nested !== null)
133
+ return nested;
134
+ }
135
+ return null;
136
+ }
137
+ /**
138
+ * Private data of one component found in its view element: private attributes or children that are present, and
139
+ * secret values (private strings and private child texts) that appear in the view's text or free-text attributes.
140
+ * A value the author also wrote in the element's public content is not a leak.
141
+ */
142
+ export function findLeaks(source, view, manifest) {
143
+ const findings = [];
144
+ for (const spec of allAttributes(manifest)) {
145
+ if (spec.visibility === 'private' && Object.hasOwn(view.attrs, spec.name)) {
146
+ findings.push({ kind: 'attribute', what: `@${spec.name}` });
147
+ }
148
+ }
149
+ for (const el of descendants(view)) {
150
+ const spec = manifest.children.find((c) => c.tag === el.tag);
151
+ if (spec === undefined)
152
+ continue;
153
+ if (spec.visibility === 'private')
154
+ findings.push({ kind: 'child', what: el.tag });
155
+ for (const attr of spec.attributes) {
156
+ if (attr.visibility === 'private' && Object.hasOwn(el.attrs, attr.name)) {
157
+ findings.push({ kind: 'attribute', what: `${el.tag}@${attr.name}` });
158
+ }
159
+ }
160
+ }
161
+ const viewText = wordsOf([view]);
162
+ const viewValues = freeTextValues(view, manifest);
163
+ const publicText = wordsOf(publicContent(source, manifest));
164
+ const publicValues = freeTextValues(source, manifest, true);
165
+ for (const { what, value } of secretValues(source, manifest)) {
166
+ const inValues = viewValues.includes(value) && !publicValues.includes(value);
167
+ const inText = containsToken(viewText, value) && !containsToken(publicText, value);
168
+ if (inValues || inText)
169
+ findings.push({ kind: 'value', what, value });
170
+ }
171
+ return findings;
172
+ }
173
+ const isChild = (node, manifest, visibility) => node.type === 'element' && manifest.children.some((c) => c.tag === node.tag && c.visibility === visibility);
174
+ /** What the author wrote for students: the public children, or a rich block's content without private children. */
175
+ function publicContent(source, manifest) {
176
+ if (manifest.content !== 'flow')
177
+ return source.children.filter((c) => isChild(c, manifest, 'public'));
178
+ const strip = (nodes) => nodes.flatMap((n) => n.type === 'text'
179
+ ? [n]
180
+ : isChild(n, manifest, 'private')
181
+ ? []
182
+ : [{ ...n, children: strip(n.children) }]);
183
+ return strip(source.children);
184
+ }
185
+ /** Element descendants, without recursion. */
186
+ export function descendants(el) {
187
+ const out = [];
188
+ const stack = [...el.children].reverse();
189
+ for (let node = stack.pop(); node !== undefined; node = stack.pop()) {
190
+ if (node.type !== 'element')
191
+ continue;
192
+ out.push(node);
193
+ for (let i = node.children.length - 1; i >= 0; i--)
194
+ stack.push(node.children[i]);
195
+ }
196
+ return out;
197
+ }
198
+ /**
199
+ * All text of the nodes, one space between text nodes, so tokens never join across elements. A picture's `alt` is text
200
+ * too (screen readers read it out), and so are the addresses of pictures and links, as written and decoded: a picture
201
+ * loads by itself, so a value in its address reaches whoever serves it.
202
+ */
203
+ export function wordsOf(nodes) {
204
+ const parts = [];
205
+ const stack = [...nodes].reverse();
206
+ for (let node = stack.pop(); node !== undefined; node = stack.pop()) {
207
+ if (node.type === 'text')
208
+ parts.push(node.value);
209
+ else {
210
+ if (node.tag === 'img' && Object.hasOwn(node.attrs, 'alt'))
211
+ parts.push(node.attrs.alt ?? '');
212
+ const url = URL_ATTRIBUTES[node.tag];
213
+ if (url !== undefined && Object.hasOwn(node.attrs, url))
214
+ parts.push(...addressWords(node.attrs[url] ?? ''));
215
+ for (let i = node.children.length - 1; i >= 0; i--)
216
+ stack.push(node.children[i]);
217
+ }
218
+ }
219
+ return parts.join(' ');
220
+ }
221
+ /** An address as written and with its escapes decoded (`%63at` and `+` for a space), where it decodes. */
222
+ function addressWords(url) {
223
+ try {
224
+ const decoded = decodeURIComponent(url.replace(/\+/g, ' '));
225
+ return decoded === url ? [url] : [url, decoded];
226
+ }
227
+ catch {
228
+ return [url];
229
+ }
230
+ }
231
+ /** Values of free-text attributes (`string`, `url`) of an element and its declared children. */
232
+ function freeTextValues(el, manifest, publicOnly = false) {
233
+ const keep = (spec) => spec !== undefined &&
234
+ (spec.type === 'string' || spec.type === 'url') &&
235
+ (publicOnly ? spec.visibility === 'public' : spec.visibility !== 'private');
236
+ const out = [];
237
+ const specs = allAttributes(manifest);
238
+ for (const [name, value] of Object.entries(el.attrs))
239
+ if (keep(find(specs, name)))
240
+ out.push(value);
241
+ for (const child of descendants(el)) {
242
+ const spec = manifest.children.find((c) => c.tag === child.tag);
243
+ if (spec === undefined || (publicOnly && spec.visibility !== 'public'))
244
+ continue;
245
+ for (const [name, value] of Object.entries(child.attrs))
246
+ if (keep(find(spec.attributes, name)))
247
+ out.push(value);
248
+ }
249
+ return out;
250
+ }
251
+ /**
252
+ * Secrets of a source element: its type's private string attributes (answers) and private child texts
253
+ * (alternatives). Common settings (`scoring`, `points`) and private numbers, enums and booleans are not secrets,
254
+ * and short values such as `2` would match by chance.
255
+ */
256
+ function secretValues(el, manifest) {
257
+ const out = [];
258
+ const add = (what, value) => {
259
+ const v = value?.trim() ?? '';
260
+ if (v !== '')
261
+ out.push({ what, value: v });
262
+ };
263
+ const secret = (spec) => spec.visibility === 'private' && spec.type === 'string';
264
+ for (const spec of manifest.attributes) {
265
+ if (secret(spec) && Object.hasOwn(el.attrs, spec.name))
266
+ add(`@${spec.name}`, el.attrs[spec.name]);
267
+ }
268
+ // Anywhere inside: a rich block's children sit in its text.
269
+ for (const child of descendants(el)) {
270
+ const spec = manifest.children.find((c) => c.tag === child.tag);
271
+ if (spec === undefined)
272
+ continue;
273
+ if (spec.visibility === 'private')
274
+ add(child.tag, wordsOf(child.children));
275
+ for (const attr of spec.attributes) {
276
+ if (secret(attr) && Object.hasOwn(child.attrs, attr.name)) {
277
+ add(`${child.tag}@${attr.name}`, child.attrs[attr.name]);
278
+ }
279
+ }
280
+ }
281
+ return out;
282
+ }
283
+ const WORD = /^[\p{L}\p{N}]$/u;
284
+ function isWordAt(text, index, before) {
285
+ if (index < 0 || index >= text.length)
286
+ return false;
287
+ let at = index;
288
+ // Step back to the start of a surrogate pair that ends at `index`.
289
+ const unit = text.charCodeAt(at);
290
+ if (before && unit >= 0xdc00 && unit <= 0xdfff && at > 0) {
291
+ const high = text.charCodeAt(at - 1);
292
+ if (high >= 0xd800 && high <= 0xdbff)
293
+ at--;
294
+ }
295
+ return WORD.test(String.fromCodePoint(text.codePointAt(at) ?? 0));
296
+ }
297
+ /**
298
+ * Whether `needle` occurs in `haystack` as a whole token (not inside a longer word or number). Knuth-Morris-Pratt,
299
+ * so the time stays linear for any input; a regular expression would be quadratic on repetitive text.
300
+ */
301
+ export function containsToken(haystack, needle) {
302
+ const m = needle.length;
303
+ if (m === 0 || m > haystack.length)
304
+ return false;
305
+ const fail = new Int32Array(m);
306
+ for (let i = 1, k = 0; i < m; i++) {
307
+ while (k > 0 && needle[i] !== needle[k])
308
+ k = fail[k - 1] ?? 0;
309
+ if (needle[i] === needle[k])
310
+ k++;
311
+ fail[i] = k;
312
+ }
313
+ for (let i = 0, k = 0; i < haystack.length; i++) {
314
+ while (k > 0 && haystack[i] !== needle[k])
315
+ k = fail[k - 1] ?? 0;
316
+ if (haystack[i] === needle[k])
317
+ k++;
318
+ if (k === m) {
319
+ const start = i - m + 1;
320
+ if (!isWordAt(haystack, start - 1, true) && !isWordAt(haystack, i + 1, false))
321
+ return true;
322
+ k = fail[k - 1] ?? 0;
323
+ }
324
+ }
325
+ return false;
326
+ }
327
+ //# sourceMappingURL=guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAEL,aAAa,EACb,UAAU,EACV,WAAW,EACX,kBAAkB,EAGlB,UAAU,EACV,WAAW,EACX,UAAU,EACV,oBAAoB,EAEpB,cAAc,EACd,cAAc,GAEf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAQ7C,MAAM,UAAU,GAAwB,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AAExE;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CACvB,IAAiB,EACjB,MAAmB,EACnB,QAA2B,EAC3B,GAAiB;IAEjB,MAAM,IAAI,GAAG,CAAC,GAAW,EAAS,EAAE;QAClC,MAAM,IAAI,KAAK,CAAC,wBAAwB,QAAQ,CAAC,GAAG,YAAY,GAAG,EAAE,CAAC,CAAC;IACzE,CAAC,CAAC;IACF,IAAI,IAAI,EAAE,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,KAAK,QAAQ,CAAC,GAAG;QAAE,IAAI,CAAC,kBAAkB,QAAQ,CAAC,GAAG,WAAW,CAAC,CAAC;IAC3G,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACtC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,E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AAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;QAChE,IAAI,QAAQ,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC;YAAE,CAAC,EAAE,CAAC;QACnC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACZ,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACxB,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,GAAG,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC;gBAAE,OAAO,IAAI,CAAC;YAC3F,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
package/dist/help.d.ts ADDED
@@ -0,0 +1,32 @@
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 { type AnswerKey, type AttemptPolicy, type ElementHelp, type GradeResult, type HintResponse, type ResultHelp } from '@astl/core';
6
+ /**
7
+ * Whether a check or the hand-in brings feedback texts and explanations under a policy: after a check when the policy
8
+ * says `check`; at the hand-in when it says `check` or `submit`, and only with the answers (`reveal: 'answers'`), as a
9
+ * feedback text names the right answer as surely as a solution does.
10
+ */
11
+ export declare function helpShown(policy: AttemptPolicy, moment: 'check' | 'submit'): {
12
+ readonly feedback: boolean;
13
+ readonly explanations: boolean;
14
+ };
15
+ /** The view attributes (`HELP_ATTRIBUTES`) for what an element or page offers: only those with something to say. */
16
+ export declare function helpAttributes(help: ElementHelp): Record<string, string>;
17
+ /** Whether `id` is a graded view element of the key: what a check of one interaction may name. */
18
+ export declare function isGradedElement(key: AnswerKey, id: string): boolean;
19
+ /**
20
+ * The help a result brings, for what it graded: each graded element's feedback for its verdict and its explanation,
21
+ * and, unless one element was checked (`element`), each graded page's own, its feedback picked by the page's overall
22
+ * verdict. `shown` says which of the two the policy gives now (`helpShown`). Empty parts are left out.
23
+ */
24
+ export declare function resultHelp(key: AnswerKey, result: GradeResult, shown: {
25
+ readonly feedback: boolean;
26
+ readonly explanations: boolean;
27
+ }, element?: string): ResultHelp;
28
+ /** How many hints an element or a page has. */
29
+ export declare function hintCount(key: AnswerKey, id: string): number;
30
+ /** The hint after the first `used` ones of an element or a page; null when there is none. */
31
+ export declare function nextHint(key: AnswerKey, id: string, used: number): HintResponse | null;
32
+ //# sourceMappingURL=help.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"help.d.ts","sourceRoot":"","sources":["../src/help.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,WAAW,EAGhB,KAAK,WAAW,EAGhB,KAAK,YAAY,EAGjB,KAAK,UAAU,EAChB,MAAM,YAAY,CAAC;AAEpB;;;;GAIG;AACH,wBAAgB,SAAS,CACvB,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,OAAO,GAAG,QAAQ,GACzB;IAAE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAA;CAAE,CAKhE;AAED,oHAAoH;AACpH,wBAAgB,cAAc,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAMxE;AAoBD,kGAAkG;AAClG,wBAAgB,eAAe,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAEnE;AAmBD;;;;GAIG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,SAAS,EACd,MAAM,EAAE,WAAW,EACnB,KAAK,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAA;CAAE,EACrE,OAAO,CAAC,EAAE,MAAM,GACf,UAAU,CAiCZ;AAED,+CAA+C;AAC/C,wBAAgB,SAAS,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAG5D;AAED,6FAA6F;AAC7F,wBAAgB,QAAQ,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAKtF"}