@astl/player 0.0.0 → 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.
- package/CHANGELOG.md +48 -0
- package/LICENSE +202 -0
- package/README.md +37 -0
- package/dist/a11y.d.ts +41 -0
- package/dist/a11y.d.ts.map +1 -0
- package/dist/a11y.js +101 -0
- package/dist/a11y.js.map +1 -0
- package/dist/attempt/controller.d.ts +104 -0
- package/dist/attempt/controller.d.ts.map +1 -0
- package/dist/attempt/controller.js +325 -0
- package/dist/attempt/controller.js.map +1 -0
- package/dist/checker/http.d.ts +17 -0
- package/dist/checker/http.d.ts.map +1 -0
- package/dist/checker/http.js +115 -0
- package/dist/checker/http.js.map +1 -0
- package/dist/define.d.ts +35 -0
- package/dist/define.d.ts.map +1 -0
- package/dist/define.js +84 -0
- package/dist/define.js.map +1 -0
- package/dist/element/base.d.ts +83 -0
- package/dist/element/base.d.ts.map +1 -0
- package/dist/element/base.js +239 -0
- package/dist/element/base.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/interaction/index.d.ts +12 -0
- package/dist/interaction/index.d.ts.map +1 -0
- package/dist/interaction/index.js +4 -0
- package/dist/interaction/index.js.map +1 -0
- package/dist/interaction/keys.d.ts +11 -0
- package/dist/interaction/keys.d.ts.map +1 -0
- package/dist/interaction/keys.js +13 -0
- package/dist/interaction/keys.js.map +1 -0
- package/dist/interaction/pick-and-place.d.ts +120 -0
- package/dist/interaction/pick-and-place.d.ts.map +1 -0
- package/dist/interaction/pick-and-place.js +395 -0
- package/dist/interaction/pick-and-place.js.map +1 -0
- package/dist/interaction/roving-focus.d.ts +44 -0
- package/dist/interaction/roving-focus.d.ts.map +1 -0
- package/dist/interaction/roving-focus.js +115 -0
- package/dist/interaction/roving-focus.js.map +1 -0
- package/dist/messages/en.json +53 -0
- package/dist/messages/help/en.json +14 -0
- package/dist/messages/help/pl.json +14 -0
- package/dist/messages/pl.json +53 -0
- package/dist/messages.d.ts +7 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +18 -0
- package/dist/messages.js.map +1 -0
- package/dist/player/book.d.ts +13 -0
- package/dist/player/book.d.ts.map +1 -0
- package/dist/player/book.js +65 -0
- package/dist/player/book.js.map +1 -0
- package/dist/player/help.d.ts +55 -0
- package/dist/player/help.d.ts.map +1 -0
- package/dist/player/help.js +484 -0
- package/dist/player/help.js.map +1 -0
- package/dist/player/player.d.ts +87 -0
- package/dist/player/player.d.ts.map +1 -0
- package/dist/player/player.js +1229 -0
- package/dist/player/player.js.map +1 -0
- package/dist/player/styled.d.ts +10 -0
- package/dist/player/styled.d.ts.map +1 -0
- package/dist/player/styled.js +213 -0
- package/dist/player/styled.js.map +1 -0
- package/dist/player/styles.d.ts +3 -0
- package/dist/player/styles.d.ts.map +1 -0
- package/dist/player/styles.js +355 -0
- package/dist/player/styles.js.map +1 -0
- package/dist/player/templates.d.ts +25 -0
- package/dist/player/templates.d.ts.map +1 -0
- package/dist/player/templates.js +101 -0
- package/dist/player/templates.js.map +1 -0
- package/dist/player/view.d.ts +44 -0
- package/dist/player/view.d.ts.map +1 -0
- package/dist/player/view.js +231 -0
- package/dist/player/view.js.map +1 -0
- package/dist/runtime.d.ts +45 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +48 -0
- package/dist/runtime.js.map +1 -0
- package/package.json +45 -4
- package/src/a11y.ts +134 -0
- package/src/attempt/controller.ts +381 -0
- package/src/checker/http.ts +149 -0
- package/src/define.ts +114 -0
- package/src/element/base.ts +310 -0
- package/src/index.ts +18 -0
- package/src/interaction/index.ts +11 -0
- package/src/interaction/keys.ts +16 -0
- package/src/interaction/pick-and-place.ts +464 -0
- package/src/interaction/roving-focus.ts +133 -0
- package/src/messages/en.json +53 -0
- package/src/messages/help/en.json +14 -0
- package/src/messages/help/pl.json +14 -0
- package/src/messages/pl.json +53 -0
- package/src/messages.ts +21 -0
- package/src/player/book.ts +70 -0
- package/src/player/help.ts +585 -0
- package/src/player/player.ts +1368 -0
- package/src/player/styled.ts +247 -0
- package/src/player/styles.ts +355 -0
- package/src/player/templates.ts +142 -0
- package/src/player/view.ts +294 -0
- package/src/runtime.ts +95 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The attempt state machine, without DOM: answers, pages, checks and submission over a Checker.
|
|
3
|
+
* The player renders it; hosts and tests can drive it directly.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
type Answers,
|
|
7
|
+
type AttemptPolicy,
|
|
8
|
+
type AttemptState,
|
|
9
|
+
type Checker,
|
|
10
|
+
CheckerError,
|
|
11
|
+
type CheckResponse,
|
|
12
|
+
type GradeResult,
|
|
13
|
+
helpPolicy,
|
|
14
|
+
isSnapshot,
|
|
15
|
+
type JsonValue,
|
|
16
|
+
ProblemCode,
|
|
17
|
+
type ProblemCodeValue,
|
|
18
|
+
SNAPSHOT_FORMAT,
|
|
19
|
+
type Snapshot,
|
|
20
|
+
type Solution,
|
|
21
|
+
type SubmitResponse,
|
|
22
|
+
} from '@astl/core';
|
|
23
|
+
|
|
24
|
+
export interface AttemptPage {
|
|
25
|
+
/** View page id. */
|
|
26
|
+
readonly id: string;
|
|
27
|
+
/** Slots answered on this page, in reading order. */
|
|
28
|
+
readonly slotIds: readonly string[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface AttemptControllerOptions {
|
|
32
|
+
readonly policy: AttemptPolicy;
|
|
33
|
+
readonly checker: Checker;
|
|
34
|
+
readonly pages: readonly AttemptPage[];
|
|
35
|
+
/** Restored when it is valid and its `viewHash` is null or equals `viewHash`. */
|
|
36
|
+
readonly snapshot?: Snapshot | null;
|
|
37
|
+
/** Hash of the view the attempt runs on; written into snapshots. */
|
|
38
|
+
readonly viewHash?: string | null;
|
|
39
|
+
/** Clock in milliseconds, for deadlines and `savedAt`. Default `Date.now`. */
|
|
40
|
+
readonly now?: () => number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type AttemptChange =
|
|
44
|
+
| { readonly type: 'state'; readonly state: AttemptState; readonly previous: AttemptState }
|
|
45
|
+
/** Only the slots that changed; `''` = cleared. */
|
|
46
|
+
| { readonly type: 'answers'; readonly answers: Answers }
|
|
47
|
+
| { readonly type: 'page'; readonly index: number; readonly previous: number }
|
|
48
|
+
| { readonly type: 'result'; readonly response: CheckResponse | SubmitResponse }
|
|
49
|
+
/** A check of one interaction (`checkElement`): its result only, the last whole result stays. */
|
|
50
|
+
| { readonly type: 'element'; readonly id: string; readonly response: CheckResponse }
|
|
51
|
+
| { readonly type: 'reset' };
|
|
52
|
+
|
|
53
|
+
export type AttemptListener = (change: AttemptChange) => void;
|
|
54
|
+
|
|
55
|
+
/** A refusal decided locally, shaped like the protocol's problem documents. */
|
|
56
|
+
function refusal(code: ProblemCodeValue, status: number, detail?: string): CheckerError {
|
|
57
|
+
return new CheckerError({
|
|
58
|
+
type: `urn:astrolabe:problem:${code}`,
|
|
59
|
+
title: code,
|
|
60
|
+
status,
|
|
61
|
+
code,
|
|
62
|
+
...(detail === undefined ? {} : { detail }),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function asCheckerError(error: unknown): CheckerError {
|
|
67
|
+
if (error instanceof CheckerError) return error;
|
|
68
|
+
return refusal(ProblemCode.internal, 500, error instanceof Error ? error.message : String(error));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export class AttemptController {
|
|
72
|
+
readonly policy: AttemptPolicy;
|
|
73
|
+
readonly pages: readonly AttemptPage[];
|
|
74
|
+
readonly viewHash: string | null;
|
|
75
|
+
/** Whether the snapshot passed in was applied. */
|
|
76
|
+
readonly restored: boolean;
|
|
77
|
+
/** The checker can be swapped at any time (e.g. a host sets it after the view). */
|
|
78
|
+
checker: Checker;
|
|
79
|
+
#now: () => number;
|
|
80
|
+
#state: AttemptState;
|
|
81
|
+
#answers: Record<string, string> = {};
|
|
82
|
+
#page = 0;
|
|
83
|
+
#checks = 0;
|
|
84
|
+
#checksLeft: number | null;
|
|
85
|
+
#result: GradeResult | null = null;
|
|
86
|
+
#solution: Solution | null = null;
|
|
87
|
+
#response: CheckResponse | SubmitResponse | null = null;
|
|
88
|
+
#pendingCheck: Promise<CheckResponse> | null = null;
|
|
89
|
+
#pendingSubmit: Promise<SubmitResponse> | null = null;
|
|
90
|
+
#listeners = new Set<AttemptListener>();
|
|
91
|
+
#slots: ReadonlySet<string>;
|
|
92
|
+
|
|
93
|
+
constructor(options: AttemptControllerOptions) {
|
|
94
|
+
this.policy = options.policy;
|
|
95
|
+
this.checker = options.checker;
|
|
96
|
+
this.pages = options.pages;
|
|
97
|
+
this.viewHash = options.viewHash ?? null;
|
|
98
|
+
this.#now = options.now ?? Date.now;
|
|
99
|
+
this.#slots = new Set(this.pages.flatMap((p) => p.slotIds));
|
|
100
|
+
const snapshot = this.#restorable(options.snapshot ?? null);
|
|
101
|
+
this.restored = snapshot !== null;
|
|
102
|
+
if (snapshot) {
|
|
103
|
+
for (const [id, value] of Object.entries(snapshot.answers)) {
|
|
104
|
+
if (this.#slots.has(id) && value !== '') this.#answers[id] = value;
|
|
105
|
+
}
|
|
106
|
+
this.#page = Math.min(snapshot.page, Math.max(0, this.pages.length - 1));
|
|
107
|
+
this.#checks = snapshot.checks;
|
|
108
|
+
}
|
|
109
|
+
this.#checksLeft =
|
|
110
|
+
this.policy.maxChecks === null ? null : Math.max(0, this.policy.maxChecks - this.#checks);
|
|
111
|
+
if (this.policy.mode === 'review') this.#state = 'review';
|
|
112
|
+
else if (snapshot?.submitted) this.#state = 'submitted';
|
|
113
|
+
else if (snapshot && (Object.keys(this.#answers).length > 0 || this.#checks > 0)) this.#state = 'active';
|
|
114
|
+
else this.#state = 'ready';
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The snapshot when it is valid and belongs to the view (`viewHash` null or equal), else null. */
|
|
118
|
+
static restorable(snapshot: unknown, viewHash: string | null): Snapshot | null {
|
|
119
|
+
if (!isSnapshot(snapshot)) return null;
|
|
120
|
+
return snapshot.viewHash === null || snapshot.viewHash === viewHash ? snapshot : null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
get state(): AttemptState {
|
|
124
|
+
return this.#state;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
get answers(): Answers {
|
|
128
|
+
return { ...this.#answers };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 0-based index of the current page. */
|
|
132
|
+
get page(): number {
|
|
133
|
+
return this.#page;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
get pageCount(): number {
|
|
137
|
+
return this.pages.length;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
get checks(): number {
|
|
141
|
+
return this.#checks;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** null = unlimited. */
|
|
145
|
+
get checksLeft(): number | null {
|
|
146
|
+
return this.#checksLeft;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The last result (practice keeps it while the student goes on). */
|
|
150
|
+
get result(): GradeResult | null {
|
|
151
|
+
return this.#result;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
get solution(): Solution | null {
|
|
155
|
+
return this.#solution;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The last CheckResponse or SubmitResponse. */
|
|
159
|
+
get response(): CheckResponse | SubmitResponse | null {
|
|
160
|
+
return this.#response;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Answers cannot change: review, submitting or submitted. */
|
|
164
|
+
get readOnly(): boolean {
|
|
165
|
+
return this.#state === 'review' || this.#state === 'submitting' || this.#state === 'submitted';
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
canCheck(): boolean {
|
|
169
|
+
return (
|
|
170
|
+
this.policy.mode === 'practice' &&
|
|
171
|
+
(this.#state === 'ready' || this.#state === 'active') &&
|
|
172
|
+
this.#checksLeft !== 0
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
canSubmit(): boolean {
|
|
177
|
+
return this.policy.mode !== 'review' && (this.#state === 'ready' || this.#state === 'active');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
canGoTo(index: number): boolean {
|
|
181
|
+
if (!Number.isInteger(index) || index < 0 || index >= this.pages.length) return false;
|
|
182
|
+
if (index >= this.#page) return true;
|
|
183
|
+
// Linear attempts never return to earlier pages while answers can still change.
|
|
184
|
+
return this.policy.navigation === 'free' || this.readOnly;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
subscribe(listener: AttemptListener): () => void {
|
|
188
|
+
this.#listeners.add(listener);
|
|
189
|
+
return () => this.#listeners.delete(listener);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** `ready -> active`. Called implicitly by the first answer, check or submit. */
|
|
193
|
+
start(): void {
|
|
194
|
+
if (this.#state === 'ready') this.#setState('active');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Applies a partial update (`''` deletes) and returns the slots that actually changed. Unknown ids are ignored. */
|
|
198
|
+
setAnswers(partial: Answers): Answers {
|
|
199
|
+
if (this.readOnly) return {};
|
|
200
|
+
const changed: Record<string, string> = {};
|
|
201
|
+
for (const [id, value] of Object.entries(partial)) {
|
|
202
|
+
if (!this.#slots.has(id) || (this.#answers[id] ?? '') === value) continue;
|
|
203
|
+
if (value === '') delete this.#answers[id];
|
|
204
|
+
else this.#answers[id] = value;
|
|
205
|
+
changed[id] = value;
|
|
206
|
+
}
|
|
207
|
+
if (Object.keys(changed).length === 0) return changed;
|
|
208
|
+
this.start();
|
|
209
|
+
this.#emit({ type: 'answers', answers: changed });
|
|
210
|
+
return changed;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
goTo(index: number): boolean {
|
|
214
|
+
if (index === this.#page || !this.canGoTo(index)) return false;
|
|
215
|
+
const previous = this.#page;
|
|
216
|
+
this.#page = index;
|
|
217
|
+
this.#emit({ type: 'page', index, previous });
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
next(): boolean {
|
|
222
|
+
return this.goTo(this.#page + 1);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
previous(): boolean {
|
|
226
|
+
return this.goTo(this.#page - 1);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Practice only. Grades everything, or one view page. A second call while checking joins the first. */
|
|
230
|
+
check(page?: string): Promise<CheckResponse> {
|
|
231
|
+
return this.#check(page);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Practice with `checkScope: 'interaction'` only: grades one interaction (a view element id), counted like any
|
|
236
|
+
* check. The response comes as an `element` change; `result` and `response` keep the last whole check.
|
|
237
|
+
*/
|
|
238
|
+
checkElement(id: string): Promise<CheckResponse> {
|
|
239
|
+
return this.#check(undefined, id);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
#check(page: string | undefined, element?: string): Promise<CheckResponse> {
|
|
243
|
+
if (this.#pendingCheck) return this.#pendingCheck;
|
|
244
|
+
const refused = this.#checkRefusal(page, element);
|
|
245
|
+
if (refused) return Promise.reject(refused);
|
|
246
|
+
const run = this.#runCheck(page, element).finally(() => {
|
|
247
|
+
this.#pendingCheck = null;
|
|
248
|
+
});
|
|
249
|
+
this.#pendingCheck = run;
|
|
250
|
+
return run;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Final. Waits for a running check first; a second call while submitting joins the first. */
|
|
254
|
+
submit(): Promise<SubmitResponse> {
|
|
255
|
+
if (this.#pendingSubmit) return this.#pendingSubmit;
|
|
256
|
+
if (this.policy.mode === 'review' || this.#state === 'submitted') {
|
|
257
|
+
return Promise.reject(refusal(ProblemCode.attemptClosed, 409));
|
|
258
|
+
}
|
|
259
|
+
const run = this.#runSubmit().finally(() => {
|
|
260
|
+
this.#pendingSubmit = null;
|
|
261
|
+
});
|
|
262
|
+
this.#pendingSubmit = run;
|
|
263
|
+
return run;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Clears answers and the last result and goes back to the first page. Not after submitting. */
|
|
267
|
+
reset(): boolean {
|
|
268
|
+
if (this.#state !== 'ready' && this.#state !== 'active') return false;
|
|
269
|
+
this.#answers = {};
|
|
270
|
+
this.#result = null;
|
|
271
|
+
this.#solution = null;
|
|
272
|
+
this.#response = null;
|
|
273
|
+
const previous = this.#page;
|
|
274
|
+
this.#page = 0;
|
|
275
|
+
this.#emit({ type: 'reset' });
|
|
276
|
+
if (previous !== 0) this.#emit({ type: 'page', index: 0, previous });
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
snapshot(ui: Readonly<Record<string, JsonValue>> = {}): Snapshot {
|
|
281
|
+
return {
|
|
282
|
+
format: SNAPSHOT_FORMAT,
|
|
283
|
+
viewHash: this.viewHash,
|
|
284
|
+
answers: this.answers,
|
|
285
|
+
page: this.#page,
|
|
286
|
+
checks: this.#checks,
|
|
287
|
+
submitted: this.#state === 'submitted',
|
|
288
|
+
ui,
|
|
289
|
+
savedAt: new Date(this.#now()).toISOString(),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Slot ids without an answer, on one page or on all of them. */
|
|
294
|
+
emptySlots(page?: number): string[] {
|
|
295
|
+
const pages = page === undefined ? this.pages : this.pages.slice(page, page + 1);
|
|
296
|
+
return pages.flatMap((p) => p.slotIds).filter((id) => (this.#answers[id] ?? '') === '');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Milliseconds to the policy deadline (0 when past it); null without a deadline. */
|
|
300
|
+
timeLeft(): number | null {
|
|
301
|
+
if (this.policy.deadline === null) return null;
|
|
302
|
+
return Math.max(0, Date.parse(this.policy.deadline) - this.#now());
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
#checkRefusal(page: string | undefined, element: string | undefined): CheckerError | null {
|
|
306
|
+
if (this.policy.mode !== 'practice') return refusal(ProblemCode.checkNotAllowed, 403);
|
|
307
|
+
if (element !== undefined && helpPolicy(this.policy).checkScope !== 'interaction') {
|
|
308
|
+
return refusal(ProblemCode.checkNotAllowed, 403);
|
|
309
|
+
}
|
|
310
|
+
if (this.#state === 'submitting' || this.#state === 'submitted' || this.#state === 'review') {
|
|
311
|
+
return refusal(ProblemCode.attemptClosed, 409);
|
|
312
|
+
}
|
|
313
|
+
if (this.#checksLeft === 0) return refusal(ProblemCode.checksExhausted, 403);
|
|
314
|
+
if (page !== undefined && !this.pages.some((p) => p.id === page))
|
|
315
|
+
return refusal(ProblemCode.notFound, 404);
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async #runCheck(page: string | undefined, element: string | undefined): Promise<CheckResponse> {
|
|
320
|
+
this.start();
|
|
321
|
+
this.#setState('checking');
|
|
322
|
+
try {
|
|
323
|
+
const answers = this.answers;
|
|
324
|
+
const scope = page !== undefined ? { page } : element !== undefined ? { element } : {};
|
|
325
|
+
const response = await this.checker.check({ answers, ...scope });
|
|
326
|
+
this.#checks++;
|
|
327
|
+
this.#checksLeft =
|
|
328
|
+
response.checksLeft ??
|
|
329
|
+
(this.policy.maxChecks === null ? null : Math.max(0, this.policy.maxChecks - this.#checks));
|
|
330
|
+
if (element === undefined) {
|
|
331
|
+
this.#result = response.result;
|
|
332
|
+
this.#response = response;
|
|
333
|
+
}
|
|
334
|
+
this.#setState('active');
|
|
335
|
+
this.#emit(
|
|
336
|
+
element === undefined ? { type: 'result', response } : { type: 'element', id: element, response },
|
|
337
|
+
);
|
|
338
|
+
return response;
|
|
339
|
+
} catch (error) {
|
|
340
|
+
const problem = asCheckerError(error);
|
|
341
|
+
if (problem.problem.code === ProblemCode.checksExhausted) this.#checksLeft = 0;
|
|
342
|
+
this.#setState(problem.problem.code === ProblemCode.attemptClosed ? 'submitted' : 'active');
|
|
343
|
+
throw problem;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async #runSubmit(): Promise<SubmitResponse> {
|
|
348
|
+
if (this.#pendingCheck) await this.#pendingCheck.catch(() => undefined);
|
|
349
|
+
if (this.#state === 'submitted') throw refusal(ProblemCode.attemptClosed, 409);
|
|
350
|
+
this.start();
|
|
351
|
+
this.#setState('submitting');
|
|
352
|
+
try {
|
|
353
|
+
const response = await this.checker.submit({ answers: this.answers });
|
|
354
|
+
this.#response = response;
|
|
355
|
+
this.#result = response.result;
|
|
356
|
+
this.#solution = response.solution;
|
|
357
|
+
this.#setState('submitted');
|
|
358
|
+
this.#emit({ type: 'result', response });
|
|
359
|
+
return response;
|
|
360
|
+
} catch (error) {
|
|
361
|
+
const problem = asCheckerError(error);
|
|
362
|
+
this.#setState(problem.problem.code === ProblemCode.attemptClosed ? 'submitted' : 'active');
|
|
363
|
+
throw problem;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
#restorable(snapshot: Snapshot | null): Snapshot | null {
|
|
368
|
+
return AttemptController.restorable(snapshot, this.viewHash);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
#setState(state: AttemptState): void {
|
|
372
|
+
const previous = this.#state;
|
|
373
|
+
if (state === previous) return;
|
|
374
|
+
this.#state = state;
|
|
375
|
+
this.#emit({ type: 'state', state, previous });
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
#emit(change: AttemptChange): void {
|
|
379
|
+
for (const listener of [...this.#listeners]) listener(change);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checker over the grading protocol (apps/docs/src/content/docs/reference/protocol.md): `POST {endpoint}/check`,
|
|
3
|
+
* `/submit` and `/hint`.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
type Checker,
|
|
7
|
+
CheckerError,
|
|
8
|
+
type CheckRequest,
|
|
9
|
+
type CheckResponse,
|
|
10
|
+
type HintRequest,
|
|
11
|
+
type HintResponse,
|
|
12
|
+
isProblemDetails,
|
|
13
|
+
JSON_MEDIA_TYPE,
|
|
14
|
+
PROBLEM_MEDIA_TYPE,
|
|
15
|
+
ProblemCode,
|
|
16
|
+
type ProblemCodeValue,
|
|
17
|
+
ProtocolPath,
|
|
18
|
+
type ResultHelp,
|
|
19
|
+
type SubmitRequest,
|
|
20
|
+
type SubmitResponse,
|
|
21
|
+
} from '@astl/core';
|
|
22
|
+
|
|
23
|
+
export interface HttpCheckerOptions {
|
|
24
|
+
/** URL of one attempt, e.g. `/api/attempts/123`; `/check`, `/submit` and `/hint` are appended. */
|
|
25
|
+
readonly endpoint: string;
|
|
26
|
+
/** Extra request headers, e.g. `Authorization`. */
|
|
27
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
28
|
+
/** Fetch credentials mode (cookies). Default: the browser default (`same-origin`). */
|
|
29
|
+
readonly credentials?: RequestCredentials;
|
|
30
|
+
/** Fetch implementation, for tests or instrumented clients. Default: the global `fetch`. */
|
|
31
|
+
readonly fetch?: (input: string, init: RequestInit) => Promise<Response>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Problem codes for error statuses without a problem body. */
|
|
35
|
+
const STATUS_CODES: Readonly<Record<number, ProblemCodeValue>> = {
|
|
36
|
+
400: ProblemCode.invalidRequest,
|
|
37
|
+
401: ProblemCode.unauthorized,
|
|
38
|
+
403: ProblemCode.unauthorized,
|
|
39
|
+
404: ProblemCode.notFound,
|
|
40
|
+
405: ProblemCode.methodNotAllowed,
|
|
41
|
+
409: ProblemCode.attemptClosed,
|
|
42
|
+
413: ProblemCode.payloadTooLarge,
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function problem(code: ProblemCodeValue, status: number, detail?: string): CheckerError {
|
|
46
|
+
return new CheckerError({
|
|
47
|
+
type: `urn:astrolabe:problem:${code}`,
|
|
48
|
+
title: code,
|
|
49
|
+
status,
|
|
50
|
+
code,
|
|
51
|
+
...(detail === undefined ? {} : { detail }),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseJson(text: string): unknown {
|
|
56
|
+
try {
|
|
57
|
+
return text === '' ? undefined : JSON.parse(text);
|
|
58
|
+
} catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The help fields of a response when they are objects. Their entries are the player's to check where it shows them
|
|
65
|
+
* (the help module, loaded with views that offer help), like the HTML in them.
|
|
66
|
+
*/
|
|
67
|
+
function helpOf({ feedback, explanations }: Record<string, unknown>): ResultHelp {
|
|
68
|
+
const object = (v: unknown) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
69
|
+
return {
|
|
70
|
+
...(object(feedback) ? { feedback: feedback as NonNullable<ResultHelp['feedback']> } : {}),
|
|
71
|
+
...(object(explanations)
|
|
72
|
+
? { explanations: explanations as NonNullable<ResultHelp['explanations']> }
|
|
73
|
+
: {}),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function httpChecker(options: HttpCheckerOptions): Checker {
|
|
78
|
+
const base = options.endpoint.replace(/\/+$/, '');
|
|
79
|
+
const send = options.fetch ?? ((input: string, init: RequestInit) => globalThis.fetch(input, init));
|
|
80
|
+
|
|
81
|
+
async function post(
|
|
82
|
+
path: string,
|
|
83
|
+
body: CheckRequest | SubmitRequest | HintRequest,
|
|
84
|
+
): Promise<Record<string, unknown>> {
|
|
85
|
+
const init: RequestInit = {
|
|
86
|
+
method: 'POST',
|
|
87
|
+
headers: {
|
|
88
|
+
'content-type': JSON_MEDIA_TYPE,
|
|
89
|
+
accept: `${JSON_MEDIA_TYPE}, ${PROBLEM_MEDIA_TYPE}`,
|
|
90
|
+
...options.headers,
|
|
91
|
+
},
|
|
92
|
+
body: JSON.stringify(body),
|
|
93
|
+
...(options.credentials === undefined ? {} : { credentials: options.credentials }),
|
|
94
|
+
};
|
|
95
|
+
let response: Response;
|
|
96
|
+
let text: string;
|
|
97
|
+
try {
|
|
98
|
+
response = await send(`${base}/${path}`, init);
|
|
99
|
+
text = await response.text();
|
|
100
|
+
} catch (error) {
|
|
101
|
+
throw problem(ProblemCode.internal, 0, error instanceof Error ? error.message : String(error));
|
|
102
|
+
}
|
|
103
|
+
const data = parseJson(text);
|
|
104
|
+
const isProblem = (response.headers.get('content-type') ?? '').includes(PROBLEM_MEDIA_TYPE);
|
|
105
|
+
if (!response.ok || isProblem) {
|
|
106
|
+
if (isProblemDetails(data)) {
|
|
107
|
+
throw new CheckerError({ ...data, type: typeof data.type === 'string' ? data.type : 'about:blank' });
|
|
108
|
+
}
|
|
109
|
+
throw problem(STATUS_CODES[response.status] ?? ProblemCode.internal, response.status);
|
|
110
|
+
}
|
|
111
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
112
|
+
throw problem(ProblemCode.internal, response.status, 'response is not a JSON object');
|
|
113
|
+
}
|
|
114
|
+
return data as Record<string, unknown>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
async check(request: CheckRequest): Promise<CheckResponse> {
|
|
119
|
+
const data = await post(ProtocolPath.check, request);
|
|
120
|
+
if (typeof data.result !== 'object' || data.result === null) {
|
|
121
|
+
throw problem(ProblemCode.internal, 200, 'check response without a result');
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
result: data.result as CheckResponse['result'],
|
|
125
|
+
checksLeft: (data.checksLeft as number | null) ?? null,
|
|
126
|
+
...helpOf(data),
|
|
127
|
+
};
|
|
128
|
+
},
|
|
129
|
+
async submit(request: SubmitRequest): Promise<SubmitResponse> {
|
|
130
|
+
const data = await post(ProtocolPath.submit, request);
|
|
131
|
+
if (typeof data.submittedAt !== 'string') {
|
|
132
|
+
throw problem(ProblemCode.internal, 200, 'submit response without submittedAt');
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
result: (data.result as SubmitResponse['result']) ?? null,
|
|
136
|
+
solution: (data.solution as SubmitResponse['solution']) ?? null,
|
|
137
|
+
passed: (data.passed as boolean | null) ?? null,
|
|
138
|
+
submittedAt: data.submittedAt,
|
|
139
|
+
...helpOf(data),
|
|
140
|
+
};
|
|
141
|
+
},
|
|
142
|
+
async hint(request: HintRequest): Promise<HintResponse> {
|
|
143
|
+
const data = await post(ProtocolPath.hint, request);
|
|
144
|
+
if (typeof data.html !== 'string')
|
|
145
|
+
throw problem(ProblemCode.internal, 200, 'hint response without html');
|
|
146
|
+
return data as unknown as HintResponse;
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
package/src/define.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ELEMENT_TAG_PATTERN,
|
|
3
|
+
isStyleTemplate,
|
|
4
|
+
type MessageCatalog,
|
|
5
|
+
type SourceCompiler,
|
|
6
|
+
STYLE_TEMPLATE_NAME,
|
|
7
|
+
type StyleTemplate,
|
|
8
|
+
strictUrlPolicy,
|
|
9
|
+
type UrlPolicy,
|
|
10
|
+
} from '@astl/core';
|
|
11
|
+
import { AstlPlayer } from './player/player.js';
|
|
12
|
+
import { refreshStyleTemplateSheet } from './player/templates.js';
|
|
13
|
+
import {
|
|
14
|
+
type ElementEntry,
|
|
15
|
+
type ElementRegistration,
|
|
16
|
+
isLazyElement,
|
|
17
|
+
type LazyElement,
|
|
18
|
+
runtime,
|
|
19
|
+
} from './runtime.js';
|
|
20
|
+
|
|
21
|
+
export interface DefinePlayerOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Component elements: a registration is defined right away, a `LazyElement` the first time a view contains its
|
|
24
|
+
* tag.
|
|
25
|
+
*/
|
|
26
|
+
readonly elements: readonly ElementEntry[];
|
|
27
|
+
/** More or overriding catalogs (any namespace), e.g. another UI locale. */
|
|
28
|
+
readonly catalogs?: readonly MessageCatalog[];
|
|
29
|
+
/** Enables light-DOM sources (HTML with answers). */
|
|
30
|
+
readonly compileSource?: SourceCompiler;
|
|
31
|
+
/**
|
|
32
|
+
* Which URLs of a view stay when the player mounts it (links, pictures, `url` attributes): the same policy as the
|
|
33
|
+
* engine that compiled the views (`createEngine({ urlPolicy })`), or the player removes what the engine kept.
|
|
34
|
+
* Default `isSafeUrl`. One policy for every player of the page: the last call that passes one sets it. An address
|
|
35
|
+
* stays only when the policy answers `true` (one that throws blocks it).
|
|
36
|
+
*/
|
|
37
|
+
readonly urlPolicy?: UrlPolicy;
|
|
38
|
+
/**
|
|
39
|
+
* Looks that exercises can pick with `style-template` on `<astl-doc>` or on a component, and hosts with
|
|
40
|
+
* `<astl-player style-template>` (trusted, like the host's own CSS).
|
|
41
|
+
*/
|
|
42
|
+
readonly styleTemplates?: readonly StyleTemplate[];
|
|
43
|
+
/** Default: the global `customElements`. */
|
|
44
|
+
readonly registry?: CustomElementRegistry;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const PLAYER_TAG = 'astl-player';
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Defines `<astl-player>` and the given elements, and registers style templates. Safe to call again: a tag already
|
|
51
|
+
* defined by the same class, a lazy element with the same `load`, or a template already registered as the same
|
|
52
|
+
* object is skipped. A tag taken by another class, by another loader or by the other kind of entry (eager or lazy),
|
|
53
|
+
* or a template name taken by another template, throws (two copies of a bundle would otherwise mix silently).
|
|
54
|
+
*/
|
|
55
|
+
export function definePlayer(options: DefinePlayerOptions): void {
|
|
56
|
+
const registry = options.registry ?? customElements;
|
|
57
|
+
const classes = new Map<string, CustomElementConstructor>();
|
|
58
|
+
const claim = (tag: string, element: CustomElementConstructor): void => {
|
|
59
|
+
const existing = classes.get(tag) ?? registry.get(tag);
|
|
60
|
+
if (existing !== undefined && existing !== element) {
|
|
61
|
+
throw new Error(`<${tag}> is already defined by another class`);
|
|
62
|
+
}
|
|
63
|
+
classes.set(tag, element);
|
|
64
|
+
};
|
|
65
|
+
const taken = (tag: string) => new Error(`<${tag}> is already registered by another entry`);
|
|
66
|
+
claim(PLAYER_TAG, AstlPlayer);
|
|
67
|
+
const eager: ElementRegistration[] = [];
|
|
68
|
+
const lazy = new Map<string, LazyElement['load']>();
|
|
69
|
+
for (const entry of options.elements) {
|
|
70
|
+
if (isLazyElement(entry)) {
|
|
71
|
+
const tag = String(entry.tag);
|
|
72
|
+
if (!ELEMENT_TAG_PATTERN.test(tag) || tag === PLAYER_TAG) {
|
|
73
|
+
throw new TypeError(`Lazy element <${tag}>: the tag must be a lowercase custom element name`);
|
|
74
|
+
}
|
|
75
|
+
const known = lazy.get(tag) ?? runtime.lazy.get(tag)?.load;
|
|
76
|
+
if (known === entry.load) continue;
|
|
77
|
+
if (known !== undefined || classes.has(tag) || runtime.elements.has(tag)) throw taken(tag);
|
|
78
|
+
lazy.set(tag, entry.load);
|
|
79
|
+
} else {
|
|
80
|
+
const tag = entry.manifest.tag;
|
|
81
|
+
if (lazy.has(tag) || runtime.lazy.has(tag)) throw taken(tag);
|
|
82
|
+
claim(tag, entry.element);
|
|
83
|
+
eager.push(entry);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const templates = new Map<string, StyleTemplate>();
|
|
87
|
+
for (const template of options.styleTemplates ?? []) {
|
|
88
|
+
const name = String(template?.name);
|
|
89
|
+
if (!STYLE_TEMPLATE_NAME.test(name)) {
|
|
90
|
+
throw new TypeError(`Style template "${name}": the name must be lowercase kebab-case`);
|
|
91
|
+
}
|
|
92
|
+
// Checked before anything is registered: one broken template must not stop every player from rendering.
|
|
93
|
+
if (!isStyleTemplate(template)) {
|
|
94
|
+
throw new TypeError(`Style template "${name}" needs a version, scopes, messages and string values`);
|
|
95
|
+
}
|
|
96
|
+
const existing = templates.get(template.name) ?? runtime.styleTemplates.get(template.name);
|
|
97
|
+
if (existing !== undefined && existing !== template) {
|
|
98
|
+
throw new Error(`Style template "${template.name}" is already registered`);
|
|
99
|
+
}
|
|
100
|
+
templates.set(template.name, template);
|
|
101
|
+
}
|
|
102
|
+
if (options.urlPolicy !== undefined && typeof options.urlPolicy !== 'function') {
|
|
103
|
+
throw new TypeError('urlPolicy must be a function');
|
|
104
|
+
}
|
|
105
|
+
for (const [tag, element] of classes) if (registry.get(tag) === undefined) registry.define(tag, element);
|
|
106
|
+
for (const registration of eager) runtime.elements.set(registration.manifest.tag, registration);
|
|
107
|
+
for (const [tag, load] of lazy) runtime.lazy.set(tag, { load, registry });
|
|
108
|
+
for (const [name, template] of templates) runtime.styleTemplates.set(name, template);
|
|
109
|
+
if (options.catalogs) runtime.catalogs.push(...options.catalogs);
|
|
110
|
+
if (options.compileSource) runtime.compileSource = options.compileSource;
|
|
111
|
+
if (options.urlPolicy) runtime.urlPolicy = strictUrlPolicy(options.urlPolicy);
|
|
112
|
+
runtime.version++;
|
|
113
|
+
refreshStyleTemplateSheet();
|
|
114
|
+
}
|