eyemind 0.9.18 → 0.9.20
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/LS-SPEC.md +1 -1
- package/README.md +30 -14
- package/bin/eyemind.js +2 -1
- package/package.json +1 -1
- package/src/cli.js +10 -9
- package/src/formats.js +28 -6
- package/src/index.js +1 -1
- package/src/jelly.js +974 -0
- package/src/jsonld.js +906 -0
- package/src/messages.js +135 -5
- package/src/node-messages.js +6 -3
- package/src/node.js +3 -1
- package/src/rdf-lexer.js +11 -4
- package/src/rdf-parser.js +3 -0
- package/src/rdf-xml.js +363 -0
- package/src/rdf.js +105 -8
- package/src/version.js +1 -1
- package/src/xml.js +174 -0
package/src/rdf.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// RDF 1.2 in and out of eyemind: Turtle, TriG, N-Triples and N-Quads
|
|
1
|
+
// RDF 1.2 in and out of eyemind: Turtle, TriG, N-Triples and N-Quads, and
|
|
2
|
+
// RDF/XML (rdf-xml.js), JSON-LD (jsonld.js) and Jelly (jelly.js).
|
|
2
3
|
//
|
|
3
4
|
// Documents are read by the RDF lexer and parser (rdf-lexer.js,
|
|
4
5
|
// rdf-parser.js and rdf-prelude.js), with the RDF 1.2 surface checks
|
|
@@ -18,6 +19,9 @@
|
|
|
18
19
|
import { lex } from './rdf-lexer.js';
|
|
19
20
|
import { checkRdfSyntax } from './rdf-syntax.js';
|
|
20
21
|
import { Parser } from './rdf-parser.js';
|
|
22
|
+
import { parseRdfXml, parseRdfXmlMessages, writeRdfXml } from './rdf-xml.js';
|
|
23
|
+
import { jsonLdToRdf, rdfToJsonLd } from './jsonld.js';
|
|
24
|
+
import { readJelly, writeJelly } from './jelly.js';
|
|
21
25
|
import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, clearParserCaches, literalParts } from './rdf-prelude.js';
|
|
22
26
|
import { EyemindError, Struct } from './terms.js';
|
|
23
27
|
import { write } from './writer.js';
|
|
@@ -26,7 +30,8 @@ const XSD = 'http://www.w3.org/2001/XMLSchema#';
|
|
|
26
30
|
const RDF_TYPE = `${RDF_NS}type`;
|
|
27
31
|
export const DEFAULT_GRAPH = 'default_graph';
|
|
28
32
|
|
|
29
|
-
const FORMATS = { ttl: 'turtle', turtle: 'turtle', trig: 'trig', nt: 'n-triples', ntriples: 'n-triples', nq: 'n-quads', nquads: 'n-quads'
|
|
33
|
+
const FORMATS = { ttl: 'turtle', turtle: 'turtle', trig: 'trig', nt: 'n-triples', ntriples: 'n-triples', nq: 'n-quads', nquads: 'n-quads',
|
|
34
|
+
rdf: 'rdf-xml', rdfxml: 'rdf-xml', jsonld: 'json-ld', ndjson: 'ndjson-ld', jelly: 'jelly' };
|
|
30
35
|
|
|
31
36
|
// The RDF format a file name names by its extension, or null.
|
|
32
37
|
export function rdfFormat(name) {
|
|
@@ -37,16 +42,28 @@ export function rdfFormat(name) {
|
|
|
37
42
|
const st = (name, ...args) => new Struct(name, args);
|
|
38
43
|
const iri = (v) => st('iri', v);
|
|
39
44
|
|
|
40
|
-
// Read an RDF document. Options: format ('turtle', 'trig', 'n-triples'
|
|
41
|
-
// 'n-quads'), base (IRI) and scope (for blank
|
|
45
|
+
// Read an RDF document. Options: format ('turtle', 'trig', 'n-triples',
|
|
46
|
+
// 'n-quads', 'rdf-xml', 'json-ld' or 'jelly'), base (IRI) and scope (for blank
|
|
47
|
+
// nodes); a Jelly stream is bytes, or a string of one character per byte;
|
|
48
|
+
// JSON-LD also takes loadDocument(url), for remote contexts, and the
|
|
49
|
+
// processingMode, expandContext and rdfDirection of the JSON-LD API. Returns { quads,
|
|
42
50
|
// prefixes }: quads are [S, P, O, G] eyemind terms, prefixes maps names to
|
|
43
51
|
// namespaces.
|
|
44
|
-
export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' } = {}) {
|
|
45
|
-
text = String(text);
|
|
52
|
+
export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf', ...jsonld } = {}) {
|
|
46
53
|
try {
|
|
54
|
+
if (format === 'jelly') {
|
|
55
|
+
const read = readJelly(text);
|
|
56
|
+
if (read.messages) throw new SyntaxError('a Jelly stream of RDF Messages is read with parseRdfMessages, which keeps its messages apart');
|
|
57
|
+
return { quads: neutralToTerms(read.statements, scope), prefixes: read.namespaces, base: null };
|
|
58
|
+
}
|
|
59
|
+
text = String(text);
|
|
60
|
+
if (format === 'rdf-xml') return parseRdfXml(text, { base, scope, graph: DEFAULT_GRAPH, literal: xmlLiteralTerm });
|
|
61
|
+
if (format === 'ndjson-ld') throw new SyntaxError('an NDJSON-LD log is read with parseRdfMessages, which keeps its messages apart');
|
|
62
|
+
if (format === 'json-ld') return { quads: neutralToTerms(jsonLdToRdf(text, { ...jsonld, base }), scope), prefixes: {}, base };
|
|
47
63
|
checkRdfSyntax(text, format);
|
|
48
64
|
assertRdf12SurfaceSyntax(text, format);
|
|
49
65
|
const parser = new Parser(lex(text, { trig: format === 'trig' }));
|
|
66
|
+
parser.verbatimIris = format === 'n-triples' || format === 'n-quads';
|
|
50
67
|
if (base) parser.prefixes.setBase(base);
|
|
51
68
|
const state = { scope, lists: 0, out: [] };
|
|
52
69
|
if (format === 'n-quads') {
|
|
@@ -144,6 +161,80 @@ function literalTerm(raw) {
|
|
|
144
161
|
return literalOf(value, datatype ?? (quoted ? `${XSD}string` : bareDatatype(value)));
|
|
145
162
|
}
|
|
146
163
|
|
|
164
|
+
function neutralWrite(write) {
|
|
165
|
+
try {
|
|
166
|
+
return write();
|
|
167
|
+
} catch (error) {
|
|
168
|
+
throw error instanceof SyntaxError ? new EyemindError(error.message) : error;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// eyemind quads as the neutral terms of the JSON-LD, RDF/XML and Jelly writers:
|
|
173
|
+
// { termType, value, datatype?, language?, direction? }, or a triple term
|
|
174
|
+
// { termType: 'triple', subject, predicate, object }; graph null for the
|
|
175
|
+
// default one. A blank node keeps its label where that label is unique.
|
|
176
|
+
export function neutralQuads(quads, blankNodePrefix = '') {
|
|
177
|
+
const labels = new Map(), taken = new Set();
|
|
178
|
+
const blank = (t) => {
|
|
179
|
+
const key = write(t);
|
|
180
|
+
if (!labels.has(key)) {
|
|
181
|
+
let label = t.name === 'bnode' && typeof t.args[1] === 'string' ? t.args[1] : '';
|
|
182
|
+
if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(label) || taken.has(label)) label = `b${labels.size}`;
|
|
183
|
+
while (taken.has(label)) label += '_';
|
|
184
|
+
taken.add(label);
|
|
185
|
+
labels.set(key, blankNodePrefix + label);
|
|
186
|
+
}
|
|
187
|
+
return { termType: 'blank', value: labels.get(key) };
|
|
188
|
+
};
|
|
189
|
+
const term = (t) => {
|
|
190
|
+
if (typeof t === 'bigint') return { termType: 'literal', value: String(t), datatype: `${XSD}integer` };
|
|
191
|
+
if (typeof t === 'number') return { termType: 'literal', value: String(t), datatype: `${XSD}double` };
|
|
192
|
+
if (!(t instanceof Struct)) throw new EyemindError(`${write(t)} is not an RDF term`);
|
|
193
|
+
const [a, b, c] = t.args;
|
|
194
|
+
if (t.name === 'iri' && t.args.length === 1 && typeof a === 'string') return { termType: 'iri', value: a };
|
|
195
|
+
if ((t.name === 'bnode' && t.args.length === 2) || (t.name === 'skolem' && t.args.length === 3)) return blank(t);
|
|
196
|
+
if (t.name === 'literal' && t.args.length === 2 && typeof a === 'string' && b instanceof Struct) {
|
|
197
|
+
if (b.name === 'lang') return { termType: 'literal', value: a, language: b.args[0], direction: b.args[1] ?? null };
|
|
198
|
+
if (b.name === 'datatype') return { termType: 'literal', value: a, datatype: b.args[0] };
|
|
199
|
+
}
|
|
200
|
+
if (t.name === 'triple' && t.args.length === 3) return { termType: 'triple', subject: term(a), predicate: term(b), object: term(c) };
|
|
201
|
+
throw new EyemindError(`${write(t)} is not an RDF term`);
|
|
202
|
+
};
|
|
203
|
+
return quads.map(([s, p, o, g]) => [term(s), term(p), term(o), g === DEFAULT_GRAPH ? null : term(g)]);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Neutral quads, of jsonld.js and jelly.js, as eyemind terms.
|
|
207
|
+
export function neutralToTerms(quads, scope) {
|
|
208
|
+
const term = (t) => {
|
|
209
|
+
if (t.termType === 'iri') return iri(t.value);
|
|
210
|
+
if (t.termType === 'blank') return st('bnode', scope, t.value);
|
|
211
|
+
if (t.termType === 'triple') return st('triple', term(t.subject), term(t.predicate), term(t.object));
|
|
212
|
+
if (t.language) return st('literal', t.value, t.direction ? st('lang', t.language, t.direction) : st('lang', t.language));
|
|
213
|
+
return literalOf(t.value, t.datatype);
|
|
214
|
+
};
|
|
215
|
+
return quads.map(([s, p, o, g]) => [term(s), term(p), term(o), g ? term(g) : DEFAULT_GRAPH]);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// The messages of an RDF/XML message log, for messages.js.
|
|
219
|
+
export function parseRdfXmlLog(text, { base = null, scope = 'messages' } = {}) {
|
|
220
|
+
try {
|
|
221
|
+
return parseRdfXmlMessages(String(text), { base, scope, graph: DEFAULT_GRAPH, literal: xmlLiteralTerm });
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error instanceof EyemindError) throw error;
|
|
224
|
+
throw new EyemindError(`rdf-xml: ${error.message}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// A literal of RDF/XML: a language string, or a typed one, xsd:string when
|
|
229
|
+
// no datatype is given.
|
|
230
|
+
function xmlLiteralTerm(value, language, datatype) {
|
|
231
|
+
if (language) {
|
|
232
|
+
if (!/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language.lang)) throw new SyntaxError(`invalid RDF 1.2 language tag ${language.lang}`);
|
|
233
|
+
return st('literal', value, language.dir ? st('lang', language.lang, language.dir) : st('lang', language.lang));
|
|
234
|
+
}
|
|
235
|
+
return literalOf(value, datatype ?? `${XSD}string`);
|
|
236
|
+
}
|
|
237
|
+
|
|
147
238
|
function unquote(lexical) {
|
|
148
239
|
try {
|
|
149
240
|
return JSON.parse(lexical);
|
|
@@ -338,13 +429,19 @@ function assertLineSyntax(text) {
|
|
|
338
429
|
|
|
339
430
|
// Write quads, [S, P, O, G] eyemind terms, as Turtle (or TriG when a quad is
|
|
340
431
|
// in a named graph) with the prefixes it uses, or as N-Triples or N-Quads.
|
|
341
|
-
export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePrefix = '' } = {}) {
|
|
432
|
+
export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePrefix = '', ...jsonld } = {}) {
|
|
433
|
+
if (format === 'json-ld') return `${JSON.stringify(rdfToJsonLd(neutralQuads(quads, blankNodePrefix), jsonld), null, 2)}\n`;
|
|
434
|
+
// Jelly is bytes.
|
|
435
|
+
if (format === 'jelly') return neutralWrite(() => writeJelly(neutralQuads(quads, blankNodePrefix), { namespaces: prefixes, ...jsonld }));
|
|
436
|
+
if (format === 'rdf-xml') return neutralWrite(() => writeRdfXml(neutralQuads(quads, blankNodePrefix), prefixes));
|
|
437
|
+
if ((format === 'turtle' || format === 'n-triples') && quads.some((q) => q[3] !== DEFAULT_GRAPH)) {
|
|
438
|
+
throw new EyemindError(`${format} has no named graphs; write trig, n-quads or json-ld`);
|
|
439
|
+
}
|
|
342
440
|
const line = format === 'n-triples' || format === 'n-quads';
|
|
343
441
|
const w = new RdfWriter(line ? {} : prefixes, line, blankNodePrefix);
|
|
344
442
|
const body = [];
|
|
345
443
|
if (line) {
|
|
346
444
|
for (const [s, p, o, g] of quads) {
|
|
347
|
-
if (format === 'n-triples' && g !== DEFAULT_GRAPH) continue;
|
|
348
445
|
body.push(`${w.term(s)} ${w.term(p)} ${w.term(o)}${g === DEFAULT_GRAPH ? '' : ` ${w.term(g)}`} .`);
|
|
349
446
|
}
|
|
350
447
|
return body.map((l) => `${l}\n`).join('');
|
package/src/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// The release this checkout is; ./release keeps it in step with package.json.
|
|
2
|
-
export const VERSION = '0.9.
|
|
2
|
+
export const VERSION = '0.9.20';
|
package/src/xml.js
CHANGED
|
@@ -15,6 +15,10 @@ const XML = 'http://www.w3.org/XML/1998/namespace';
|
|
|
15
15
|
const XMLNS = 'http://www.w3.org/2000/xmlns/';
|
|
16
16
|
const INVALID_RAW = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F\uD800-\uDFFF\uFFFE\uFFFF]/u;
|
|
17
17
|
|
|
18
|
+
// Whether a text is an XML name without a colon, as rdf:ID and rdf:nodeID are.
|
|
19
|
+
const NC_NAME_ONLY = new RegExp(`^${NC_NAME}$`, 'u');
|
|
20
|
+
export const isNcName = (text) => NC_NAME_ONLY.test(text);
|
|
21
|
+
|
|
18
22
|
function match(pattern, text, at) {
|
|
19
23
|
pattern.lastIndex = at;
|
|
20
24
|
return pattern.exec(text);
|
|
@@ -140,3 +144,173 @@ export function isXmlContent(text) {
|
|
|
140
144
|
}
|
|
141
145
|
return open.length === 0;
|
|
142
146
|
}
|
|
147
|
+
|
|
148
|
+
// An XML document as a tree, for RDF/XML: the root element, each element
|
|
149
|
+
// { name, ns, local, attrs, children, declared } with attrs [{ name, ns,
|
|
150
|
+
// local, value }] and declared the namespaces it declares, and text, comment
|
|
151
|
+
// and processing instruction nodes. A DOCTYPE may declare internal general
|
|
152
|
+
// entities; external ones are not read. Throws a SyntaxError.
|
|
153
|
+
// https://www.w3.org/TR/xml/#sec-documents
|
|
154
|
+
export function parseXml(input) {
|
|
155
|
+
const fail = (message) => { throw new SyntaxError(`XML: ${message}`); };
|
|
156
|
+
if (INVALID_RAW.test(input)) fail('a character is not allowed in XML');
|
|
157
|
+
const text = String(input).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
|
|
158
|
+
const entities = { ...ENTITIES };
|
|
159
|
+
let at = 0;
|
|
160
|
+
const take = (token) => text.startsWith(token, at) && (at += token.length, true);
|
|
161
|
+
const read = (pattern) => {
|
|
162
|
+
const found = match(pattern, text, at)?.[0];
|
|
163
|
+
if (found) at += found.length;
|
|
164
|
+
return found;
|
|
165
|
+
};
|
|
166
|
+
const until = (token, what) => {
|
|
167
|
+
const end = text.indexOf(token, at);
|
|
168
|
+
if (end < 0) fail(`unterminated ${what}`);
|
|
169
|
+
const body = text.slice(at, end);
|
|
170
|
+
at = end + token.length;
|
|
171
|
+
return body;
|
|
172
|
+
};
|
|
173
|
+
// Character and entity references; an entity's text may hold references.
|
|
174
|
+
const expand = (raw, attribute, depth = 0) => {
|
|
175
|
+
if (depth > 16) fail('entities nest too deeply');
|
|
176
|
+
let value = '', start = 0;
|
|
177
|
+
for (let amp = raw.indexOf('&'); amp >= 0; amp = raw.indexOf('&', start)) {
|
|
178
|
+
const plain = raw.slice(start, amp);
|
|
179
|
+
value += attribute ? plain.replace(/[\t\n]/g, ' ') : plain;
|
|
180
|
+
const char = reference(raw, amp);
|
|
181
|
+
if (char) {
|
|
182
|
+
value += char[1];
|
|
183
|
+
start = amp + char[0];
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const named = /^&([^;\s&]+);/.exec(raw.slice(amp));
|
|
187
|
+
if (!named || !(named[1] in entities)) fail(`unknown reference ${raw.slice(amp, amp + 12)}`);
|
|
188
|
+
value += named[1] in ENTITIES ? entities[named[1]] : expand(entities[named[1]], attribute, depth + 1);
|
|
189
|
+
start = amp + named[0].length;
|
|
190
|
+
}
|
|
191
|
+
const rest = raw.slice(start);
|
|
192
|
+
return value + (attribute ? rest.replace(/[\t\n]/g, ' ') : rest);
|
|
193
|
+
};
|
|
194
|
+
const misc = () => {
|
|
195
|
+
for (;;) {
|
|
196
|
+
read(SPACE);
|
|
197
|
+
if (take('<!--')) {
|
|
198
|
+
const body = until('-->', 'comment');
|
|
199
|
+
if (body.includes('--')) fail('a comment contains --');
|
|
200
|
+
} else if (text.startsWith('<?', at) && !text.startsWith('<?xml ', at)) {
|
|
201
|
+
at += 2;
|
|
202
|
+
if (!read(PI_NAME)) fail('a processing instruction has no target');
|
|
203
|
+
until('?>', 'processing instruction');
|
|
204
|
+
} else return;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
if (take('<?xml')) until('?>', 'XML declaration');
|
|
208
|
+
misc();
|
|
209
|
+
if (take('<!DOCTYPE')) {
|
|
210
|
+
// Internal general entities; parameter entities and external ones are not read.
|
|
211
|
+
let depth = 0;
|
|
212
|
+
const start = at;
|
|
213
|
+
while (at < text.length && (depth || text[at] !== '>')) {
|
|
214
|
+
if (text[at] === '[') depth++;
|
|
215
|
+
else if (text[at] === ']') depth--;
|
|
216
|
+
else if (text[at] === '"' || text[at] === "'") at = text.indexOf(text[at], at + 1);
|
|
217
|
+
if (at < 0) fail('unterminated DOCTYPE');
|
|
218
|
+
at++;
|
|
219
|
+
}
|
|
220
|
+
for (const [, name, , value] of text.slice(start, at).matchAll(/<!ENTITY\s+([^\s%]+)\s+(["'])([\s\S]*?)\2\s*>/g)) {
|
|
221
|
+
if (!(name in entities)) entities[name] = value;
|
|
222
|
+
}
|
|
223
|
+
if (!take('>')) fail('unterminated DOCTYPE');
|
|
224
|
+
misc();
|
|
225
|
+
}
|
|
226
|
+
const scope = [new Map([['xml', XML], ['', '']])];
|
|
227
|
+
const resolve = (name, element) => {
|
|
228
|
+
const colon = name.indexOf(':');
|
|
229
|
+
const prefix = colon < 0 ? '' : name.slice(0, colon), local = colon < 0 ? name : name.slice(colon + 1);
|
|
230
|
+
if (colon < 0 && !element) return { ns: '', local };
|
|
231
|
+
const ns = scope.at(-1).get(prefix);
|
|
232
|
+
if (ns === undefined) fail(`the prefix ${prefix} is not declared`);
|
|
233
|
+
return { ns, local };
|
|
234
|
+
};
|
|
235
|
+
const element = () => {
|
|
236
|
+
const name = read(QNAME);
|
|
237
|
+
if (!name) fail(`an element name is expected at offset ${at}`);
|
|
238
|
+
const raw = [];
|
|
239
|
+
while (read(SPACE) && text[at] !== '>' && text[at] !== '/') {
|
|
240
|
+
const attr = read(QNAME);
|
|
241
|
+
if (!attr) fail(`an attribute name is expected in <${name}>`);
|
|
242
|
+
read(SPACE);
|
|
243
|
+
if (!take('=')) fail(`the attribute ${attr} has no value`);
|
|
244
|
+
read(SPACE);
|
|
245
|
+
const quote = text[at++];
|
|
246
|
+
if (quote !== '"' && quote !== "'") fail(`the value of ${attr} is not quoted`);
|
|
247
|
+
const value = until(quote, 'attribute value');
|
|
248
|
+
if (value.includes('<')) fail(`the value of ${attr} contains <`);
|
|
249
|
+
if (raw.some(([n]) => n === attr)) fail(`the attribute ${attr} occurs twice`);
|
|
250
|
+
raw.push([attr, expand(value, true)]);
|
|
251
|
+
}
|
|
252
|
+
const empty = take('/>');
|
|
253
|
+
if (!empty && !take('>')) fail(`the tag <${name}> is not closed`);
|
|
254
|
+
const namespaces = new Map(scope.at(-1)), declared = {};
|
|
255
|
+
for (const [key, value] of raw) {
|
|
256
|
+
if (key !== 'xmlns' && !key.startsWith('xmlns:')) continue;
|
|
257
|
+
const prefix = key === 'xmlns' ? '' : key.slice(6);
|
|
258
|
+
if (prefix === 'xmlns' || value === XMLNS || (prefix === 'xml') !== (value === XML) || (prefix && !value)) fail(`the namespace declaration ${key} is not allowed`);
|
|
259
|
+
namespaces.set(prefix, value);
|
|
260
|
+
declared[prefix] = value;
|
|
261
|
+
}
|
|
262
|
+
scope.push(namespaces);
|
|
263
|
+
const node = { type: 'element', name, ...resolve(name, true), attrs: [], children: [], declared };
|
|
264
|
+
const seen = new Set();
|
|
265
|
+
for (const [key, value] of raw) {
|
|
266
|
+
if (key === 'xmlns' || key.startsWith('xmlns:')) continue;
|
|
267
|
+
const attr = { name: key, ...resolve(key, false), value };
|
|
268
|
+
if (seen.has(attr.ns + ' ' + attr.local)) fail(`the attribute ${key} occurs twice`);
|
|
269
|
+
seen.add(attr.ns + ' ' + attr.local);
|
|
270
|
+
node.attrs.push(attr);
|
|
271
|
+
}
|
|
272
|
+
if (!empty) {
|
|
273
|
+
for (;;) {
|
|
274
|
+
if (take('</')) {
|
|
275
|
+
if (read(QNAME) !== name) fail(`</${name}> is expected`);
|
|
276
|
+
read(SPACE);
|
|
277
|
+
if (!take('>')) fail(`the end tag of ${name} is not closed`);
|
|
278
|
+
break;
|
|
279
|
+
} else if (take('<!--')) {
|
|
280
|
+
const body = until('-->', 'comment');
|
|
281
|
+
if (body.includes('--')) fail('a comment contains --');
|
|
282
|
+
node.children.push({ type: 'comment', value: body });
|
|
283
|
+
} else if (take('<![CDATA[')) {
|
|
284
|
+
const value = until(']]>', 'CDATA section'), last = node.children.at(-1);
|
|
285
|
+
if (last?.type === 'text') last.value += value;
|
|
286
|
+
else node.children.push({ type: 'text', value });
|
|
287
|
+
} else if (take('<?')) {
|
|
288
|
+
const target = read(PI_NAME);
|
|
289
|
+
if (!target || target.toLowerCase() === 'xml') fail('a processing instruction has no valid target');
|
|
290
|
+
const data = take('?>') ? '' : (read(SPACE), until('?>', 'processing instruction'));
|
|
291
|
+
node.children.push({ type: 'pi', target, value: data });
|
|
292
|
+
} else if (take('<')) {
|
|
293
|
+
node.children.push(element());
|
|
294
|
+
} else if (at >= text.length) {
|
|
295
|
+
fail(`<${name}> is not closed`);
|
|
296
|
+
} else {
|
|
297
|
+
const end = text.indexOf('<', at);
|
|
298
|
+
const raw = text.slice(at, end < 0 ? text.length : end);
|
|
299
|
+
if (raw.includes(']]>')) fail('character data contains ]]>');
|
|
300
|
+
at += raw.length;
|
|
301
|
+
const value = expand(raw, false);
|
|
302
|
+
const last = node.children.at(-1);
|
|
303
|
+
if (last?.type === 'text') last.value += value;
|
|
304
|
+
else node.children.push({ type: 'text', value });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
scope.pop();
|
|
309
|
+
return node;
|
|
310
|
+
};
|
|
311
|
+
if (!take('<')) fail('the document has no root element');
|
|
312
|
+
const root = element();
|
|
313
|
+
misc();
|
|
314
|
+
if (at < text.length) fail('only one root element is allowed');
|
|
315
|
+
return root;
|
|
316
|
+
}
|