@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.
- package/CHANGELOG.md +54 -0
- package/LICENSE +202 -0
- package/README.md +38 -0
- package/dist/answers.d.ts +29 -0
- package/dist/answers.d.ts.map +1 -0
- package/dist/answers.js +40 -0
- package/dist/answers.js.map +1 -0
- package/dist/ast.d.ts +25 -0
- package/dist/ast.d.ts.map +1 -0
- package/dist/ast.js +27 -0
- package/dist/ast.js.map +1 -0
- package/dist/authoring.d.ts +451 -0
- package/dist/authoring.d.ts.map +1 -0
- package/dist/authoring.js +2 -0
- package/dist/authoring.js.map +1 -0
- package/dist/checker.d.ts +78 -0
- package/dist/checker.d.ts.map +1 -0
- package/dist/checker.js +10 -0
- package/dist/checker.js.map +1 -0
- package/dist/compiled.d.ts +94 -0
- package/dist/compiled.d.ts.map +1 -0
- package/dist/compiled.js +16 -0
- package/dist/compiled.js.map +1 -0
- package/dist/content.d.ts +72 -0
- package/dist/content.d.ts.map +1 -0
- package/dist/content.js +128 -0
- package/dist/content.js.map +1 -0
- package/dist/declarations.d.ts +52 -0
- package/dist/declarations.d.ts.map +1 -0
- package/dist/declarations.js +358 -0
- package/dist/declarations.js.map +1 -0
- package/dist/definition.d.ts +106 -0
- package/dist/definition.d.ts.map +1 -0
- package/dist/definition.js +2 -0
- package/dist/definition.js.map +1 -0
- package/dist/engine.d.ts +95 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +2 -0
- package/dist/engine.js.map +1 -0
- package/dist/format.d.ts +29 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/format.js +55 -0
- package/dist/format.js.map +1 -0
- package/dist/help.d.ts +38 -0
- package/dist/help.d.ts.map +1 -0
- package/dist/help.js +22 -0
- package/dist/help.js.map +1 -0
- package/dist/i18n/check.d.ts +11 -0
- package/dist/i18n/check.d.ts.map +1 -0
- package/dist/i18n/check.js +64 -0
- package/dist/i18n/check.js.map +1 -0
- package/dist/i18n/format.d.ts +40 -0
- package/dist/i18n/format.d.ts.map +1 -0
- package/dist/i18n/format.js +280 -0
- package/dist/i18n/format.js.map +1 -0
- package/dist/i18n/i18n.d.ts +14 -0
- package/dist/i18n/i18n.d.ts.map +1 -0
- package/dist/i18n/i18n.js +82 -0
- package/dist/i18n/i18n.js.map +1 -0
- package/dist/i18n/types.d.ts +31 -0
- package/dist/i18n/types.d.ts.map +1 -0
- package/dist/i18n/types.js +7 -0
- package/dist/i18n/types.js.map +1 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/issues.d.ts +98 -0
- package/dist/issues.d.ts.map +1 -0
- package/dist/issues.js +74 -0
- package/dist/issues.js.map +1 -0
- package/dist/json.d.ts +7 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +2 -0
- package/dist/json.js.map +1 -0
- package/dist/manifest.d.ts +135 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/manifest.js +63 -0
- package/dist/manifest.js.map +1 -0
- package/dist/player.d.ts +129 -0
- package/dist/player.d.ts.map +1 -0
- package/dist/player.js +18 -0
- package/dist/player.js.map +1 -0
- package/dist/policy.d.ts +53 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +55 -0
- package/dist/policy.js.map +1 -0
- package/dist/protocol.d.ts +54 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +51 -0
- package/dist/protocol.js.map +1 -0
- package/dist/result.d.ts +44 -0
- package/dist/result.d.ts.map +1 -0
- package/dist/result.js +5 -0
- package/dist/result.js.map +1 -0
- package/dist/scoring.d.ts +27 -0
- package/dist/scoring.d.ts.map +1 -0
- package/dist/scoring.js +6 -0
- package/dist/scoring.js.map +1 -0
- package/dist/slots.d.ts +47 -0
- package/dist/slots.d.ts.map +1 -0
- package/dist/slots.js +9 -0
- package/dist/slots.js.map +1 -0
- package/dist/snapshot.d.ts +23 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +22 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/style.d.ts +51 -0
- package/dist/style.d.ts.map +1 -0
- package/dist/style.js +36 -0
- package/dist/style.js.map +1 -0
- package/package.json +40 -4
- package/src/answers.ts +52 -0
- package/src/ast.ts +49 -0
- package/src/authoring.ts +475 -0
- package/src/checker.ts +91 -0
- package/src/compiled.ts +115 -0
- package/src/content.ts +156 -0
- package/src/declarations.ts +427 -0
- package/src/definition.ts +104 -0
- package/src/engine.ts +98 -0
- package/src/format.ts +67 -0
- package/src/help.ts +41 -0
- package/src/i18n/check.ts +67 -0
- package/src/i18n/format.ts +318 -0
- package/src/i18n/i18n.ts +92 -0
- package/src/i18n/types.ts +35 -0
- package/src/index.ts +201 -0
- package/src/issues.ts +107 -0
- package/src/json.ts +6 -0
- package/src/manifest.ts +193 -0
- package/src/player.ts +145 -0
- package/src/policy.ts +117 -0
- package/src/protocol.ts +65 -0
- package/src/result.ts +53 -0
- package/src/scoring.ts +31 -0
- package/src/slots.ts +57 -0
- package/src/snapshot.ts +40 -0
- package/src/style.ts +89 -0
package/src/engine.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The engine contract. `@astl/engine` implements it with `createEngine(options)`; other implementations
|
|
3
|
+
* (a remote validator, a port in another language) must pass the same conformance fixtures.
|
|
4
|
+
*/
|
|
5
|
+
import type { Answers } from './answers.js';
|
|
6
|
+
import type { AnswerKey, Compilation } from './compiled.js';
|
|
7
|
+
import type { ComponentDefinition } from './definition.js';
|
|
8
|
+
import type { MessageCatalog } from './i18n/types.js';
|
|
9
|
+
import type { Issue } from './issues.js';
|
|
10
|
+
import type { ComponentManifest } from './manifest.js';
|
|
11
|
+
import type { GradeResult, Solution } from './result.js';
|
|
12
|
+
import type { NormalisationProfile, SlotKind } from './slots.js';
|
|
13
|
+
import type { StyleTemplate } from './style.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Decides whether a URL in content may stay: asked with the element's tag and attribute (`img` and `src` for a
|
|
17
|
+
* picture in text, a component's tag and its `url` attribute). Only `true` keeps it: engines, players and the
|
|
18
|
+
* authoring kit treat a throw or any other answer as no (`strictUrlPolicy`). Default (`isSafeUrl`): absolute
|
|
19
|
+
* `http:`, `https:` and `mailto:` URLs.
|
|
20
|
+
*/
|
|
21
|
+
export type UrlPolicy = (
|
|
22
|
+
url: string,
|
|
23
|
+
context: { readonly tag: string; readonly attribute: string },
|
|
24
|
+
) => boolean;
|
|
25
|
+
|
|
26
|
+
export interface EngineOptions {
|
|
27
|
+
readonly components: readonly ComponentDefinition[];
|
|
28
|
+
/** Added to the built-in slot kinds (`text`, `number`, `choice`, `flag`). Same kind twice = error. */
|
|
29
|
+
readonly slotKinds?: readonly SlotKind[];
|
|
30
|
+
/**
|
|
31
|
+
* HMAC secret for opaque ids and permutations, at least 16 bytes. Keep it stable: it decides every view. Only
|
|
32
|
+
* `compile` needs it and throws without one. There is no default: a known secret undoes the keyed option order.
|
|
33
|
+
*/
|
|
34
|
+
readonly secret?: string | Uint8Array;
|
|
35
|
+
/** Which URLs stay in sources and views (`UrlPolicy`). Default `isSafeUrl`. */
|
|
36
|
+
readonly urlPolicy?: UrlPolicy;
|
|
37
|
+
/** Overrides of the default text comparison profile. */
|
|
38
|
+
readonly profile?: Partial<NormalisationProfile>;
|
|
39
|
+
/** Extra or replacement message catalogs (e.g. more locales) for `describe`. */
|
|
40
|
+
readonly catalogs?: readonly MessageCatalog[];
|
|
41
|
+
/**
|
|
42
|
+
* Style templates the hosts' players register, so `style-template` values can be checked: a name that is not
|
|
43
|
+
* registered, or not allowed at its scope or for its tag, gives the warning STYLE_TEMPLATE_UNKNOWN (the attribute
|
|
44
|
+
* stays in the view). Same name twice = error.
|
|
45
|
+
*/
|
|
46
|
+
readonly styleTemplates?: readonly StyleTemplate[];
|
|
47
|
+
/**
|
|
48
|
+
* The colours a page shows text on (hex), for the warning STYLE_LOW_CONTRAST: a colour declared in a `style` is
|
|
49
|
+
* compared with these where nothing else is declared around it. Without them, only colours both declared are
|
|
50
|
+
* compared.
|
|
51
|
+
*/
|
|
52
|
+
readonly groundColors?: GroundColors;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The colours a page shows text on (hex or `rgb()`). */
|
|
56
|
+
export interface GroundColors {
|
|
57
|
+
readonly surface: string;
|
|
58
|
+
readonly ink: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface CompileOptions {
|
|
62
|
+
/** Mixed into opaque ids and permutations, e.g. the exercise id, so two exercises never share ids. */
|
|
63
|
+
readonly salt?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface GradeOptions {
|
|
67
|
+
/** Grade one view page only (per-page check). */
|
|
68
|
+
readonly page?: string;
|
|
69
|
+
/** Grade one view element only (a check of one interaction): the groups of its slots. */
|
|
70
|
+
readonly element?: string;
|
|
71
|
+
/**
|
|
72
|
+
* Hints used, by view element id or view page id (the first n of its hints). A group loses the costs of the hints
|
|
73
|
+
* used of its element and of its page, each a fraction of the group's maximum, never below 0. Its verdict stays.
|
|
74
|
+
*/
|
|
75
|
+
readonly hintsUsed?: Readonly<Record<string, number>>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ValidationReport {
|
|
79
|
+
/** True when there are no errors (warnings allowed). */
|
|
80
|
+
readonly ok: boolean;
|
|
81
|
+
readonly issues: readonly Issue[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export type CompileResult =
|
|
85
|
+
| ({ readonly ok: true; readonly issues: readonly Issue[] } & Compilation)
|
|
86
|
+
| { readonly ok: false; readonly issues: readonly Issue[] };
|
|
87
|
+
|
|
88
|
+
export interface Engine {
|
|
89
|
+
/** Manifests of the registered components, in registration order. */
|
|
90
|
+
readonly manifests: readonly ComponentManifest[];
|
|
91
|
+
validate(source: string): ValidationReport;
|
|
92
|
+
compile(source: string, options?: CompileOptions): Promise<CompileResult>;
|
|
93
|
+
/** Pure and synchronous: safe to call per request. Malformed answers count as unanswered. */
|
|
94
|
+
grade(key: AnswerKey, answers: Answers, options?: GradeOptions): GradeResult;
|
|
95
|
+
solution(key: AnswerKey, options?: GradeOptions): Solution;
|
|
96
|
+
/** Renders an issue in the given UI locale (falls back to English, then to the code). */
|
|
97
|
+
describe(issue: Issue, locale: string): string;
|
|
98
|
+
}
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content format constants and the id grammar.
|
|
3
|
+
*
|
|
4
|
+
* Source: `<astl-doc format="1" lang="pl">` with `<astl-page>` children (or loose content = one implicit page).
|
|
5
|
+
* Source ids are written by authors and editors; opaque ids are written by the compiler into views.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Current content format. Written as `format="1"` on `<astl-doc>` in sources and views. */
|
|
9
|
+
export const FORMAT_VERSION = 1;
|
|
10
|
+
export const SUPPORTED_FORMATS: readonly number[] = [1];
|
|
11
|
+
|
|
12
|
+
export const DOC_TAG = 'astl-doc';
|
|
13
|
+
export const PAGE_TAG = 'astl-page';
|
|
14
|
+
|
|
15
|
+
/** Largest accepted source, in UTF-16 code units. */
|
|
16
|
+
export const MAX_SOURCE_LENGTH = 1_000_000;
|
|
17
|
+
|
|
18
|
+
/** Author ids: a letter, then letters, digits, `_` or `-`; at most 64 characters. Unique within one document. */
|
|
19
|
+
export const SOURCE_ID_PATTERN: RegExp = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
20
|
+
|
|
21
|
+
/** Opaque ids in views: `k` + 16 lowercase base32 characters (80 bits of an HMAC-SHA-256). */
|
|
22
|
+
export const OPAQUE_ID_PATTERN: RegExp = /^k[a-z2-7]{16}$/;
|
|
23
|
+
|
|
24
|
+
/** Custom element names that components may use (HTML custom element rules, lowercase ASCII). */
|
|
25
|
+
export const ELEMENT_TAG_PATTERN: RegExp = /^[a-z][a-z0-9]*-[a-z0-9-]*$/;
|
|
26
|
+
|
|
27
|
+
/** Prefix reserved for built-in Astrolabe elements. */
|
|
28
|
+
export const BUILT_IN_PREFIX = 'astl-';
|
|
29
|
+
|
|
30
|
+
export function isSourceId(value: string): boolean {
|
|
31
|
+
return SOURCE_ID_PATTERN.test(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function isOpaqueId(value: string): boolean {
|
|
35
|
+
return OPAQUE_ID_PATTERN.test(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type Direction = 'ltr' | 'rtl';
|
|
39
|
+
|
|
40
|
+
/** Scripts written right to left, by BCP 47 primary language subtag (enough for the markets we target). */
|
|
41
|
+
const RTL_LANGUAGES: ReadonlySet<string> = new Set([
|
|
42
|
+
'ar',
|
|
43
|
+
'arc',
|
|
44
|
+
'ckb',
|
|
45
|
+
'dv',
|
|
46
|
+
'fa',
|
|
47
|
+
'he',
|
|
48
|
+
'ks',
|
|
49
|
+
'ku',
|
|
50
|
+
'ps',
|
|
51
|
+
'sd',
|
|
52
|
+
'ug',
|
|
53
|
+
'ur',
|
|
54
|
+
'yi',
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
/** Writing direction for a BCP 47 tag, e.g. `he` -> `rtl`, `pl-PL` -> `ltr`. Script subtags win (`az-Arab`). */
|
|
58
|
+
export function directionOf(lang: string): Direction {
|
|
59
|
+
const parts = lang.toLowerCase().split('-');
|
|
60
|
+
if (parts.includes('arab') || parts.includes('hebr') || parts.includes('thaa') || parts.includes('syrc'))
|
|
61
|
+
return 'rtl';
|
|
62
|
+
if (parts.includes('latn') || parts.includes('cyrl')) return 'ltr';
|
|
63
|
+
return RTL_LANGUAGES.has(parts[0] ?? '') ? 'rtl' : 'ltr';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Loose BCP 47 check: `pl`, `pl-PL`, `zh-Hant-TW`, `sr-Latn`. */
|
|
67
|
+
export const LANGUAGE_TAG_PATTERN: RegExp = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*$/;
|
package/src/help.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Help for students (content format 1, additive): hints, an explanation and feedback texts. Inside a graded component
|
|
3
|
+
* they belong to that interaction; directly on a page, to the page. They usually give the answer away, so they are
|
|
4
|
+
* key-side data: compile moves their content into the answer key (`AnswerKey.help`), and the view keeps only what a
|
|
5
|
+
* player needs to offer them (`ElementHelp`, written as the attributes `HELP_ATTRIBUTES`).
|
|
6
|
+
*/
|
|
7
|
+
/** One hint, rich content; hints come in source order. `cost`: the fraction 0..1 of the points it takes off. */
|
|
8
|
+
export const HINT_TAG = 'astl-hint';
|
|
9
|
+
/** Why the answer is what it is; at most one per interaction or page. */
|
|
10
|
+
export const EXPLANATION_TAG = 'astl-explanation';
|
|
11
|
+
/** The text for one verdict, picked by `when`; at most one per `when`. */
|
|
12
|
+
export const FEEDBACK_TAG = 'astl-feedback';
|
|
13
|
+
export const HELP_TAGS: ReadonlySet<string> = new Set([HINT_TAG, EXPLANATION_TAG, FEEDBACK_TAG]);
|
|
14
|
+
|
|
15
|
+
/** The `when` of a feedback text: one per group verdict, `omitted` for `empty`. */
|
|
16
|
+
export type FeedbackVariant = 'correct' | 'incorrect' | 'partial' | 'omitted';
|
|
17
|
+
export const FEEDBACK_VARIANTS: readonly FeedbackVariant[] = ['correct', 'incorrect', 'partial', 'omitted'];
|
|
18
|
+
|
|
19
|
+
/** What a view says about the help of an interaction or a page, so a player can offer it: never its text. */
|
|
20
|
+
export interface ElementHelp {
|
|
21
|
+
/** The cost of each hint, in order (0: free). */
|
|
22
|
+
readonly hints: readonly number[];
|
|
23
|
+
readonly explanation: boolean;
|
|
24
|
+
/** The variants with a text, in `FEEDBACK_VARIANTS` order. */
|
|
25
|
+
readonly feedback: readonly FeedbackVariant[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The view attributes of `ElementHelp`, on a graded component or a page: `hints="0 0.25"` (the costs, space
|
|
30
|
+
* separated), `explanation` (present when there is one) and `feedback="correct incorrect"` (the variants with a text,
|
|
31
|
+
* in `FEEDBACK_VARIANTS` order). Only those with something to say are written; sources never carry them. The engine
|
|
32
|
+
* writes them (compile), the player reads them.
|
|
33
|
+
*/
|
|
34
|
+
export const HELP_ATTRIBUTES: readonly string[] = ['hints', 'explanation', 'feedback'];
|
|
35
|
+
|
|
36
|
+
/** A feedback text as a student gets it: the variant of the verdict and the author's text (HTML of format 1). */
|
|
37
|
+
export interface Feedback {
|
|
38
|
+
/** The verdict's variant; its text is the `incorrect` one when a partial verdict has none of its own. */
|
|
39
|
+
readonly variant: FeedbackVariant;
|
|
40
|
+
readonly html: string;
|
|
41
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catalog checks for CI: every translation has the same keys and parameters as the source catalog, parses, and
|
|
3
|
+
* covers every plural category its locale needs (Polish: one, few, many, other).
|
|
4
|
+
*/
|
|
5
|
+
import { type MessagePart, messageParams, parseMessage, pluralCategories } from './format.js';
|
|
6
|
+
import type { MessageCatalog } from './types.js';
|
|
7
|
+
|
|
8
|
+
export interface CatalogProblem {
|
|
9
|
+
readonly key: string;
|
|
10
|
+
readonly kind: 'missing' | 'extra' | 'syntax' | 'params' | 'plural';
|
|
11
|
+
readonly detail: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function pluralProblems(parts: readonly MessagePart[], locale: string): string[] {
|
|
15
|
+
const out: string[] = [];
|
|
16
|
+
const walk = (list: readonly MessagePart[]) => {
|
|
17
|
+
for (const p of list) {
|
|
18
|
+
if (p.type === 'plural') {
|
|
19
|
+
const needed = pluralCategories(locale, p.ordinal);
|
|
20
|
+
const missing = needed.filter((c) => !Object.hasOwn(p.options, c));
|
|
21
|
+
if (missing.length > 0) out.push(`{${p.name}} lacks ${missing.join(', ')}`);
|
|
22
|
+
}
|
|
23
|
+
if (p.type === 'plural' || p.type === 'select') for (const sub of Object.values(p.options)) walk(sub);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
walk(parts);
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Problems of `catalog` alone (syntax and plural coverage). */
|
|
31
|
+
export function checkCatalog(catalog: MessageCatalog): CatalogProblem[] {
|
|
32
|
+
const problems: CatalogProblem[] = [];
|
|
33
|
+
for (const [key, message] of Object.entries(catalog.messages)) {
|
|
34
|
+
try {
|
|
35
|
+
const parts = parseMessage(message);
|
|
36
|
+
for (const detail of pluralProblems(parts, catalog.locale))
|
|
37
|
+
problems.push({ key, kind: 'plural', detail });
|
|
38
|
+
} catch (e) {
|
|
39
|
+
problems.push({ key, kind: 'syntax', detail: (e as Error).message });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return problems;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Problems of a translation compared with its source catalog (same namespace). */
|
|
46
|
+
export function compareCatalogs(source: MessageCatalog, translation: MessageCatalog): CatalogProblem[] {
|
|
47
|
+
const problems = checkCatalog(translation);
|
|
48
|
+
for (const [key, message] of Object.entries(source.messages)) {
|
|
49
|
+
const other = Object.hasOwn(translation.messages, key) ? translation.messages[key] : undefined;
|
|
50
|
+
if (other === undefined) {
|
|
51
|
+
problems.push({ key, kind: 'missing', detail: `missing in ${translation.locale}` });
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const want = [...messageParams(parseMessage(message))].sort().join(',');
|
|
56
|
+
const got = [...messageParams(parseMessage(other))].sort().join(',');
|
|
57
|
+
if (want !== got) problems.push({ key, kind: 'params', detail: `expected {${want}}, got {${got}}` });
|
|
58
|
+
} catch {
|
|
59
|
+
// Syntax problems are already reported by checkCatalog.
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
for (const key of Object.keys(translation.messages)) {
|
|
63
|
+
if (!Object.hasOwn(source.messages, key))
|
|
64
|
+
problems.push({ key, kind: 'extra', detail: `not in ${source.locale}` });
|
|
65
|
+
}
|
|
66
|
+
return problems;
|
|
67
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A dependency-free ICU MessageFormat 1 subset: `{name}`, `{name, number[, integer|percent]}`,
|
|
3
|
+
* `{name, plural|selectordinal, [offset:n] =0 {..} one {..} few {..} many {..} other {..}}` with `#`,
|
|
4
|
+
* and `{name, select, a {..} other {..}}`, nested to any depth. Apostrophe quoting as in ICU
|
|
5
|
+
* (`''` is a literal apostrophe, `'{'` quotes syntax characters). Dates and times are not supported on purpose:
|
|
6
|
+
* hosts format them and pass strings.
|
|
7
|
+
*/
|
|
8
|
+
import type { MessageFormatter, MessageParams } from './types.js';
|
|
9
|
+
|
|
10
|
+
export type MessagePart =
|
|
11
|
+
| { readonly type: 'text'; readonly value: string }
|
|
12
|
+
| {
|
|
13
|
+
readonly type: 'arg';
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly style: 'plain' | 'number' | 'integer' | 'percent';
|
|
16
|
+
}
|
|
17
|
+
| {
|
|
18
|
+
readonly type: 'plural';
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly ordinal: boolean;
|
|
21
|
+
readonly offset: number;
|
|
22
|
+
readonly options: Readonly<Record<string, readonly MessagePart[]>>;
|
|
23
|
+
}
|
|
24
|
+
| {
|
|
25
|
+
readonly type: 'select';
|
|
26
|
+
readonly name: string;
|
|
27
|
+
readonly options: Readonly<Record<string, readonly MessagePart[]>>;
|
|
28
|
+
}
|
|
29
|
+
| { readonly type: 'pound' };
|
|
30
|
+
|
|
31
|
+
export class MessageSyntaxError extends Error {
|
|
32
|
+
readonly offset: number;
|
|
33
|
+
|
|
34
|
+
constructor(message: string, offset: number) {
|
|
35
|
+
super(`${message} at offset ${offset}`);
|
|
36
|
+
this.name = 'MessageSyntaxError';
|
|
37
|
+
this.offset = offset;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const PLURAL_KEYWORDS: ReadonlySet<string> = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
|
|
42
|
+
|
|
43
|
+
class Parser {
|
|
44
|
+
private pos = 0;
|
|
45
|
+
|
|
46
|
+
constructor(private readonly src: string) {}
|
|
47
|
+
|
|
48
|
+
parse(): MessagePart[] {
|
|
49
|
+
const parts = this.message(false);
|
|
50
|
+
if (this.pos < this.src.length) throw new MessageSyntaxError('Unexpected "}"', this.pos);
|
|
51
|
+
return parts;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Parses until an unmatched `}` (not consumed) or the end. */
|
|
55
|
+
private message(inPlural: boolean): MessagePart[] {
|
|
56
|
+
const parts: MessagePart[] = [];
|
|
57
|
+
let buf = '';
|
|
58
|
+
const flush = () => {
|
|
59
|
+
if (buf !== '') parts.push({ type: 'text', value: buf });
|
|
60
|
+
buf = '';
|
|
61
|
+
};
|
|
62
|
+
while (this.pos < this.src.length) {
|
|
63
|
+
const ch = this.src[this.pos] as string;
|
|
64
|
+
if (ch === "'") {
|
|
65
|
+
buf += this.apostrophe(inPlural);
|
|
66
|
+
} else if (ch === '{') {
|
|
67
|
+
flush();
|
|
68
|
+
parts.push(this.argument());
|
|
69
|
+
} else if (ch === '}') {
|
|
70
|
+
break;
|
|
71
|
+
} else if (ch === '#' && inPlural) {
|
|
72
|
+
flush();
|
|
73
|
+
parts.push({ type: 'pound' });
|
|
74
|
+
this.pos++;
|
|
75
|
+
} else {
|
|
76
|
+
buf += ch;
|
|
77
|
+
this.pos++;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
flush();
|
|
81
|
+
return parts;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private apostrophe(inPlural: boolean): string {
|
|
85
|
+
const next = this.src[this.pos + 1];
|
|
86
|
+
if (next === "'") {
|
|
87
|
+
this.pos += 2;
|
|
88
|
+
return "'";
|
|
89
|
+
}
|
|
90
|
+
if (next === '{' || next === '}' || (inPlural && next === '#')) {
|
|
91
|
+
// Quoted literal until the next lone apostrophe.
|
|
92
|
+
this.pos++;
|
|
93
|
+
let out = '';
|
|
94
|
+
while (this.pos < this.src.length) {
|
|
95
|
+
const ch = this.src[this.pos] as string;
|
|
96
|
+
if (ch === "'") {
|
|
97
|
+
if (this.src[this.pos + 1] === "'") {
|
|
98
|
+
out += "'";
|
|
99
|
+
this.pos += 2;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
this.pos++;
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
out += ch;
|
|
106
|
+
this.pos++;
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
this.pos++;
|
|
111
|
+
return "'";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private argument(): MessagePart {
|
|
115
|
+
const start = this.pos;
|
|
116
|
+
this.pos++; // {
|
|
117
|
+
const name = this.word();
|
|
118
|
+
if (name === '') throw new MessageSyntaxError('Missing argument name', this.pos);
|
|
119
|
+
this.space();
|
|
120
|
+
if (this.eat('}')) return { type: 'arg', name, style: 'plain' };
|
|
121
|
+
if (!this.eat(',')) throw new MessageSyntaxError('Expected "," or "}"', this.pos);
|
|
122
|
+
this.space();
|
|
123
|
+
const kind = this.word();
|
|
124
|
+
this.space();
|
|
125
|
+
if (kind === 'number') {
|
|
126
|
+
let style: 'number' | 'integer' | 'percent' = 'number';
|
|
127
|
+
if (this.eat(',')) {
|
|
128
|
+
this.space();
|
|
129
|
+
const s = this.word();
|
|
130
|
+
if (s !== 'integer' && s !== 'percent')
|
|
131
|
+
throw new MessageSyntaxError(`Unsupported number style "${s}"`, this.pos);
|
|
132
|
+
style = s;
|
|
133
|
+
this.space();
|
|
134
|
+
}
|
|
135
|
+
this.expect('}');
|
|
136
|
+
return { type: 'arg', name, style };
|
|
137
|
+
}
|
|
138
|
+
if (kind === 'plural' || kind === 'selectordinal' || kind === 'select') {
|
|
139
|
+
this.expect(',');
|
|
140
|
+
this.space();
|
|
141
|
+
let offset = 0;
|
|
142
|
+
if (kind !== 'select' && this.src.startsWith('offset:', this.pos)) {
|
|
143
|
+
this.pos += 'offset:'.length;
|
|
144
|
+
this.space();
|
|
145
|
+
const n = this.word();
|
|
146
|
+
offset = Number(n);
|
|
147
|
+
if (!Number.isInteger(offset) || offset < 0)
|
|
148
|
+
throw new MessageSyntaxError(`Invalid offset "${n}"`, this.pos);
|
|
149
|
+
this.space();
|
|
150
|
+
}
|
|
151
|
+
// Null prototype: option keys like `__proto__` or `constructor` stay plain data.
|
|
152
|
+
const options: Record<string, readonly MessagePart[]> = Object.create(null);
|
|
153
|
+
while (!this.eat('}')) {
|
|
154
|
+
if (this.pos >= this.src.length) throw new MessageSyntaxError('Unclosed argument', start);
|
|
155
|
+
const key = this.word();
|
|
156
|
+
if (key === '') throw new MessageSyntaxError('Expected an option key', this.pos);
|
|
157
|
+
if (kind !== 'select' && !PLURAL_KEYWORDS.has(key) && !/^=\d+$/.test(key)) {
|
|
158
|
+
throw new MessageSyntaxError(`Invalid plural key "${key}"`, this.pos);
|
|
159
|
+
}
|
|
160
|
+
if (Object.hasOwn(options, key)) throw new MessageSyntaxError(`Duplicate option "${key}"`, this.pos);
|
|
161
|
+
this.space();
|
|
162
|
+
this.expect('{');
|
|
163
|
+
options[key] = this.message(kind !== 'select');
|
|
164
|
+
this.expect('}');
|
|
165
|
+
this.space();
|
|
166
|
+
}
|
|
167
|
+
if (!Object.hasOwn(options, 'other')) throw new MessageSyntaxError('Missing "other" option', start);
|
|
168
|
+
return kind === 'select'
|
|
169
|
+
? { type: 'select', name, options }
|
|
170
|
+
: { type: 'plural', name, ordinal: kind === 'selectordinal', offset, options };
|
|
171
|
+
}
|
|
172
|
+
throw new MessageSyntaxError(`Unsupported argument type "${kind}"`, this.pos);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private word(): string {
|
|
176
|
+
const m = /^[^\s{}#,'"]+/u.exec(this.src.slice(this.pos));
|
|
177
|
+
if (!m) return '';
|
|
178
|
+
this.pos += m[0].length;
|
|
179
|
+
return m[0];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private space(): void {
|
|
183
|
+
while (this.pos < this.src.length && /\s/u.test(this.src[this.pos] as string)) this.pos++;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private eat(ch: string): boolean {
|
|
187
|
+
if (this.src[this.pos] === ch) {
|
|
188
|
+
this.pos++;
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private expect(ch: string): void {
|
|
195
|
+
if (!this.eat(ch)) throw new MessageSyntaxError(`Expected "${ch}"`, this.pos);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function parseMessage(message: string): MessagePart[] {
|
|
200
|
+
return new Parser(message).parse();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Names of all arguments a message uses, including plural and select selectors. */
|
|
204
|
+
export function messageParams(parts: readonly MessagePart[]): Set<string> {
|
|
205
|
+
const names = new Set<string>();
|
|
206
|
+
const walk = (list: readonly MessagePart[]) => {
|
|
207
|
+
for (const p of list) {
|
|
208
|
+
if (p.type === 'arg') names.add(p.name);
|
|
209
|
+
if (p.type === 'plural' || p.type === 'select') {
|
|
210
|
+
names.add(p.name);
|
|
211
|
+
for (const sub of Object.values(p.options)) walk(sub);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
walk(parts);
|
|
216
|
+
return names;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Own-property lookup: option keys such as `constructor` must never resolve to Object.prototype members. */
|
|
220
|
+
function option(
|
|
221
|
+
options: Readonly<Record<string, readonly MessagePart[]>>,
|
|
222
|
+
key: string,
|
|
223
|
+
): readonly MessagePart[] | undefined {
|
|
224
|
+
return Object.hasOwn(options, key) ? options[key] : undefined;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function render(
|
|
228
|
+
parts: readonly MessagePart[],
|
|
229
|
+
params: MessageParams,
|
|
230
|
+
locale: string,
|
|
231
|
+
pound: string | null,
|
|
232
|
+
): string {
|
|
233
|
+
let out = '';
|
|
234
|
+
for (const p of parts) {
|
|
235
|
+
switch (p.type) {
|
|
236
|
+
case 'text':
|
|
237
|
+
out += p.value;
|
|
238
|
+
break;
|
|
239
|
+
case 'pound':
|
|
240
|
+
out += pound ?? '#';
|
|
241
|
+
break;
|
|
242
|
+
case 'arg': {
|
|
243
|
+
const v = params[p.name];
|
|
244
|
+
if (v === undefined) out += `{${p.name}}`;
|
|
245
|
+
else if (typeof v === 'number' || p.style !== 'plain')
|
|
246
|
+
out += formatNumber(Number(v), p.style, locale);
|
|
247
|
+
else out += v;
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
case 'select': {
|
|
251
|
+
const v = params[p.name];
|
|
252
|
+
const branch =
|
|
253
|
+
(v !== undefined ? option(p.options, String(v)) : undefined) ?? option(p.options, 'other') ?? [];
|
|
254
|
+
out += render(branch, params, locale, pound);
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
case 'plural': {
|
|
258
|
+
const n = Number(params[p.name]);
|
|
259
|
+
if (Number.isNaN(n)) {
|
|
260
|
+
out += render(option(p.options, 'other') ?? [], params, locale, `{${p.name}}`);
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
const exact = option(p.options, `=${n}`);
|
|
264
|
+
const value = n - p.offset;
|
|
265
|
+
const category = pluralRules(locale, p.ordinal).select(value);
|
|
266
|
+
const branch = exact ?? option(p.options, category) ?? option(p.options, 'other') ?? [];
|
|
267
|
+
out += render(branch, params, locale, formatNumber(value, 'number', locale));
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const pluralCache = new Map<string, Intl.PluralRules>();
|
|
276
|
+
|
|
277
|
+
function pluralRules(locale: string, ordinal: boolean): Intl.PluralRules {
|
|
278
|
+
const id = `${locale}|${ordinal ? 'o' : 'c'}`;
|
|
279
|
+
let rules = pluralCache.get(id);
|
|
280
|
+
if (!rules) {
|
|
281
|
+
rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });
|
|
282
|
+
pluralCache.set(id, rules);
|
|
283
|
+
}
|
|
284
|
+
return rules;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function formatNumber(
|
|
288
|
+
value: number,
|
|
289
|
+
style: 'plain' | 'number' | 'integer' | 'percent',
|
|
290
|
+
locale: string,
|
|
291
|
+
): string {
|
|
292
|
+
if (style === 'integer') return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(value);
|
|
293
|
+
if (style === 'percent') return new Intl.NumberFormat(locale, { style: 'percent' }).format(value);
|
|
294
|
+
return new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(value);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Plural categories a locale needs, e.g. `pl` -> one, few, many, other. */
|
|
298
|
+
export function pluralCategories(locale: string, ordinal = false): readonly string[] {
|
|
299
|
+
return pluralRules(locale, ordinal).resolvedOptions().pluralCategories as readonly string[];
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const parsedCache = new Map<string, readonly MessagePart[] | null>();
|
|
303
|
+
|
|
304
|
+
/** The default MessageFormatter. A message with a syntax error renders as its raw text instead of throwing. */
|
|
305
|
+
export const icuFormatter: MessageFormatter = {
|
|
306
|
+
format(message: string, params: MessageParams, locale: string): string {
|
|
307
|
+
let parts = parsedCache.get(message);
|
|
308
|
+
if (parts === undefined) {
|
|
309
|
+
try {
|
|
310
|
+
parts = parseMessage(message);
|
|
311
|
+
} catch {
|
|
312
|
+
parts = null;
|
|
313
|
+
}
|
|
314
|
+
parsedCache.set(message, parts);
|
|
315
|
+
}
|
|
316
|
+
return parts === null ? message : render(parts, params, locale, null);
|
|
317
|
+
},
|
|
318
|
+
};
|
package/src/i18n/i18n.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { icuFormatter } from './format.js';
|
|
2
|
+
import type { I18n, MessageCatalog, MessageFormatter, MessageParams, Translate } from './types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* BCP 47 lookup (RFC 4647 section 3.4, extended): for each requested tag try the tag, then shorter prefixes
|
|
6
|
+
* (`pl-PL` -> `pl`), then any available tag with the same language (`pt` -> `pt-BR`). Case-insensitive.
|
|
7
|
+
*/
|
|
8
|
+
export function negotiateLocale(
|
|
9
|
+
requested: readonly string[],
|
|
10
|
+
available: readonly string[],
|
|
11
|
+
fallback: string,
|
|
12
|
+
): string {
|
|
13
|
+
const byLower = new Map(available.map((a) => [a.toLowerCase(), a]));
|
|
14
|
+
for (const tag of requested) {
|
|
15
|
+
const parts = tag.toLowerCase().split('-');
|
|
16
|
+
for (let n = parts.length; n > 0; n--) {
|
|
17
|
+
const hit = byLower.get(parts.slice(0, n).join('-'));
|
|
18
|
+
if (hit) return hit;
|
|
19
|
+
}
|
|
20
|
+
const lang = parts[0];
|
|
21
|
+
const sameLanguage = available.find((a) => a.toLowerCase().split('-')[0] === lang);
|
|
22
|
+
if (sameLanguage) return sameLanguage;
|
|
23
|
+
}
|
|
24
|
+
return fallback;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `pl-PL` -> [`pl-PL`, `pl`]. */
|
|
28
|
+
function chain(locale: string): string[] {
|
|
29
|
+
const parts = locale.split('-');
|
|
30
|
+
const out: string[] = [];
|
|
31
|
+
for (let n = parts.length; n > 0; n--) out.push(parts.slice(0, n).join('-').toLowerCase());
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface CreateI18nOptions {
|
|
36
|
+
readonly catalogs: readonly MessageCatalog[];
|
|
37
|
+
/** Default `en`. */
|
|
38
|
+
readonly fallbackLocale?: string;
|
|
39
|
+
readonly formatter?: MessageFormatter;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function createI18n(options: CreateI18nOptions): I18n {
|
|
43
|
+
const fallbackLocale = options.fallbackLocale ?? 'en';
|
|
44
|
+
const formatter = options.formatter ?? icuFormatter;
|
|
45
|
+
// namespace -> lowercased locale -> { locale, messages }
|
|
46
|
+
const table = new Map<string, Map<string, { locale: string; messages: Record<string, string> }>>();
|
|
47
|
+
for (const c of options.catalogs) {
|
|
48
|
+
let byLocale = table.get(c.namespace);
|
|
49
|
+
if (!byLocale) {
|
|
50
|
+
byLocale = new Map();
|
|
51
|
+
table.set(c.namespace, byLocale);
|
|
52
|
+
}
|
|
53
|
+
const id = c.locale.toLowerCase();
|
|
54
|
+
const entry = byLocale.get(id) ?? {
|
|
55
|
+
locale: c.locale,
|
|
56
|
+
messages: Object.create(null) as Record<string, string>,
|
|
57
|
+
};
|
|
58
|
+
Object.assign(entry.messages, c.messages);
|
|
59
|
+
byLocale.set(id, entry);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const t = (locale: string, namespace: string, key: string, params: MessageParams = {}): string => {
|
|
63
|
+
const byLocale = table.get(namespace);
|
|
64
|
+
if (byLocale) {
|
|
65
|
+
for (const id of [...chain(locale), ...chain(fallbackLocale)]) {
|
|
66
|
+
const entry = byLocale.get(id);
|
|
67
|
+
const message = entry && Object.hasOwn(entry.messages, key) ? entry.messages[key] : undefined;
|
|
68
|
+
if (entry && message !== undefined) return formatter.format(message, params, entry.locale);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return key;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
fallbackLocale,
|
|
76
|
+
locales(namespace?: string): readonly string[] {
|
|
77
|
+
const out = new Set<string>();
|
|
78
|
+
for (const [ns, byLocale] of table) {
|
|
79
|
+
if (namespace !== undefined && ns !== namespace) continue;
|
|
80
|
+
for (const entry of byLocale.values()) out.add(entry.locale);
|
|
81
|
+
}
|
|
82
|
+
return [...out];
|
|
83
|
+
},
|
|
84
|
+
t,
|
|
85
|
+
translator(locale: string, namespace: string): Translate {
|
|
86
|
+
return (key, params) => t(locale, namespace, key, params);
|
|
87
|
+
},
|
|
88
|
+
with(catalogs: readonly MessageCatalog[]): I18n {
|
|
89
|
+
return createI18n({ ...options, catalogs: [...options.catalogs, ...catalogs] });
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|