@astl/engine 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 +35 -0
- package/LICENSE +202 -0
- package/README.md +41 -0
- package/dist/analyse.d.ts +68 -0
- package/dist/analyse.d.ts.map +1 -0
- package/dist/analyse.js +1179 -0
- package/dist/analyse.js.map +1 -0
- package/dist/checker.d.ts +19 -0
- package/dist/checker.d.ts.map +1 -0
- package/dist/checker.js +103 -0
- package/dist/checker.js.map +1 -0
- package/dist/compile.d.ts +16 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +329 -0
- package/dist/compile.js.map +1 -0
- package/dist/conformance.d.ts +35 -0
- package/dist/conformance.d.ts.map +1 -0
- package/dist/conformance.js +101 -0
- package/dist/conformance.js.map +1 -0
- package/dist/engine.d.ts +13 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +231 -0
- package/dist/engine.js.map +1 -0
- package/dist/grade.d.ts +9 -0
- package/dist/grade.d.ts.map +1 -0
- package/dist/grade.js +192 -0
- package/dist/grade.js.map +1 -0
- package/dist/guard.d.ts +45 -0
- package/dist/guard.d.ts.map +1 -0
- package/dist/guard.js +327 -0
- package/dist/guard.js.map +1 -0
- package/dist/help.d.ts +32 -0
- package/dist/help.d.ts.map +1 -0
- package/dist/help.js +120 -0
- package/dist/help.js.map +1 -0
- package/dist/html.d.ts +31 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +246 -0
- package/dist/html.js.map +1 -0
- package/dist/ids.d.ts +35 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +126 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/kit/attributes.d.ts +6 -0
- package/dist/kit/attributes.d.ts.map +1 -0
- package/dist/kit/attributes.js +20 -0
- package/dist/kit/attributes.js.map +1 -0
- package/dist/kit/index.d.ts +43 -0
- package/dist/kit/index.d.ts.map +1 -0
- package/dist/kit/index.js +118 -0
- package/dist/kit/index.js.map +1 -0
- package/dist/limits.d.ts +17 -0
- package/dist/limits.d.ts.map +1 -0
- package/dist/limits.js +173 -0
- package/dist/limits.js.map +1 -0
- package/dist/messages/en.json +48 -0
- package/dist/messages/pl.json +48 -0
- package/dist/messages.d.ts +4 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +9 -0
- package/dist/messages.js.map +1 -0
- package/dist/round.d.ts +3 -0
- package/dist/round.d.ts.map +1 -0
- package/dist/round.js +5 -0
- package/dist/round.js.map +1 -0
- package/dist/slot-kinds.d.ts +58 -0
- package/dist/slot-kinds.d.ts.map +1 -0
- package/dist/slot-kinds.js +151 -0
- package/dist/slot-kinds.js.map +1 -0
- package/dist/text.d.ts +23 -0
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +236 -0
- package/dist/text.js.map +1 -0
- package/package.json +39 -4
- package/src/analyse.ts +1396 -0
- package/src/checker.ts +132 -0
- package/src/compile.ts +394 -0
- package/src/conformance.ts +120 -0
- package/src/engine.ts +274 -0
- package/src/grade.ts +229 -0
- package/src/guard.ts +356 -0
- package/src/help.ts +141 -0
- package/src/html.ts +274 -0
- package/src/ids.ts +144 -0
- package/src/index.ts +12 -0
- package/src/kit/attributes.ts +21 -0
- package/src/kit/index.ts +140 -0
- package/src/limits.ts +153 -0
- package/src/messages/en.json +48 -0
- package/src/messages/pl.json +48 -0
- package/src/messages.ts +9 -0
- package/src/round.ts +4 -0
- package/src/slot-kinds.ts +212 -0
- package/src/text.ts +234 -0
package/src/html.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML <-> core AST. Parsing follows the HTML standard (parse5, fragment mode), so the engine sees the same tree a
|
|
3
|
+
* browser would build. Serialisation is deterministic: the same tree always gives the same bytes.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
type ElementNode,
|
|
7
|
+
element,
|
|
8
|
+
MAX_ATTRIBUTES_PER_ELEMENT,
|
|
9
|
+
MAX_NESTING_DEPTH,
|
|
10
|
+
type Node,
|
|
11
|
+
text,
|
|
12
|
+
} from '@astl/core';
|
|
13
|
+
import {
|
|
14
|
+
type DefaultTreeAdapterMap,
|
|
15
|
+
type DefaultTreeAdapterTypes,
|
|
16
|
+
defaultTreeAdapter,
|
|
17
|
+
parseFragment,
|
|
18
|
+
type TreeAdapter,
|
|
19
|
+
} from 'parse5';
|
|
20
|
+
import { mostAttributes } from './limits.js';
|
|
21
|
+
|
|
22
|
+
type ParsedNode = DefaultTreeAdapterTypes.ChildNode;
|
|
23
|
+
type ParsedParent = DefaultTreeAdapterTypes.ParentNode;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Parses HTML (a whole source or a single element snippet) into core nodes. Comments and doctypes are dropped,
|
|
27
|
+
* tag and attribute names are lowercased, `<template>` content is dropped and adjacent text nodes are merged.
|
|
28
|
+
*
|
|
29
|
+
* The result is stable: serialising it and parsing again gives the same tree. The HTML parser alone does not promise
|
|
30
|
+
* that (`<h3><table><h6>` puts the h6 inside the h3, and re-parsing `<h3><h6>` closes the h3), so the serialisation
|
|
31
|
+
* is re-parsed until it stops changing; well-formed input settles after one check.
|
|
32
|
+
*
|
|
33
|
+
* Throws a RangeError for input nested deeper than MAX_NESTING_DEPTH elements or with an element carrying more than
|
|
34
|
+
* MAX_ATTRIBUTES_PER_ELEMENT attributes (`validate` reports SOURCE_TOO_DEEP and SOURCE_TOO_COMPLEX instead).
|
|
35
|
+
*/
|
|
36
|
+
export function parseHtml(html: string): Node[] {
|
|
37
|
+
if (mostAttributes(html, MAX_ATTRIBUTES_PER_ELEMENT) > MAX_ATTRIBUTES_PER_ELEMENT) {
|
|
38
|
+
throw new RangeError(`HTML has an element with more than ${MAX_ATTRIBUTES_PER_ELEMENT} attributes`);
|
|
39
|
+
}
|
|
40
|
+
const nodes = parseSource(html);
|
|
41
|
+
if (nodes === null) throw new RangeError(`HTML is nested deeper than ${MAX_NESTING_DEPTH} elements`);
|
|
42
|
+
return nodes;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Like parseHtml, but returns null for input nested deeper than MAX_NESTING_DEPTH elements. */
|
|
46
|
+
export function parseSource(html: string): Node[] | null {
|
|
47
|
+
let nodes = parseOnce(html);
|
|
48
|
+
if (nodes === null) return null;
|
|
49
|
+
let serialised = serializeHtml(nodes);
|
|
50
|
+
for (let round = 0; round < MAX_ROUNDS; round++) {
|
|
51
|
+
const again = parseOnce(serialised);
|
|
52
|
+
if (again === null) return null;
|
|
53
|
+
const next = serializeHtml(again);
|
|
54
|
+
if (next === serialised) return nodes;
|
|
55
|
+
nodes = again;
|
|
56
|
+
serialised = next;
|
|
57
|
+
}
|
|
58
|
+
return nodes;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Each round undoes one level of misnesting; the cap only bounds pathological input. */
|
|
62
|
+
const MAX_ROUNDS = 8;
|
|
63
|
+
|
|
64
|
+
class TooDeep extends Error {}
|
|
65
|
+
|
|
66
|
+
/** Element ancestors of a node while parsing, plus itself, counted up to the guard's bound only. */
|
|
67
|
+
function depthOf(node: ParsedParent): number {
|
|
68
|
+
let depth = 0;
|
|
69
|
+
for (let n: ParsedParent | null = node; n !== null && 'tagName' in n; n = n.parentNode) {
|
|
70
|
+
if (++depth > PARSER_BOUND) break;
|
|
71
|
+
}
|
|
72
|
+
return depth;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The fragment parser builds its tree inside two wrapper elements (a stand-in document and a temporary `<html>`
|
|
77
|
+
* root). The guard only has to bound the parser's work, so it allows them; the exact limit is checked on the finished
|
|
78
|
+
* tree.
|
|
79
|
+
*/
|
|
80
|
+
const PARSER_BOUND = MAX_NESTING_DEPTH + 2;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The default tree adapter, refusing to nest elements beyond the bound while the tree is built. The parser scans its
|
|
84
|
+
* stack of open elements for many tags, so deep input (tens of thousands of nested divs) would take quadratic time
|
|
85
|
+
* before any check after parsing could run.
|
|
86
|
+
*/
|
|
87
|
+
const guardedAdapter: TreeAdapter<DefaultTreeAdapterMap> = {
|
|
88
|
+
...defaultTreeAdapter,
|
|
89
|
+
appendChild(parent, node) {
|
|
90
|
+
if ('tagName' in node && depthOf(parent) >= PARSER_BOUND) throw new TooDeep();
|
|
91
|
+
defaultTreeAdapter.appendChild(parent, node);
|
|
92
|
+
},
|
|
93
|
+
insertBefore(parent, node, reference) {
|
|
94
|
+
if ('tagName' in node && depthOf(parent) >= PARSER_BOUND) throw new TooDeep();
|
|
95
|
+
defaultTreeAdapter.insertBefore(parent, node, reference);
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** Deepest element nesting of a parsed fragment, without recursion (the adapter does not see moved subtrees). */
|
|
100
|
+
function maxDepth(root: ParsedParent): number {
|
|
101
|
+
let max = 0;
|
|
102
|
+
const stack: [ParsedNode, number][] = root.childNodes.map((n) => [n, 1]);
|
|
103
|
+
for (let entry = stack.pop(); entry !== undefined; entry = stack.pop()) {
|
|
104
|
+
const [node, depth] = entry;
|
|
105
|
+
if (!('tagName' in node)) continue;
|
|
106
|
+
if (depth > max) max = depth;
|
|
107
|
+
for (const child of node.childNodes) stack.push([child, depth + 1]);
|
|
108
|
+
}
|
|
109
|
+
return max;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function parseOnce(html: string): Node[] | null {
|
|
113
|
+
let fragment: DefaultTreeAdapterTypes.DocumentFragment;
|
|
114
|
+
try {
|
|
115
|
+
fragment = parseFragment(html, { treeAdapter: guardedAdapter });
|
|
116
|
+
} catch (e) {
|
|
117
|
+
if (e instanceof TooDeep) return null;
|
|
118
|
+
throw e;
|
|
119
|
+
}
|
|
120
|
+
return maxDepth(fragment) > MAX_NESTING_DEPTH ? null : convert(fragment.childNodes);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function convert(nodes: readonly ParsedNode[]): Node[] {
|
|
124
|
+
const out: Node[] = [];
|
|
125
|
+
for (const node of nodes) {
|
|
126
|
+
if (node.nodeName === '#text') {
|
|
127
|
+
appendText(out, (node as DefaultTreeAdapterTypes.TextNode).value);
|
|
128
|
+
} else if ('tagName' in node) {
|
|
129
|
+
const attrs: Record<string, string> = {};
|
|
130
|
+
for (const a of node.attrs) {
|
|
131
|
+
const name = (a.prefix ? `${a.prefix}:${a.name}` : a.name).toLowerCase();
|
|
132
|
+
// defineProperty keeps names such as `__proto__` as plain own attributes.
|
|
133
|
+
if (!Object.hasOwn(attrs, name))
|
|
134
|
+
Object.defineProperty(attrs, name, {
|
|
135
|
+
value: a.value,
|
|
136
|
+
enumerable: true,
|
|
137
|
+
writable: true,
|
|
138
|
+
configurable: true,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const children = node.nodeName === 'template' ? [] : convert(node.childNodes);
|
|
142
|
+
out.push(element(node.tagName.toLowerCase(), attrs, children));
|
|
143
|
+
}
|
|
144
|
+
// Comments and doctypes are dropped.
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Appends text, merging it into a preceding text node. */
|
|
150
|
+
export function appendText(out: Node[], value: string): void {
|
|
151
|
+
const last = out[out.length - 1];
|
|
152
|
+
if (last?.type === 'text') out[out.length - 1] = text(last.value + value);
|
|
153
|
+
else if (value !== '') out.push(text(value));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const VOID_ELEMENTS: ReadonlySet<string> = new Set([
|
|
157
|
+
'area',
|
|
158
|
+
'base',
|
|
159
|
+
'br',
|
|
160
|
+
'col',
|
|
161
|
+
'embed',
|
|
162
|
+
'hr',
|
|
163
|
+
'img',
|
|
164
|
+
'input',
|
|
165
|
+
'link',
|
|
166
|
+
'meta',
|
|
167
|
+
'source',
|
|
168
|
+
'track',
|
|
169
|
+
'wbr',
|
|
170
|
+
]);
|
|
171
|
+
|
|
172
|
+
/** Elements whose text the parser reads raw (no entity decoding), so it must be written raw too. */
|
|
173
|
+
const RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set([
|
|
174
|
+
'script',
|
|
175
|
+
'style',
|
|
176
|
+
'xmp',
|
|
177
|
+
'iframe',
|
|
178
|
+
'noembed',
|
|
179
|
+
'noframes',
|
|
180
|
+
'plaintext',
|
|
181
|
+
'noscript',
|
|
182
|
+
]);
|
|
183
|
+
|
|
184
|
+
/** The parser drops a newline right after these start tags, so one is written back when the text starts with one. */
|
|
185
|
+
const LEADING_NEWLINE: ReadonlySet<string> = new Set(['pre', 'textarea', 'listing']);
|
|
186
|
+
|
|
187
|
+
/** SVG and MathML elements whose content the parser reads as HTML again. */
|
|
188
|
+
const SVG_HTML_POINTS: ReadonlySet<string> = new Set(['foreignobject', 'desc', 'title']);
|
|
189
|
+
const MATHML_HTML_POINTS: ReadonlySet<string> = new Set(['mi', 'mo', 'mn', 'ms', 'mtext']);
|
|
190
|
+
|
|
191
|
+
type Namespace = 'html' | 'svg' | 'math';
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Serialises nodes to HTML. Text escapes `&`, `<`, `>` and U+00A0 (` `); attribute values escape `&`, `"` and
|
|
195
|
+
* U+00A0; empty attributes are written bare (`multiple`); void elements have no end tag. Text is kept as is.
|
|
196
|
+
* Parsing the output gives the same tree back (a fixpoint), including the parser's special cases: raw text elements,
|
|
197
|
+
* the newline after `<pre>`, `<plaintext>` (which never ends) and SVG / MathML content.
|
|
198
|
+
*/
|
|
199
|
+
export function serializeHtml(nodes: readonly Node[]): string {
|
|
200
|
+
const state = { ended: false };
|
|
201
|
+
return serializeList(nodes, 'html', false, state);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function serializeList(
|
|
205
|
+
nodes: readonly Node[],
|
|
206
|
+
ns: Namespace,
|
|
207
|
+
raw: boolean,
|
|
208
|
+
state: { ended: boolean },
|
|
209
|
+
): string {
|
|
210
|
+
let out = '';
|
|
211
|
+
for (const node of nodes) {
|
|
212
|
+
if (state.ended) break;
|
|
213
|
+
out +=
|
|
214
|
+
node.type === 'text' ? (raw ? node.value : escapeText(node.value)) : serializeElement(node, ns, state);
|
|
215
|
+
}
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function serializeElement(node: ElementNode, parentNs: Namespace, state: { ended: boolean }): string {
|
|
220
|
+
const tag = node.tag;
|
|
221
|
+
const ns: Namespace = parentNs === 'html' && (tag === 'svg' || tag === 'math') ? tag : parentNs;
|
|
222
|
+
let out = `<${tag}`;
|
|
223
|
+
for (const [name, value] of Object.entries(node.attrs)) {
|
|
224
|
+
out += value === '' ? ` ${name}` : ` ${name}="${escapeAttribute(value)}"`;
|
|
225
|
+
}
|
|
226
|
+
out += '>';
|
|
227
|
+
if (ns === 'html' && VOID_ELEMENTS.has(tag)) return out;
|
|
228
|
+
const first = node.children[0];
|
|
229
|
+
if (ns === 'html' && LEADING_NEWLINE.has(tag) && first?.type === 'text' && first.value.startsWith('\n'))
|
|
230
|
+
out += '\n';
|
|
231
|
+
out += serializeList(
|
|
232
|
+
node.children,
|
|
233
|
+
childNamespace(node, ns),
|
|
234
|
+
ns === 'html' && RAW_TEXT_ELEMENTS.has(tag),
|
|
235
|
+
state,
|
|
236
|
+
);
|
|
237
|
+
// Nothing can follow <plaintext>: the parser reads the rest of the input as its text.
|
|
238
|
+
if (ns === 'html' && tag === 'plaintext') state.ended = true;
|
|
239
|
+
return state.ended ? out : `${out}</${tag}>`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function childNamespace(node: ElementNode, ns: Namespace): Namespace {
|
|
243
|
+
if (ns === 'svg' && SVG_HTML_POINTS.has(node.tag)) return 'html';
|
|
244
|
+
if (ns === 'math' && MATHML_HTML_POINTS.has(node.tag)) return 'html';
|
|
245
|
+
if (ns === 'math' && node.tag === 'annotation-xml') {
|
|
246
|
+
const encoding = (node.attrs.encoding ?? '').toLowerCase();
|
|
247
|
+
if (encoding === 'text/html' || encoding === 'application/xhtml+xml') return 'html';
|
|
248
|
+
}
|
|
249
|
+
return ns;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const NBSP = String.fromCodePoint(0xa0);
|
|
253
|
+
const TEXT_SPECIALS = new RegExp(`[&<>${NBSP}]`, 'g');
|
|
254
|
+
const ATTRIBUTE_SPECIALS = new RegExp(`[&"${NBSP}]`, 'g');
|
|
255
|
+
const ENTITIES: Readonly<Record<string, string>> = {
|
|
256
|
+
'&': '&',
|
|
257
|
+
'<': '<',
|
|
258
|
+
'>': '>',
|
|
259
|
+
'"': '"',
|
|
260
|
+
[NBSP]: ' ',
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
function escapeText(value: string): string {
|
|
264
|
+
return value.replace(TEXT_SPECIALS, (ch) => ENTITIES[ch] ?? ch);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function escapeAttribute(value: string): string {
|
|
268
|
+
return value.replace(ATTRIBUTE_SPECIALS, (ch) => ENTITIES[ch] ?? ch);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** HTML inter-element whitespace (ASCII only, as in the HTML standard). */
|
|
272
|
+
export function isHtmlWhitespace(value: string): boolean {
|
|
273
|
+
return /^[\t\n\f\r ]*$/.test(value);
|
|
274
|
+
}
|
package/src/ids.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opaque ids and keyed permutations. Every view id is derived from HMAC-SHA-256(secret, salt U+001F path), with
|
|
3
|
+
* paths `page:<id>` (implicit page: `page:#0`), `el:<id>` and `el:<id>/<localId>`. Ports in other languages must
|
|
4
|
+
* implement exactly this to produce byte-identical views.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const encoder = new TextEncoder();
|
|
8
|
+
|
|
9
|
+
/** Bytes of a secret given as a string (UTF-8) or as bytes (copied). */
|
|
10
|
+
export function secretBytes(secret: string | Uint8Array): Uint8Array<ArrayBuffer> {
|
|
11
|
+
return typeof secret === 'string' ? encoder.encode(secret) : new Uint8Array(secret);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** HMAC-SHA-256 with a lazily imported key, reused for every call. */
|
|
15
|
+
export type Hmac = (message: string) => Promise<Uint8Array>;
|
|
16
|
+
|
|
17
|
+
export function createHmac(secret: Uint8Array<ArrayBuffer>): Hmac {
|
|
18
|
+
let key: Promise<CryptoKey> | undefined;
|
|
19
|
+
return async (message) => {
|
|
20
|
+
key ??= crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
21
|
+
return new Uint8Array(await crypto.subtle.sign('HMAC', await key, encoder.encode(message)));
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** U+001F (unit separator), written as a code point so no formatter turns it into a raw control character. */
|
|
26
|
+
const SEPARATOR = String.fromCodePoint(0x1f);
|
|
27
|
+
|
|
28
|
+
/** The HMAC message for an id path: salt, U+001F, path. */
|
|
29
|
+
export function idMessage(salt: string, path: string): string {
|
|
30
|
+
return `${salt}${SEPARATOR}${path}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function pagePath(sourceId: string | null): string {
|
|
34
|
+
return `page:${sourceId ?? '#0'}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function elementPath(sourceId: string, localId?: string): string {
|
|
38
|
+
return localId === undefined ? `el:${sourceId}` : `el:${sourceId}/${localId}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567';
|
|
42
|
+
|
|
43
|
+
/** RFC 4648 base32, lowercase, without padding. */
|
|
44
|
+
export function base32(bytes: Uint8Array): string {
|
|
45
|
+
let out = '';
|
|
46
|
+
let buffer = 0;
|
|
47
|
+
let bits = 0;
|
|
48
|
+
for (const byte of bytes) {
|
|
49
|
+
buffer = ((buffer << 8) | byte) & 0xffff;
|
|
50
|
+
bits += 8;
|
|
51
|
+
while (bits >= 5) {
|
|
52
|
+
bits -= 5;
|
|
53
|
+
out += BASE32[(buffer >>> bits) & 31];
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (bits > 0) out += BASE32[(buffer << (5 - bits)) & 31];
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** `k` + base32 of digest bytes 0..9: 16 characters, 80 bits. */
|
|
61
|
+
export function opaqueId(digest: Uint8Array): string {
|
|
62
|
+
return `k${base32(digest.subarray(0, 10))}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Permutation seed: digest bytes 16..31 as four big-endian 32-bit words. */
|
|
66
|
+
export function seedWords(digest: Uint8Array): readonly number[] {
|
|
67
|
+
const view = new DataView(digest.buffer, digest.byteOffset + 16, 16);
|
|
68
|
+
return [view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 32-bit FNV-1a over UTF-8. */
|
|
72
|
+
export function fnv1a(value: string): number {
|
|
73
|
+
let hash = 0x811c9dc5;
|
|
74
|
+
for (const byte of encoder.encode(value)) hash = Math.imul(hash ^ byte, 0x01000193);
|
|
75
|
+
return hash >>> 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** sfc32 (Chris Doty-Humphrey's Small Fast Counting generator): 32-bit outputs, integer arithmetic only. */
|
|
79
|
+
function sfc32(seed: readonly number[]): () => number {
|
|
80
|
+
let a = (seed[0] ?? 0) | 0;
|
|
81
|
+
let b = (seed[1] ?? 0) | 0;
|
|
82
|
+
let c = (seed[2] ?? 0) | 0;
|
|
83
|
+
let d = (seed[3] ?? 0) | 0;
|
|
84
|
+
return () => {
|
|
85
|
+
const t = (((a + b) | 0) + d) | 0;
|
|
86
|
+
d = (d + 1) | 0;
|
|
87
|
+
a = b ^ (b >>> 9);
|
|
88
|
+
b = (c + (c << 3)) | 0;
|
|
89
|
+
c = (c << 21) | (c >>> 11);
|
|
90
|
+
c = (c + t) | 0;
|
|
91
|
+
return t >>> 0;
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Keyed permutation of `n` indices: a pure function of (seed, salt, n). The generator is sfc32 seeded with the four
|
|
97
|
+
* seed words, the first XOR FNV-1a(salt), and warmed up for 12 rounds; then Fisher-Yates from the end with
|
|
98
|
+
* j = floor(r * (i + 1) / 2^32).
|
|
99
|
+
*
|
|
100
|
+
* With `avoidOriginal` and n >= 2, an identity result is drawn again from the same generator, so the result is
|
|
101
|
+
* uniform over the orders that differ from the source. For n = 2 that leaves one order: the swap. (Rotating the
|
|
102
|
+
* identity instead would make one order twice as likely as the others.)
|
|
103
|
+
*/
|
|
104
|
+
export function permutation(
|
|
105
|
+
seed: readonly number[],
|
|
106
|
+
salt: string,
|
|
107
|
+
n: number,
|
|
108
|
+
avoidOriginal: boolean,
|
|
109
|
+
): number[] {
|
|
110
|
+
const next = sfc32([(seed[0] ?? 0) ^ fnv1a(salt), seed[1] ?? 0, seed[2] ?? 0, seed[3] ?? 0]);
|
|
111
|
+
for (let i = 0; i < 12; i++) next();
|
|
112
|
+
const draw = (): number[] => {
|
|
113
|
+
const order = Array.from({ length: n }, (_, i) => i);
|
|
114
|
+
for (let i = n - 1; i > 0; i--) {
|
|
115
|
+
const j = Math.floor((next() * (i + 1)) / 0x100000000);
|
|
116
|
+
const tmp = order[i] as number;
|
|
117
|
+
order[i] = order[j] as number;
|
|
118
|
+
order[j] = tmp;
|
|
119
|
+
}
|
|
120
|
+
return order;
|
|
121
|
+
};
|
|
122
|
+
if (avoidOriginal && n === 2) return [1, 0];
|
|
123
|
+
let order = draw();
|
|
124
|
+
// An identity draw has probability 1/n! <= 1/6 here, so a second draw almost always succeeds; the cap only makes
|
|
125
|
+
// termination certain.
|
|
126
|
+
for (let tries = 0; avoidOriginal && n > 2 && isIdentity(order) && tries < MAX_DRAWS; tries++)
|
|
127
|
+
order = draw();
|
|
128
|
+
if (avoidOriginal && n > 2 && isIdentity(order)) order.push(order.shift() as number);
|
|
129
|
+
return order;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const MAX_DRAWS = 64;
|
|
133
|
+
|
|
134
|
+
function isIdentity(order: readonly number[]): boolean {
|
|
135
|
+
return order.every((v, i) => v === i);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Lowercase hex SHA-256 of the UTF-8 text. */
|
|
139
|
+
export async function sha256Hex(text: string): Promise<string> {
|
|
140
|
+
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(text)));
|
|
141
|
+
let out = '';
|
|
142
|
+
for (const byte of digest) out += byte.toString(16).padStart(2, '0');
|
|
143
|
+
return out;
|
|
144
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type { LocalChecker } from './checker.js';
|
|
2
|
+
export { localChecker } from './checker.js';
|
|
3
|
+
export type { Leak, RefResolver } from './conformance.js';
|
|
4
|
+
export { leakProbe, refResolver } from './conformance.js';
|
|
5
|
+
export { createEngine } from './engine.js';
|
|
6
|
+
export { helpShown, hintCount, isGradedElement, nextHint, resultHelp } from './help.js';
|
|
7
|
+
export { parseHtml, serializeHtml } from './html.js';
|
|
8
|
+
export * as kit from './kit/index.js';
|
|
9
|
+
export { engineMessages } from './messages.js';
|
|
10
|
+
export type { ChoiceKey, FlagKey, LetterKey, NumberKey, ProfileData, TextKey } from './slot-kinds.js';
|
|
11
|
+
export { choiceSlot, flagSlot, letterSlot, numberSlot, textSlot } from './slot-kinds.js';
|
|
12
|
+
export { normalise, parseNumber } from './text.js';
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Attribute value grammar shared by validation and the definition kit. Attribute numbers always use a dot. */
|
|
2
|
+
|
|
3
|
+
const INTEGER = /^-?\d+$/;
|
|
4
|
+
const DECIMAL = /^-?(\d+(\.\d+)?|\.\d+)$/;
|
|
5
|
+
|
|
6
|
+
export function parseIntegerValue(value: string): number | null {
|
|
7
|
+
if (!INTEGER.test(value)) return null;
|
|
8
|
+
const n = Number(value);
|
|
9
|
+
return Number.isSafeInteger(n) ? n : null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function parseDecimalValue(value: string): number | null {
|
|
13
|
+
if (!DECIMAL.test(value)) return null;
|
|
14
|
+
const n = Number(value);
|
|
15
|
+
return Number.isFinite(n) ? n : null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** HTML boolean attribute syntax: empty, or the attribute's own name (any case). */
|
|
19
|
+
export function isBooleanValue(name: string, value: string): boolean {
|
|
20
|
+
return value === '' || value.toLowerCase() === name;
|
|
21
|
+
}
|
package/src/kit/index.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for component definitions. Elements reaching a definition are already sanitised and validated against
|
|
3
|
+
* the manifest, so the readers below only parse; they never report.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
allAttributes,
|
|
7
|
+
type ChildSpec,
|
|
8
|
+
CONTENT_ATTRIBUTES,
|
|
9
|
+
type CompileContext,
|
|
10
|
+
type ComponentManifest,
|
|
11
|
+
childElements,
|
|
12
|
+
type ElementNode,
|
|
13
|
+
element,
|
|
14
|
+
type Node,
|
|
15
|
+
textContent,
|
|
16
|
+
} from '@astl/core';
|
|
17
|
+
import { parseDecimalValue, parseIntegerValue } from './attributes.js';
|
|
18
|
+
|
|
19
|
+
/** The attribute value, or null when absent. */
|
|
20
|
+
export function stringAttr(el: ElementNode, name: string): string | null {
|
|
21
|
+
return Object.hasOwn(el.attrs, name) ? (el.attrs[name] ?? null) : null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A `url` attribute, or null when absent or blank. The sanitiser has already passed it through the engine's URL
|
|
26
|
+
* policy, so a blocked URL never reaches a definition.
|
|
27
|
+
*/
|
|
28
|
+
export function urlAttr(el: ElementNode, name: string): string | null {
|
|
29
|
+
const value = stringAttr(el, name);
|
|
30
|
+
return value === null || value.trim() === '' ? null : value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** HTML boolean attribute: present = true. */
|
|
34
|
+
export function boolAttr(el: ElementNode, name: string): boolean {
|
|
35
|
+
return Object.hasOwn(el.attrs, name);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A decimal number (dot separator), or null when absent or not a number. */
|
|
39
|
+
export function numberAttr(el: ElementNode, name: string): number | null {
|
|
40
|
+
const value = stringAttr(el, name);
|
|
41
|
+
return value === null ? null : parseDecimalValue(value);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An integer, or null when absent or not an integer. */
|
|
45
|
+
export function intAttr(el: ElementNode, name: string): number | null {
|
|
46
|
+
const value = stringAttr(el, name);
|
|
47
|
+
return value === null ? null : parseIntegerValue(value);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One of `values`, else `fallback` (absent or unknown value). */
|
|
51
|
+
export function enumAttr<T extends string>(
|
|
52
|
+
el: ElementNode,
|
|
53
|
+
name: string,
|
|
54
|
+
values: readonly T[],
|
|
55
|
+
fallback: T,
|
|
56
|
+
): T {
|
|
57
|
+
const value = stringAttr(el, name);
|
|
58
|
+
return value !== null && (values as readonly string[]).includes(value) ? (value as T) : fallback;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Element children with the given tag, in order. */
|
|
62
|
+
export function children(el: ElementNode, tag: string): ElementNode[] {
|
|
63
|
+
return childElements(el, tag);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Elements with the given tag anywhere inside `el`, in document order: the inline children of a rich block. */
|
|
67
|
+
export function descendants(el: ElementNode, tag: string): ElementNode[] {
|
|
68
|
+
return el.children.flatMap((n) =>
|
|
69
|
+
n.type !== 'element' ? [] : n.tag === tag ? [n, ...descendants(n, tag)] : descendants(n, tag),
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Text of an element and its descendants, as written. */
|
|
74
|
+
export function text(el: ElementNode): string {
|
|
75
|
+
return textContent(el);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* What an element says to a student: its text with each picture's `alt` in its place (screen readers read it out),
|
|
80
|
+
* whitespace runs collapsed, trimmed. Empty when there is no text and every picture is decorative (`alt=""`), so
|
|
81
|
+
* definitions can tell an option or a card that shows only a picture from an empty one.
|
|
82
|
+
*/
|
|
83
|
+
export function label(el: ElementNode): string {
|
|
84
|
+
const parts: string[] = [];
|
|
85
|
+
const visit = (node: Node): void => {
|
|
86
|
+
if (node.type === 'text') parts.push(node.value);
|
|
87
|
+
else if (node.tag === 'img') parts.push(` ${node.attrs.alt ?? ''} `);
|
|
88
|
+
else for (const child of node.children) visit(child);
|
|
89
|
+
};
|
|
90
|
+
visit(el);
|
|
91
|
+
return parts.join('').replace(/\s+/gu, ' ').trim();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Whether the element shows a picture (an `img` anywhere inside it). */
|
|
95
|
+
export function hasPicture(el: ElementNode): boolean {
|
|
96
|
+
return el.children.some((n) => n.type === 'element' && (n.tag === 'img' || hasPicture(n)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The generic public view of an element: `id` (opaque) and `v` (manifest version) first, then the public attributes
|
|
101
|
+
* as written plus `lang` and `dir`; private attributes and private children are dropped; public children keep their
|
|
102
|
+
* public attributes (local `id`-typed values become opaque ids) and their sanitised content. A rich block
|
|
103
|
+
* (`content: 'flow'`) keeps its content, with the same rules for the children in it. Definitions add derived
|
|
104
|
+
* attributes or reorder children on top of it.
|
|
105
|
+
*/
|
|
106
|
+
export function publicView(el: ElementNode, manifest: ComponentManifest, ctx: CompileContext): ElementNode {
|
|
107
|
+
const specs = allAttributes(manifest);
|
|
108
|
+
const attrs: Record<string, string> = { id: ctx.opaque(), v: String(manifest.version) };
|
|
109
|
+
for (const [name, value] of Object.entries(el.attrs)) {
|
|
110
|
+
if (name === 'id' || name === 'v') continue;
|
|
111
|
+
if (CONTENT_ATTRIBUTES.has(name)) {
|
|
112
|
+
attrs[name] = value;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const spec = specs.find((s) => s.name === name);
|
|
116
|
+
if (spec?.visibility === 'public') attrs[name] = spec.type === 'id' ? ctx.opaque(value) : value;
|
|
117
|
+
}
|
|
118
|
+
const flow = manifest.content === 'flow';
|
|
119
|
+
const content = (nodes: readonly Node[]): Node[] =>
|
|
120
|
+
nodes.flatMap((child): Node[] => {
|
|
121
|
+
if (child.type !== 'element') return flow ? [child] : [];
|
|
122
|
+
const spec = manifest.children.find((c) => c.tag === child.tag);
|
|
123
|
+
if (spec !== undefined) return spec.visibility === 'public' ? [publicChild(child, spec, ctx)] : [];
|
|
124
|
+
return flow ? [element(child.tag, child.attrs, content(child.children))] : [];
|
|
125
|
+
});
|
|
126
|
+
return element(manifest.tag, attrs, content(el.children));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function publicChild(child: ElementNode, spec: ChildSpec, ctx: CompileContext): ElementNode {
|
|
130
|
+
const attrs: Record<string, string> = {};
|
|
131
|
+
for (const [name, value] of Object.entries(child.attrs)) {
|
|
132
|
+
if (CONTENT_ATTRIBUTES.has(name)) {
|
|
133
|
+
attrs[name] = value;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const attr = spec.attributes.find((a) => a.name === name);
|
|
137
|
+
if (attr?.visibility === 'public') attrs[name] = attr.type === 'id' ? ctx.opaque(value) : value;
|
|
138
|
+
}
|
|
139
|
+
return element(child.tag, attrs, child.children);
|
|
140
|
+
}
|