@astl/core 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.
Files changed (139) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +202 -0
  3. package/README.md +38 -0
  4. package/dist/answers.d.ts +29 -0
  5. package/dist/answers.d.ts.map +1 -0
  6. package/dist/answers.js +40 -0
  7. package/dist/answers.js.map +1 -0
  8. package/dist/ast.d.ts +25 -0
  9. package/dist/ast.d.ts.map +1 -0
  10. package/dist/ast.js +27 -0
  11. package/dist/ast.js.map +1 -0
  12. package/dist/authoring.d.ts +451 -0
  13. package/dist/authoring.d.ts.map +1 -0
  14. package/dist/authoring.js +2 -0
  15. package/dist/authoring.js.map +1 -0
  16. package/dist/checker.d.ts +78 -0
  17. package/dist/checker.d.ts.map +1 -0
  18. package/dist/checker.js +10 -0
  19. package/dist/checker.js.map +1 -0
  20. package/dist/compiled.d.ts +94 -0
  21. package/dist/compiled.d.ts.map +1 -0
  22. package/dist/compiled.js +16 -0
  23. package/dist/compiled.js.map +1 -0
  24. package/dist/content.d.ts +72 -0
  25. package/dist/content.d.ts.map +1 -0
  26. package/dist/content.js +128 -0
  27. package/dist/content.js.map +1 -0
  28. package/dist/declarations.d.ts +52 -0
  29. package/dist/declarations.d.ts.map +1 -0
  30. package/dist/declarations.js +358 -0
  31. package/dist/declarations.js.map +1 -0
  32. package/dist/definition.d.ts +106 -0
  33. package/dist/definition.d.ts.map +1 -0
  34. package/dist/definition.js +2 -0
  35. package/dist/definition.js.map +1 -0
  36. package/dist/engine.d.ts +95 -0
  37. package/dist/engine.d.ts.map +1 -0
  38. package/dist/engine.js +2 -0
  39. package/dist/engine.js.map +1 -0
  40. package/dist/format.d.ts +29 -0
  41. package/dist/format.d.ts.map +1 -0
  42. package/dist/format.js +55 -0
  43. package/dist/format.js.map +1 -0
  44. package/dist/help.d.ts +38 -0
  45. package/dist/help.d.ts.map +1 -0
  46. package/dist/help.js +22 -0
  47. package/dist/help.js.map +1 -0
  48. package/dist/i18n/check.d.ts +11 -0
  49. package/dist/i18n/check.d.ts.map +1 -0
  50. package/dist/i18n/check.js +64 -0
  51. package/dist/i18n/check.js.map +1 -0
  52. package/dist/i18n/format.d.ts +40 -0
  53. package/dist/i18n/format.d.ts.map +1 -0
  54. package/dist/i18n/format.js +280 -0
  55. package/dist/i18n/format.js.map +1 -0
  56. package/dist/i18n/i18n.d.ts +14 -0
  57. package/dist/i18n/i18n.d.ts.map +1 -0
  58. package/dist/i18n/i18n.js +82 -0
  59. package/dist/i18n/i18n.js.map +1 -0
  60. package/dist/i18n/types.d.ts +31 -0
  61. package/dist/i18n/types.d.ts.map +1 -0
  62. package/dist/i18n/types.js +7 -0
  63. package/dist/i18n/types.js.map +1 -0
  64. package/dist/index.d.ts +45 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +21 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/issues.d.ts +98 -0
  69. package/dist/issues.d.ts.map +1 -0
  70. package/dist/issues.js +74 -0
  71. package/dist/issues.js.map +1 -0
  72. package/dist/json.d.ts +7 -0
  73. package/dist/json.d.ts.map +1 -0
  74. package/dist/json.js +2 -0
  75. package/dist/json.js.map +1 -0
  76. package/dist/manifest.d.ts +135 -0
  77. package/dist/manifest.d.ts.map +1 -0
  78. package/dist/manifest.js +63 -0
  79. package/dist/manifest.js.map +1 -0
  80. package/dist/player.d.ts +129 -0
  81. package/dist/player.d.ts.map +1 -0
  82. package/dist/player.js +18 -0
  83. package/dist/player.js.map +1 -0
  84. package/dist/policy.d.ts +53 -0
  85. package/dist/policy.d.ts.map +1 -0
  86. package/dist/policy.js +55 -0
  87. package/dist/policy.js.map +1 -0
  88. package/dist/protocol.d.ts +54 -0
  89. package/dist/protocol.d.ts.map +1 -0
  90. package/dist/protocol.js +51 -0
  91. package/dist/protocol.js.map +1 -0
  92. package/dist/result.d.ts +44 -0
  93. package/dist/result.d.ts.map +1 -0
  94. package/dist/result.js +5 -0
  95. package/dist/result.js.map +1 -0
  96. package/dist/scoring.d.ts +27 -0
  97. package/dist/scoring.d.ts.map +1 -0
  98. package/dist/scoring.js +6 -0
  99. package/dist/scoring.js.map +1 -0
  100. package/dist/slots.d.ts +47 -0
  101. package/dist/slots.d.ts.map +1 -0
  102. package/dist/slots.js +9 -0
  103. package/dist/slots.js.map +1 -0
  104. package/dist/snapshot.d.ts +23 -0
  105. package/dist/snapshot.d.ts.map +1 -0
  106. package/dist/snapshot.js +22 -0
  107. package/dist/snapshot.js.map +1 -0
  108. package/dist/style.d.ts +51 -0
  109. package/dist/style.d.ts.map +1 -0
  110. package/dist/style.js +36 -0
  111. package/dist/style.js.map +1 -0
  112. package/package.json +40 -4
  113. package/src/answers.ts +52 -0
  114. package/src/ast.ts +49 -0
  115. package/src/authoring.ts +475 -0
  116. package/src/checker.ts +91 -0
  117. package/src/compiled.ts +115 -0
  118. package/src/content.ts +156 -0
  119. package/src/declarations.ts +427 -0
  120. package/src/definition.ts +104 -0
  121. package/src/engine.ts +98 -0
  122. package/src/format.ts +67 -0
  123. package/src/help.ts +41 -0
  124. package/src/i18n/check.ts +67 -0
  125. package/src/i18n/format.ts +318 -0
  126. package/src/i18n/i18n.ts +92 -0
  127. package/src/i18n/types.ts +35 -0
  128. package/src/index.ts +201 -0
  129. package/src/issues.ts +107 -0
  130. package/src/json.ts +6 -0
  131. package/src/manifest.ts +193 -0
  132. package/src/player.ts +145 -0
  133. package/src/policy.ts +117 -0
  134. package/src/protocol.ts +65 -0
  135. package/src/result.ts +53 -0
  136. package/src/scoring.ts +31 -0
  137. package/src/slots.ts +57 -0
  138. package/src/snapshot.ts +40 -0
  139. package/src/style.ts +89 -0
package/src/policy.ts ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Attempt policies. Practice, quiz and test are policies over the same content, not different content: a document's
3
+ * `kind` (`DOC_KINDS`, exercise or book) is how it shows, never how it grades.
4
+ * The server is authoritative: the player only reflects the policy it is given.
5
+ */
6
+ export type AttemptMode = 'practice' | 'test' | 'review';
7
+
8
+ /**
9
+ * What a submit returns to the student:
10
+ * - `nothing`: just the confirmation (results released later by the host);
11
+ * - `score`: score and verdicts;
12
+ * - `answers`: score, verdicts and the solution.
13
+ */
14
+ export type Reveal = 'nothing' | 'score' | 'answers';
15
+
16
+ /** `interaction`: a check may cover one interaction too (`CheckRequest.element`), not only the exercise or a page. */
17
+ export type CheckScope = 'exercise' | 'interaction';
18
+
19
+ /**
20
+ * When feedback texts or explanations come: `never`; `check`: after every check and the hand-in; `submit`: after the
21
+ * hand-in only. At the hand-in they come only with the answers (`reveal: 'answers'`): they may give them away.
22
+ */
23
+ export type HelpMoment = 'never' | 'check' | 'submit';
24
+
25
+ export interface AttemptPolicy {
26
+ /** `practice`: check any time. `test`: no check, one submit. `review`: read-only, shows a submitted attempt. */
27
+ readonly mode: AttemptMode;
28
+ /** `linear`: no going back to earlier pages (tests). */
29
+ readonly navigation: 'free' | 'linear';
30
+ /** Practice only. null = unlimited. */
31
+ readonly maxChecks: number | null;
32
+ /** ISO 8601. The server auto-submits at the deadline; the player only shows the countdown. */
33
+ readonly deadline: string | null;
34
+ /** Fraction of the maximum score needed to pass, 0..1. null = no pass mark. */
35
+ readonly passMark: number | null;
36
+ readonly reveal: Reveal;
37
+ /** Seed for per-attempt UI shuffles. null = keep the view order. */
38
+ readonly seed: string | null;
39
+ // The help fields may be left out (policies written before them): each absent one is its mode's default, the value
40
+ // in PRACTICE_POLICY for practice and in TEST_POLICY otherwise (`helpPolicy`). A host merges an author's switches
41
+ // into them, turning help off.
42
+ /** Hints on request, one at a time from the checker (`Checker.hint`). Practice only. */
43
+ readonly hints?: boolean;
44
+ /** Practice only. */
45
+ readonly checkScope?: CheckScope;
46
+ readonly feedback?: HelpMoment;
47
+ readonly explanations?: HelpMoment;
48
+ }
49
+
50
+ export const PRACTICE_POLICY: AttemptPolicy = {
51
+ mode: 'practice',
52
+ navigation: 'free',
53
+ maxChecks: null,
54
+ deadline: null,
55
+ passMark: null,
56
+ reveal: 'answers',
57
+ seed: null,
58
+ hints: true,
59
+ checkScope: 'interaction',
60
+ feedback: 'check',
61
+ explanations: 'check',
62
+ };
63
+
64
+ export const TEST_POLICY: AttemptPolicy = {
65
+ mode: 'test',
66
+ navigation: 'free',
67
+ maxChecks: 0,
68
+ deadline: null,
69
+ passMark: null,
70
+ reveal: 'score',
71
+ seed: null,
72
+ hints: false,
73
+ checkScope: 'exercise',
74
+ feedback: 'submit',
75
+ explanations: 'submit',
76
+ };
77
+
78
+ /** The help fields of a policy, with every absent one taken from its mode's default policy. */
79
+ export interface HelpPolicy {
80
+ readonly hints: boolean;
81
+ readonly checkScope: CheckScope;
82
+ readonly feedback: HelpMoment;
83
+ readonly explanations: HelpMoment;
84
+ }
85
+
86
+ export function helpPolicy(policy: AttemptPolicy): HelpPolicy {
87
+ const base = policy.mode === 'practice' ? PRACTICE_POLICY : TEST_POLICY;
88
+ const practice = policy.mode === 'practice';
89
+ return {
90
+ hints: practice && (policy.hints ?? base.hints) === true,
91
+ checkScope: practice ? (policy.checkScope ?? base.checkScope ?? 'exercise') : 'exercise',
92
+ feedback: policy.feedback ?? base.feedback ?? 'never',
93
+ explanations: policy.explanations ?? base.explanations ?? 'never',
94
+ };
95
+ }
96
+
97
+ const isMoment = (x: unknown): boolean => x === 'never' || x === 'check' || x === 'submit';
98
+
99
+ export function isAttemptPolicy(value: unknown): value is AttemptPolicy {
100
+ if (typeof value !== 'object' || value === null) return false;
101
+ const v = value as Partial<AttemptPolicy>;
102
+ const nullableNumber = (x: unknown) =>
103
+ x === null || (typeof x === 'number' && Number.isFinite(x) && x >= 0);
104
+ return (
105
+ (v.mode === 'practice' || v.mode === 'test' || v.mode === 'review') &&
106
+ (v.navigation === 'free' || v.navigation === 'linear') &&
107
+ nullableNumber(v.maxChecks) &&
108
+ (v.deadline === null || (typeof v.deadline === 'string' && !Number.isNaN(Date.parse(v.deadline)))) &&
109
+ (v.passMark === null || (typeof v.passMark === 'number' && v.passMark >= 0 && v.passMark <= 1)) &&
110
+ (v.reveal === 'nothing' || v.reveal === 'score' || v.reveal === 'answers') &&
111
+ (v.seed === null || typeof v.seed === 'string') &&
112
+ (v.hints === undefined || typeof v.hints === 'boolean') &&
113
+ (v.checkScope === undefined || v.checkScope === 'exercise' || v.checkScope === 'interaction') &&
114
+ (v.feedback === undefined || isMoment(v.feedback)) &&
115
+ (v.explanations === undefined || isMoment(v.explanations))
116
+ );
117
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Grading protocol over HTTP. Any backend in any language can implement it:
3
+ *
4
+ * POST {endpoint}/check body CheckRequest -> 200 CheckResponse
5
+ * POST {endpoint}/submit body SubmitRequest -> 200 SubmitResponse
6
+ * POST {endpoint}/hint body HintRequest -> 200 HintResponse
7
+ *
8
+ * `{endpoint}` identifies one attempt (e.g. `/api/attempts/123`); how it is authorised is up to the host
9
+ * (cookie, bearer token). Errors are `application/problem+json` (RFC 9457) with a `code` from ProblemCode.
10
+ */
11
+
12
+ export const PROTOCOL_VERSION = 1;
13
+
14
+ export const JSON_MEDIA_TYPE = 'application/json';
15
+ export const PROBLEM_MEDIA_TYPE = 'application/problem+json';
16
+
17
+ export const ProtocolPath = {
18
+ check: 'check',
19
+ submit: 'submit',
20
+ hint: 'hint',
21
+ } as const;
22
+
23
+ export const ProblemCode = {
24
+ /** 400: body is not valid JSON or does not match the request schema. */
25
+ invalidRequest: 'invalid_request',
26
+ /** 401: the host could not identify the attempt. */
27
+ unauthorized: 'unauthorized',
28
+ /** 403: checking is not allowed under this policy (tests). */
29
+ checkNotAllowed: 'check_not_allowed',
30
+ /** 403: the practice policy's maxChecks is used up. */
31
+ checksExhausted: 'checks_exhausted',
32
+ /** 403: the policy offers no hints (tests, or a practice policy with `hints: false`). */
33
+ hintsNotAllowed: 'hints_not_allowed',
34
+ /** 403: every hint of that interaction or page is used. */
35
+ hintsExhausted: 'hints_exhausted',
36
+ /** 404: unknown attempt, page or element. */
37
+ notFound: 'not_found',
38
+ /** 405: wrong method. */
39
+ methodNotAllowed: 'method_not_allowed',
40
+ /** 409: the attempt is already submitted. */
41
+ attemptClosed: 'attempt_closed',
42
+ /** 413: body too large. */
43
+ payloadTooLarge: 'payload_too_large',
44
+ /** 500: unexpected server error. */
45
+ internal: 'internal_error',
46
+ } as const;
47
+
48
+ export type ProblemCodeValue = (typeof ProblemCode)[keyof typeof ProblemCode];
49
+
50
+ export interface ProblemDetails {
51
+ readonly type: string;
52
+ readonly title: string;
53
+ readonly status: number;
54
+ readonly detail?: string;
55
+ readonly code: ProblemCodeValue;
56
+ }
57
+
58
+ /** Largest request body servers should accept, in bytes. */
59
+ export const MAX_REQUEST_BYTES: number = 256 * 1024;
60
+
61
+ export function isProblemDetails(value: unknown): value is ProblemDetails {
62
+ if (typeof value !== 'object' || value === null) return false;
63
+ const v = value as Partial<ProblemDetails>;
64
+ return typeof v.title === 'string' && typeof v.status === 'number' && typeof v.code === 'string';
65
+ }
package/src/result.ts ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Grading results as students and hosts see them. Results never contain key data: no accepted answers, no correct
3
+ * option ids. Solutions travel separately and only when the attempt policy reveals them.
4
+ */
5
+ import type { SlotId } from './answers.js';
6
+
7
+ export type SlotVerdict = 'correct' | 'incorrect';
8
+
9
+ export type GroupVerdict = 'correct' | 'partial' | 'incorrect' | 'empty';
10
+
11
+ export interface GroupResult {
12
+ readonly id: string;
13
+ readonly verdict: GroupVerdict;
14
+ readonly score: number;
15
+ readonly max: number;
16
+ }
17
+
18
+ export interface Score {
19
+ readonly score: number;
20
+ readonly max: number;
21
+ }
22
+
23
+ export interface VerdictCounts {
24
+ readonly correct: number;
25
+ readonly partial: number;
26
+ readonly incorrect: number;
27
+ readonly empty: number;
28
+ /** Number of groups counted. */
29
+ readonly total: number;
30
+ }
31
+
32
+ export interface GradeResult extends Score {
33
+ /** True when every included group is correct; false when no group is included (empty key or unknown page). */
34
+ readonly correct: boolean;
35
+ /**
36
+ * Per-slot verdicts the student may see: answered slots only, selected flags only, and nothing for slots of
37
+ * multi-slot `all-correct` groups (those show only the group verdict).
38
+ */
39
+ readonly slots: Readonly<Record<SlotId, SlotVerdict>>;
40
+ readonly groups: readonly GroupResult[];
41
+ /** Score per view page id. */
42
+ readonly pages: Readonly<Record<string, Score>>;
43
+ /** Counts over groups. */
44
+ readonly counts: VerdictCounts;
45
+ }
46
+
47
+ /** Correct answers by slot, shown when the policy reveals them. `''` entries are omitted. */
48
+ export type Solution = Readonly<Record<SlotId, string>>;
49
+
50
+ /** Rounds a score for display: at most 2 decimals, no trailing zeros. */
51
+ export function roundScore(value: number): number {
52
+ return Math.round(value * 100) / 100;
53
+ }
package/src/scoring.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Scoring groups. Every graded component forms one group by default (id = the component's opaque id), or one per
3
+ * part when its definition grades it in parts (`ComponentDefinition.groups`, a crossword's words), where a slot may
4
+ * sit in several groups.
5
+ *
6
+ * Rules (n = slots in the group, c = correct slots, P = points):
7
+ * - `all-correct`: max P; score P when c = n, else 0. Feedback shows only the group verdict, never which slot is wrong.
8
+ * - `per-slot`: max P x n; score P x c.
9
+ * - `proportional`: max P; score P x c / n (exact, not rounded).
10
+ *
11
+ * Selection slots (flags, e.g. options of a multiple-answer choice): an unselected flag gets no verdict, and a group
12
+ * whose flags are all unselected scores 0 with verdict `empty`.
13
+ */
14
+ export type ScoringRule = 'all-correct' | 'per-slot' | 'proportional';
15
+
16
+ export const SCORING_RULES: readonly ScoringRule[] = ['all-correct', 'per-slot', 'proportional'];
17
+
18
+ export interface ScoringGroup {
19
+ readonly id: string;
20
+ readonly rule: ScoringRule;
21
+ readonly points: number;
22
+ /** Slot ids in reading order. */
23
+ readonly slots: readonly string[];
24
+ /** View page id the group belongs to. */
25
+ readonly page: string;
26
+ }
27
+
28
+ /** Group maximum for a rule. */
29
+ export function groupMax(rule: ScoringRule, points: number, slotCount: number): number {
30
+ return rule === 'per-slot' ? points * slotCount : points;
31
+ }
package/src/slots.ts ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Slot kinds: the open registry of grading semantics. The engine never switches on a kind; it asks the registered
3
+ * SlotKind. Built-ins (engine): `text`, `number`, `choice`, `flag`, and `open` (stored for a teacher, never graded).
4
+ * Hosts and third parties may register more.
5
+ */
6
+ import type { JsonObject } from './json.js';
7
+
8
+ export interface GradeContext {
9
+ /** Content language of the slot (BCP 47), for locale-aware comparisons. */
10
+ readonly lang: string;
11
+ }
12
+
13
+ export interface SlotKind<TKey extends JsonObject = JsonObject> {
14
+ readonly kind: string;
15
+ /** Selection slots use flag semantics (see scoring.ts). */
16
+ readonly selection: boolean;
17
+ /**
18
+ * False for a kind that is stored but never graded (the built-in `open`): its slots belong to no scoring group, get
19
+ * no verdict and add nothing to the maximum, and only ungraded types (`graded: false`) produce them. Default true:
20
+ * graded types produce only graded kinds.
21
+ */
22
+ readonly graded?: boolean;
23
+ /** Validates a stored key (compile output, or a key loaded from storage). */
24
+ isKey(key: JsonObject): key is TKey;
25
+ /** `answer` is never empty here: the engine handles unanswered slots before calling. */
26
+ isCorrect(key: TKey, answer: string, context: GradeContext): boolean;
27
+ /** The answer that shows the solution. `''` = leave the slot empty (an unselected flag). */
28
+ solution(key: TKey): string;
29
+ }
30
+
31
+ /**
32
+ * How typed text is compared. Resolved at compile time and stored inside each text key, so stored keys grade the same
33
+ * forever, whatever the defaults are later.
34
+ */
35
+ export interface NormalisationProfile {
36
+ /** Unicode normalisation applied first. */
37
+ readonly form: 'NFC' | 'NFKC';
38
+ /** `collapse`: trim and turn every whitespace run into one space. */
39
+ readonly space: 'strict' | 'collapse';
40
+ /** `insensitive`: locale-aware lower-casing with the content language (Turkish dotless i works). */
41
+ readonly case: 'sensitive' | 'insensitive';
42
+ /** `fold`: ignore diacritics (ą = a, ł = l, ø = o, ß = ss). `strict` keeps them: żółw != zolw. */
43
+ readonly marks: 'strict' | 'fold';
44
+ /** `ignore-edge`: drop punctuation at the start and end ("ssak." = "ssak"). */
45
+ readonly punctuation: 'strict' | 'ignore-edge';
46
+ /** `fold`: typographic quotes, apostrophes and dashes compare equal to ASCII ones. */
47
+ readonly quotes: 'strict' | 'fold';
48
+ }
49
+
50
+ export const DEFAULT_PROFILE: NormalisationProfile = {
51
+ form: 'NFC',
52
+ space: 'collapse',
53
+ case: 'insensitive',
54
+ marks: 'strict',
55
+ punctuation: 'ignore-edge',
56
+ quotes: 'fold',
57
+ };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Snapshot: everything needed to restore an attempt in the player after a reload. Hosts store it
3
+ * (localStorage, server draft); the player emits it and accepts it back.
4
+ */
5
+ import { type Answers, isAnswers } from './answers.js';
6
+ import type { JsonValue } from './json.js';
7
+
8
+ export const SNAPSHOT_FORMAT = 1;
9
+
10
+ export interface Snapshot {
11
+ readonly format: typeof SNAPSHOT_FORMAT;
12
+ /** View the snapshot was taken on. A player ignores snapshots of another view. */
13
+ readonly viewHash: string | null;
14
+ readonly answers: Answers;
15
+ /** 0-based page index. */
16
+ readonly page: number;
17
+ readonly checks: number;
18
+ readonly submitted: boolean;
19
+ /** Non-answer UI state per element id (e.g. a flashcard index). */
20
+ readonly ui: Readonly<Record<string, JsonValue>>;
21
+ /** ISO 8601. */
22
+ readonly savedAt: string;
23
+ }
24
+
25
+ export function isSnapshot(value: unknown): value is Snapshot {
26
+ if (typeof value !== 'object' || value === null) return false;
27
+ const v = value as Partial<Snapshot>;
28
+ return (
29
+ v.format === SNAPSHOT_FORMAT &&
30
+ (v.viewHash === null || typeof v.viewHash === 'string') &&
31
+ isAnswers(v.answers) &&
32
+ Number.isInteger(v.page) &&
33
+ (v.page ?? -1) >= 0 &&
34
+ Number.isInteger(v.checks) &&
35
+ typeof v.submitted === 'boolean' &&
36
+ typeof v.ui === 'object' &&
37
+ v.ui !== null &&
38
+ typeof v.savedAt === 'string'
39
+ );
40
+ }
package/src/style.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * StyleTemplate: a named look for a whole exercise or for single components, registered by the host (trusted code,
3
+ * like the host's own CSS; exercises only refer to templates by name). Authors pick one with
4
+ * `style-template="<name>"` on `<astl-doc>` or on a component. The closest one wins: the component's, then the
5
+ * document's, then the player's default. A template restyles through design tokens and `::part()` declarations only:
6
+ * it never changes behaviour or grading, and it does not apply in the `hc` theme or under forced colours, so
7
+ * high-contrast users always get the high-contrast look.
8
+ */
9
+ import type { MessageCatalog } from './i18n/types.js';
10
+
11
+ /** The attribute that picks a template, on `<astl-doc>` and on every component. */
12
+ export const STYLE_TEMPLATE_ATTRIBUTE = 'style-template';
13
+
14
+ /** Template names: lowercase kebab-case, 1 to 40 characters, starting with a letter. */
15
+ export const STYLE_TEMPLATE_NAME: RegExp = /^(?=.{1,40}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
16
+
17
+ /** `document`: the whole exercise (the player's canvas and chrome). `component`: one element and its subtree. */
18
+ export type StyleScope = 'document' | 'component';
19
+
20
+ /** Token values by token name without the `--astl-` prefix, e.g. `{ accent: '#7a3ff2', 'radius-m': '1rem' }`. */
21
+ export type TokenOverrides = Readonly<Record<string, string>>;
22
+
23
+ /** CSS declarations by property name, e.g. `{ 'border-radius': 'var(--astl-radius-l)' }`. */
24
+ export type Declarations = Readonly<Record<string, string>>;
25
+
26
+ export interface StyleTemplate {
27
+ /** What authors write in `style-template`. Matches STYLE_TEMPLATE_NAME. */
28
+ readonly name: string;
29
+ /** Bumped when the look changes visibly. Exercises keep referring to the name. */
30
+ readonly version: number;
31
+ /** Where the template may be used. */
32
+ readonly scopes: readonly StyleScope[];
33
+ /** Component tags it supports at the `component` scope; absent = every registered component. */
34
+ readonly components?: readonly string[];
35
+ /** i18n namespace of its texts: `label` (picker label) and `description` (one line), e.g. `astl.style.notebook`. */
36
+ readonly messages: string;
37
+ /** Catalogs of that namespace. */
38
+ readonly catalogs?: readonly MessageCatalog[];
39
+ /** Token overrides for the light and dark themes (never `hc`). */
40
+ readonly tokens?: TokenOverrides;
41
+ /** Overrides on top of `tokens` for the light theme only. */
42
+ readonly light?: TokenOverrides;
43
+ /** Overrides on top of `tokens` for the dark theme only. */
44
+ readonly dark?: TokenOverrides;
45
+ /**
46
+ * `::part()` declarations by component tag, then part name (a name from the manifest's `cssParts`), e.g.
47
+ * `{ 'astl-choice': { option: { 'border-radius': 'var(--astl-radius-l)' } } }`. Use tokens in values so the
48
+ * declarations follow the theme.
49
+ */
50
+ readonly parts?: Readonly<Record<string, Readonly<Record<string, Declarations>>>>;
51
+ }
52
+
53
+ const SCOPES: readonly unknown[] = ['document', 'component'];
54
+
55
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
56
+ typeof value === 'object' && value !== null && !Array.isArray(value);
57
+
58
+ /** Absent, or a record of strings. */
59
+ const isStrings = (value: unknown): boolean =>
60
+ value === undefined || (isRecord(value) && Object.values(value).every((v) => typeof v === 'string'));
61
+
62
+ /**
63
+ * Whether `value` has the shape of a StyleTemplate: a valid name, a positive version, one or both scopes, string tags,
64
+ * a namespace, and records of strings for tokens and parts. Registries use it for hosts without type checking.
65
+ */
66
+ export function isStyleTemplate(value: unknown): value is StyleTemplate {
67
+ if (!isRecord(value)) return false;
68
+ const { name, version, scopes, components, messages, catalogs, tokens, light, dark, parts } = value;
69
+ const parted = (byTag: unknown) => isRecord(byTag) && Object.values(byTag).every(isStrings);
70
+ return (
71
+ typeof name === 'string' &&
72
+ STYLE_TEMPLATE_NAME.test(name) &&
73
+ typeof version === 'number' &&
74
+ Number.isInteger(version) &&
75
+ version >= 1 &&
76
+ Array.isArray(scopes) &&
77
+ scopes.length > 0 &&
78
+ new Set(scopes).size === scopes.length &&
79
+ scopes.every((scope) => SCOPES.includes(scope)) &&
80
+ (components === undefined ||
81
+ (Array.isArray(components) && components.every((t) => typeof t === 'string'))) &&
82
+ typeof messages === 'string' &&
83
+ (catalogs === undefined || Array.isArray(catalogs)) &&
84
+ isStrings(tokens) &&
85
+ isStrings(light) &&
86
+ isStrings(dark) &&
87
+ (parts === undefined || (isRecord(parts) && Object.values(parts).every(parted)))
88
+ );
89
+ }