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/src/messages.js CHANGED
@@ -1,7 +1,8 @@
1
1
  // RDF Message Logs: delimit datasets before parsing them, so blank nodes and
2
2
  // assertions stay local to a message. The replay view is ordinary N3 data.
3
3
  // See https://w3c-cg.github.io/rsp/spec/messages and its companion tests.
4
- import { DEFAULT_GRAPH, parseRdf } from './rdf.js';
4
+ import { DEFAULT_GRAPH, neutralQuads, neutralToTerms, parseRdf, parseRdfXmlLog, writeRdf } from './rdf.js';
5
+ import { readJelly, writeJelly } from './jelly.js';
5
6
  import { readSources } from './n3.js';
6
7
  import { tripleToEyemind } from './n3-writer.js';
7
8
  import { EyemindError } from './terms.js';
@@ -15,6 +16,8 @@ const triple = (s, p, o) => ({ s, p: iri(p), o });
15
16
  const int = (v) => ({ t: 'int', v: BigInt(v) });
16
17
  const wordEnd = (c) => c === undefined || /[\s<>"'{}\[\]();,]/.test(c);
17
18
  const iriText = (v) => v.replace(/[\u0000-\u0020<>"{}|^`\\]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
19
+ // The start of an RDF/XML message log: its rdfm:MessageLog root.
20
+ const XML_LOG = /^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<(?:[\w.-]+:)?MessageLog[\s>/]/;
18
21
  function trivia(s, at, final) {
19
22
  while (at < s.length) {
20
23
  if (/\s/.test(s[at])) at++;
@@ -30,9 +33,12 @@ function trivia(s, at, final) {
30
33
  // Accept strings incrementally. Only the current message and active directive
31
34
  // context are retained; onMessage runs before reading any further input.
32
35
  export class RdfMessageReader {
33
- constructor({ format = 'trig', base = null, scope = 'messages', onMessage = () => {}, probe = false } = {}) {
34
- if (!['turtle', 'trig', 'n-triples', 'n-quads'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
36
+ constructor({ format = 'trig', base = null, scope = 'messages', onMessage = () => {}, probe = false, loadDocument = null } = {}) {
37
+ if (!['turtle', 'trig', 'n-triples', 'n-quads', 'rdf-xml', 'ndjson-ld', 'jelly'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
35
38
  this.format = format;
39
+ this.loadDocument = loadDocument;
40
+ this.context = undefined;
41
+ this.line = 0;
36
42
  this.base = base;
37
43
  this.scope = scope;
38
44
  this.onMessage = onMessage;
@@ -54,7 +60,27 @@ export class RdfMessageReader {
54
60
 
55
61
  write(text) {
56
62
  if (this.stopped) return;
63
+ // Jelly is bytes, kept as one character per byte.
64
+ if (text instanceof Uint8Array) {
65
+ let chunk = '';
66
+ for (let i = 0; i < text.length; i += 0x8000) chunk += String.fromCharCode(...text.subarray(i, i + 0x8000));
67
+ text = chunk;
68
+ }
57
69
  this.buffer += text;
70
+ // An RDF/XML log is one XML document, and a Jelly stream is read whole.
71
+ if (this.format === 'rdf-xml' || this.format === 'jelly') return;
72
+ if (this.format === 'ndjson-ld') {
73
+ for (let end = this.buffer.indexOf('\n'); end >= 0 && !this.stopped; end = this.buffer.indexOf('\n')) {
74
+ const line = this.buffer.slice(0, end);
75
+ this.buffer = this.buffer.slice(end + 1);
76
+ this.ndjsonLine(line.replace(/\r$/, ''));
77
+ }
78
+ return;
79
+ }
80
+ if (this.probe && XML_LOG.test(this.buffer)) {
81
+ this.isLog = true;
82
+ return;
83
+ }
58
84
  this.scan(false);
59
85
  if (this.probe) {
60
86
  this.buffer = this.buffer.slice(this.at);
@@ -64,6 +90,40 @@ export class RdfMessageReader {
64
90
 
65
91
  finish() {
66
92
  if (this.stopped) { this.buffer = ''; return; }
93
+ if (this.format === 'jelly') {
94
+ try {
95
+ const read = readJelly(this.buffer);
96
+ if (!read.messages) throw new EyemindError('a Jelly stream of RDF Messages has the stream type MESSAGES');
97
+ for (const [i, statements] of read.messages.entries()) {
98
+ this.index = i + 1;
99
+ const message = { quads: neutralToTerms(statements, `${this.scope}#message${i + 1}`), prefixes: read.namespaces, base: this.base, index: i + 1 };
100
+ if (this.onMessage(message) === false) break;
101
+ }
102
+ } catch (error) {
103
+ throw new EyemindError(`RDF Message Log: ${error.message.replace(/^RDF Message Log: /, '')}`);
104
+ } finally {
105
+ this.buffer = '';
106
+ }
107
+ return;
108
+ }
109
+ if (this.format === 'ndjson-ld') {
110
+ if (this.buffer !== '') this.ndjsonLine(this.buffer.replace(/\r$/, ''));
111
+ this.buffer = '';
112
+ return;
113
+ }
114
+ if (this.format === 'rdf-xml') {
115
+ try {
116
+ for (const message of parseRdfXmlLog(this.buffer, { base: this.base, scope: this.scope })) {
117
+ this.index = message.index;
118
+ if (this.onMessage(message) === false) break;
119
+ }
120
+ } catch (error) {
121
+ throw new EyemindError(`RDF Message Log: ${error.message}`);
122
+ } finally {
123
+ this.buffer = '';
124
+ }
125
+ return;
126
+ }
67
127
  this.scan(true);
68
128
  if (!this.probe) {
69
129
  if (!this.isLog) throw new EyemindError('RDF Message Log needs a VERSION "*-messages" directive');
@@ -72,6 +132,39 @@ export class RdfMessageReader {
72
132
  this.buffer = '';
73
133
  }
74
134
 
135
+ // A line of an NDJSON-LD log: a context message, whose @context is the
136
+ // active context for the messages that follow, an empty message {}, or a
137
+ // data message, read as the document {"@context": C, "@graph": message}.
138
+ // https://w3c-cg.github.io/rsp/spec/messages#ndjson-ld
139
+ ndjsonLine(line) {
140
+ this.line++;
141
+ let object;
142
+ try {
143
+ object = JSON.parse(line);
144
+ } catch {
145
+ object = null;
146
+ }
147
+ if (line.trim() === '') throw new EyemindError(`RDF Message Log line ${this.line}: NDJSON-LD allows no blank lines`);
148
+ if (object === null || typeof object !== 'object' || Array.isArray(object)) {
149
+ throw new EyemindError(`RDF Message Log line ${this.line}: each line of NDJSON-LD is one JSON object`);
150
+ }
151
+ const keys = Object.keys(object);
152
+ if (keys.length === 1 && keys[0] === '@context') {
153
+ this.context = object['@context'];
154
+ return;
155
+ }
156
+ const document = keys.length === 0 ? null : this.context === undefined ? object : { '@context': this.context, '@graph': object };
157
+ const number = this.index + 1;
158
+ let quads = [];
159
+ try {
160
+ if (document) quads = parseRdf(JSON.stringify(document), { format: 'json-ld', base: this.base, scope: `${this.scope}#message${number}`, loadDocument: this.loadDocument }).quads;
161
+ } catch (error) {
162
+ throw new EyemindError(`RDF Message Log message ${number}: ${error.message}`);
163
+ }
164
+ this.isLog = true;
165
+ this.stopped = this.onMessage({ quads, prefixes: {}, base: this.base, index: ++this.index }) === false;
166
+ }
167
+
75
168
  emit(text, boundary) {
76
169
  if (this.probe) return;
77
170
  const line = this.format === 'n-triples' || this.format === 'n-quads';
@@ -216,9 +309,10 @@ export class RdfMessageReader {
216
309
  }
217
310
 
218
311
  export function isRdfMessageLog(text) {
312
+ if (XML_LOG.test(text)) return true;
219
313
  const reader = new RdfMessageReader({ probe: true });
220
314
  try {
221
- reader.write(String(text));
315
+ reader.write(text instanceof Uint8Array ? text : String(text));
222
316
  reader.finish();
223
317
  } catch { /* The selected parser reports malformed inputs. */ }
224
318
  return reader.isLog;
@@ -257,7 +351,43 @@ export function replayMessages(messages, { scope = 'messages' } = {}) {
257
351
  export function parseRdfMessages(text, options = {}) {
258
352
  const messages = [];
259
353
  const reader = new RdfMessageReader({ ...options, onMessage: (m) => messages.push(m) });
260
- reader.write(String(text));
354
+ reader.write(text instanceof Uint8Array ? text : String(text));
261
355
  reader.finish();
262
356
  return { ...replayMessages(messages, options), messages };
263
357
  }
358
+
359
+ // An RDF Message Log of messages, each its quads: VERSION "1.2-messages"
360
+ // and a MESSAGE delimiter between messages in Turtle, TriG, N-Triples and
361
+ // N-Quads, an rdf:RDF per message in RDF/XML, a line per message in
362
+ // NDJSON-LD, and message boundaries in Jelly, whose log is bytes. A final empty message needs one more delimiter, as a trailing
363
+ // delimiter alone opens no message.
364
+ export function writeRdfMessages(messages, { format = 'trig', prefixes = {} } = {}) {
365
+ if (format === 'jelly') {
366
+ try {
367
+ return writeJelly(messages.map((quads) => neutralQuads(quads)), { messages: true, namespaces: prefixes });
368
+ } catch (error) {
369
+ throw new EyemindError(error.message);
370
+ }
371
+ }
372
+ if (format === 'ndjson-ld') {
373
+ return messages.map((quads) => `${quads.length ? JSON.stringify({ '@graph': JSON.parse(writeRdf(quads, { format: 'json-ld' })) }) : '{}'}\n`).join('');
374
+ }
375
+ if (format === 'rdf-xml') {
376
+ let version = '1.0';
377
+ const parts = messages.map((quads) => {
378
+ const text = writeRdf(quads, { format: 'rdf-xml', prefixes });
379
+ if (text.startsWith('<?xml version="1.1"')) version = '1.1';
380
+ return text.replace(/^<\?xml[^>]*\?>\n/, '').replace(/^/gm, ' ').trimEnd();
381
+ });
382
+ return `<?xml version="${version}" encoding="utf-8"?>\n<rdfm:MessageLog xmlns:rdfm="https://w3c-cg.github.io/rsp/spec/messages#">\n` +
383
+ parts.map((p) => `${p}\n`).join('') + '</rdfm:MessageLog>\n';
384
+ }
385
+ if (!['turtle', 'trig', 'n-triples', 'n-quads'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
386
+ const out = ['VERSION "1.2-messages"\n'];
387
+ messages.forEach((quads, i) => {
388
+ if (i > 0) out.push('MESSAGE\n');
389
+ out.push(writeRdf(quads, { format, prefixes }));
390
+ });
391
+ if (messages.length && !messages.at(-1).length) out.push('MESSAGE\n');
392
+ return out.join('');
393
+ }
@@ -1,16 +1,19 @@
1
1
  // Node's incremental RDF Message input. The shared CLI supplies the operation
2
2
  // to run for each message; this adapter owns only file/HTTP/stdin access.
3
- import { createReadStream } from 'node:fs';
3
+ import { createReadStream, readFileSync } from 'node:fs';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { resolve } from 'node:path';
6
6
  import { rdfMessageFormat } from './formats.js';
7
7
  import { replayMessages, RdfMessageReader } from './messages.js';
8
+ import { isJellyMessages } from './jelly.js';
8
9
 
9
10
  const remote = (name) => /^https?:/.test(name);
10
11
 
11
12
  async function messageFile(name) {
12
13
  if (name === '-' || remote(name)) return true;
13
14
  if (/\.js$/i.test(name)) return false;
15
+ if (rdfMessageFormat(name) === 'ndjson-ld') return true;
16
+ if (rdfMessageFormat(name) === 'jelly') return isJellyMessages(readFileSync(name));
14
17
  const probe = new RdfMessageReader({ probe: true });
15
18
  for await (const text of createReadStream(name, { encoding: 'utf8' })) {
16
19
  probe.write(text);
@@ -26,7 +29,7 @@ async function openSource(name) {
26
29
  process.stdin.setEncoding('utf8');
27
30
  return { body: process.stdin, base: null };
28
31
  }
29
- if (!remote(name)) return { body: createReadStream(name, { encoding: 'utf8' }), base: pathToFileURL(resolve(name)).href };
32
+ if (!remote(name)) return { body: createReadStream(name, { encoding: /\.jelly$/i.test(name) ? 'latin1' : 'utf8' }), base: pathToFileURL(resolve(name)).href };
30
33
  const controller = new AbortController();
31
34
  const timer = setTimeout(() => controller.abort(), 10000);
32
35
  let response;
@@ -59,7 +62,7 @@ export async function streamMessages(request, io) {
59
62
  if (await messageFile(name)) logs.push({ name, index });
60
63
  else inputs.push([name, io.readFile(name)]);
61
64
  }
62
- if (!logs.length) throw new Error('--stream-messages needs an RDF Message Log with VERSION "*-messages"');
65
+ if (!logs.length) throw new Error('--stream-messages needs an RDF Message Log: VERSION "*-messages", an rdfm:MessageLog in RDF/XML, NDJSON-LD (.ndjson), or Jelly messages');
63
66
  for (const { name, index } of logs) {
64
67
  const source = await openSource(name);
65
68
  const scope = request.scope(name, index);
package/src/node.js CHANGED
@@ -8,7 +8,9 @@ import vm from 'node:vm';
8
8
  import { EyemindError } from './terms.js';
9
9
 
10
10
  export const nodeIO = {
11
- readFile: (path) => readFileSync(path, 'utf8'),
11
+ // A Jelly file is binary: read as one character per byte, which jelly.js
12
+ // takes back as bytes.
13
+ readFile: (path) => readFileSync(path, /\.jelly$/i.test(path) ? 'latin1' : 'utf8'),
12
14
  // The loader is synchronous. Fetch in a child before compilation, with
13
15
  // bounds on its time and output; no I/O happens during proof checking.
14
16
  readDocument(iri) {
package/src/rdf-lexer.js CHANGED
@@ -259,9 +259,11 @@ function decodeIriRefEscapes(s, offset = null) {
259
259
  for (let i = 0; i < s.length; i++) {
260
260
  const c = s[i];
261
261
  if (c !== '\\') {
262
- const cp = c.codePointAt(0);
262
+ // eyemind: by code point, so a character beyond U+FFFF is no lone surrogate.
263
+ const cp = s.codePointAt(i);
263
264
  assertValidIriRefCodePoint(cp, offset);
264
- out += c;
265
+ out += String.fromCodePoint(cp);
266
+ if (cp > 0xffff) i++;
265
267
  continue;
266
268
  }
267
269
 
@@ -869,11 +871,16 @@ function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
869
871
  }
870
872
  }
871
873
 
872
- // Not TriG named-graph syntax after all; copy the first character and
873
- // continue as ordinary N3.
874
+ // Not TriG named-graph syntax after all; copy the term, or else the
875
+ // first character, and continue as ordinary N3.
876
+ // eyemind: the whole term, so a # in its IRI is no comment.
874
877
  if (graphKeyword) {
875
878
  out += 'GRAPH ';
876
879
  statementStart = false;
880
+ } else if (term && term.end > i) {
881
+ out += s.slice(i, term.end);
882
+ i = term.end;
883
+ statementStart = false;
877
884
  } else if (i < s.length) {
878
885
  const copied = s[i++];
879
886
  out += copied;
package/src/rdf-parser.js CHANGED
@@ -274,6 +274,9 @@ class Parser {
274
274
  if (typ === 'LtLt') return this.parseReifiedTriple();
275
275
 
276
276
  if (typ === 'IriRef') {
277
+ // eyemind: N-Triples and N-Quads take an IRI as written; Turtle and
278
+ // TriG resolve every IRI reference (RFC 3986, 5.2).
279
+ if (this.verbatimIris) return internIri(val || '');
277
280
  const base = this.prefixes.baseIri || '';
278
281
  return internIri(resolveIriRef(val || '', base));
279
282
  }
package/src/rdf-xml.js ADDED
@@ -0,0 +1,363 @@
1
+ // RDF/XML in eyemind: the grammar of RDF 1.2 XML Syntax read from an XML
2
+ // tree, giving the same quads as the other RDF formats, and those quads
3
+ // written as RDF/XML. Where the RDF 1.2
4
+ // draft disagrees with itself, the W3C RDF/XML tests decide: a triple term
5
+ // (rdf:parseType="Triple") holds one node element with one property, and
6
+ // rdf:annotation or rdf:annotationNodeID names a reifier of its triple.
7
+ // https://www.w3.org/TR/rdf12-xml/#section-Infoset-Grammar
8
+ import { resolveIriRef } from './rdf-prelude.js';
9
+ import { Struct } from './terms.js';
10
+ import { isNcName, isXmlContent, parseXml } from './xml.js';
11
+
12
+ const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
13
+ const XML = 'http://www.w3.org/XML/1998/namespace';
14
+ const ITS = 'http://www.w3.org/2005/11/its';
15
+
16
+ // The names the grammar reserves (RDF 1.2 XML Syntax, 6.2.2 to 6.2.4).
17
+ const CORE = new Set(['RDF', 'ID', 'about', 'parseType', 'resource', 'nodeID', 'datatype', 'version', 'annotation', 'annotationNodeID']);
18
+ const OLD = new Set(['aboutEach', 'aboutEachPrefix', 'bagID']);
19
+ // Unqualified attributes that older documents use for their RDF names.
20
+ const UNQUALIFIED = new Set(['ID', 'about', 'resource', 'parseType', 'type', 'version']);
21
+
22
+ const st = (name, ...args) => new Struct(name, args);
23
+ const iri = (v) => st('iri', v);
24
+ // Whether an RDF version of 1.2 or later, such as 1.2-basic, is in scope.
25
+ const rdf12 = (context) => /^(?:1\.(?:[2-9]|[1-9][0-9]+)|[2-9]\.)/.test(context.version ?? '');
26
+
27
+ // Read an RDF/XML document into [S, P, O, G] quads of the default graph.
28
+ // The caller supplies the terms for literals, so they match the other formats.
29
+ export function parseRdfXml(source, options) {
30
+ const root = parseXml(source);
31
+ const top = { base: options.base ? options.base.replace(/#.*$/, '') : null, lang: '', dir: '', version: '' };
32
+ return { ...reader(options).document(root, top), prefixes: prefixesOf(root), base: top.base };
33
+ }
34
+
35
+ // The messages of an RDF Message Log in RDF/XML: an rdfm:MessageLog root
36
+ // whose rdf:RDF children are the messages, each with its own blank nodes.
37
+ // Namespaces, base, language and direction on the log apply to them all.
38
+ // https://w3c-cg.github.io/rsp/spec/messages#rdf-xml
39
+ const RDFM = 'https://w3c-cg.github.io/rsp/spec/messages#';
40
+ export function parseRdfXmlMessages(source, options) {
41
+ const root = parseXml(source);
42
+ if (root.ns !== RDFM || root.local !== 'MessageLog') throw new SyntaxError('an RDF/XML message log has an rdfm:MessageLog root');
43
+ const top = { base: options.base ? options.base.replace(/#.*$/, '') : null, lang: '', dir: '', version: '' };
44
+ const { context } = reader(options).contextOf(root, top);
45
+ const messages = [];
46
+ for (const child of root.children) {
47
+ if (child.type === 'text' && /\S/.test(child.value)) throw new SyntaxError('an RDF/XML message log holds only rdf:RDF elements');
48
+ if (child.type !== 'element') continue;
49
+ if (child.ns !== RDF || child.local !== 'RDF') throw new SyntaxError(`an RDF/XML message log holds rdf:RDF elements, not <${child.name}>`);
50
+ const scope = `${options.scope ?? 'messages'}#message${messages.length + 1}`;
51
+ messages.push({ ...reader({ ...options, scope }).document(child, context), prefixes: prefixesOf(root), base: context.base, index: messages.length + 1 });
52
+ }
53
+ return messages;
54
+ }
55
+
56
+ function reader({ scope = 'rdf', graph, literal }) {
57
+ const out = [];
58
+ const ids = new Set();
59
+ let blanks = 0;
60
+ const fail = (message) => { throw new SyntaxError(message); };
61
+ const fresh = () => st('bnode', scope, String(++blanks));
62
+ const node = (id) => {
63
+ if (!isNcName(id)) fail(`rdf:nodeID "${id}" is not an XML name`);
64
+ return st('bnode', scope, id);
65
+ };
66
+ const resolve = (ref, context) => iri(resolveIriRef(ref, context.base ?? ''));
67
+ const emit = (s, p, o, target = out) => target.push([s, p, o, graph]);
68
+ const rdf = (local) => iri(RDF + local);
69
+
70
+ // An element's context: base, language, direction and RDF version,
71
+ // inherited, and its attributes without the XML and ITS ones. Text
72
+ // direction (its:dir) needs an RDF version of 1.2 or later in scope.
73
+ const contextOf = (element, parent) => {
74
+ const context = { base: parent.base, lang: parent.lang, dir: parent.dir, version: parent.version };
75
+ const attrs = new Map();
76
+ const version = element.attrs.find((a) => a.local === 'version' && (a.ns === RDF || !a.ns));
77
+ if (version) context.version = version.value;
78
+ for (const a of element.attrs) {
79
+ if (a.ns === XML) {
80
+ if (a.local === 'base') context.base = resolveIriRef(a.value, parent.base ?? '').replace(/#.*$/, '');
81
+ else if (a.local === 'lang') context.lang = a.value.toLowerCase();
82
+ } else if (a.ns === ITS) {
83
+ if (a.local === 'dir' && rdf12(context)) {
84
+ if (!['ltr', 'rtl', ''].includes(a.value)) fail(`its:dir is ltr or rtl, not "${a.value}"`);
85
+ context.dir = a.value;
86
+ }
87
+ } else if (!a.ns && /^xml/i.test(a.local)) {
88
+ // Names starting with xml are reserved by XML and ignored here.
89
+ } else if (!a.ns) {
90
+ if (!UNQUALIFIED.has(a.local)) fail(`the attribute ${a.name} has no namespace`);
91
+ attrs.set(RDF + a.local, a.value);
92
+ } else attrs.set(a.ns + a.local, a.value);
93
+ }
94
+ attrs.delete(`${RDF}version`);
95
+ return { context, attrs };
96
+ };
97
+ const textOf = (element) => element.children.filter((c) => c.type === 'text').map((c) => c.value).join('');
98
+ const elements = (element) => {
99
+ const found = element.children.filter((c) => c.type === 'element');
100
+ if (found.length && /\S/.test(textOf(element))) fail(`<${element.name}> mixes text and elements`);
101
+ return found;
102
+ };
103
+ const plain = (value, context) => literal(value, context.lang ? { lang: context.lang, dir: context.dir } : null, null);
104
+ const idOf = (value, context) => {
105
+ if (!isNcName(value)) fail(`rdf:ID "${value}" is not an XML name`);
106
+ const id = resolveIriRef(`#${value}`, context.base ?? '');
107
+ if (ids.has(id)) fail(`rdf:ID "${value}" is used twice with one base`);
108
+ ids.add(id);
109
+ return iri(id);
110
+ };
111
+
112
+ // A node element: its subject, type and property attributes, then its
113
+ // property elements. Returns the subject.
114
+ const nodeElement = (element, parent, target = out) => {
115
+ const name = element.ns + element.local;
116
+ if (name.startsWith(RDF) && (CORE.has(element.local) || OLD.has(element.local) || element.local === 'li')) {
117
+ fail(`rdf:${element.local} cannot name a node element`);
118
+ }
119
+ const { context, attrs } = contextOf(element, parent);
120
+ const ways = [`${RDF}ID`, `${RDF}about`, `${RDF}nodeID`].filter((k) => attrs.has(k));
121
+ if (ways.length > 1) fail(`<${element.name}> has more than one of rdf:ID, rdf:about and rdf:nodeID`);
122
+ let subject;
123
+ if (attrs.has(`${RDF}ID`)) subject = idOf(attrs.get(`${RDF}ID`), context);
124
+ else if (attrs.has(`${RDF}about`)) subject = resolve(attrs.get(`${RDF}about`), context);
125
+ else if (attrs.has(`${RDF}nodeID`)) subject = node(attrs.get(`${RDF}nodeID`));
126
+ else subject = fresh();
127
+ for (const k of ways) attrs.delete(k);
128
+ if (name !== `${RDF}Description`) emit(subject, rdf('type'), iri(name), target);
129
+ propertyAttributes(subject, attrs, context, target);
130
+ let li = 0;
131
+ for (const child of elements(element)) li = propertyElement(child, subject, context, li, target);
132
+ if (/\S/.test(textOf(element))) fail(`<${element.name}> has text, not property elements`);
133
+ return subject;
134
+ };
135
+
136
+ // Property attributes of a node, or of the node an empty property element
137
+ // makes: each is a triple with a literal object, rdf:type an IRI one.
138
+ const propertyAttributes = (subject, attrs, context, target) => {
139
+ for (const [name, value] of attrs) {
140
+ if (name.startsWith(RDF) && (CORE.has(name.slice(RDF.length)) || OLD.has(name.slice(RDF.length)) || ['li', 'Description'].includes(name.slice(RDF.length)))) {
141
+ fail(`rdf:${name.slice(RDF.length)} cannot be a property attribute here`);
142
+ }
143
+ if (name === `${RDF}type`) emit(subject, rdf('type'), resolve(value, context), target);
144
+ else emit(subject, iri(name), plain(value, context), target);
145
+ }
146
+ };
147
+
148
+ // The triples that an rdf:ID on a property element (reification) and an
149
+ // annotation (a reifier of a triple term) add.
150
+ const decorate = (s, p, o, attrs, context, target) => {
151
+ if (attrs.has(`${RDF}ID`)) {
152
+ const r = idOf(attrs.get(`${RDF}ID`), context);
153
+ emit(r, rdf('type'), rdf('Statement'), target);
154
+ emit(r, rdf('subject'), s, target);
155
+ emit(r, rdf('predicate'), p, target);
156
+ emit(r, rdf('object'), o, target);
157
+ }
158
+ if (attrs.has(`${RDF}annotation`) && attrs.has(`${RDF}annotationNodeID`)) fail('rdf:annotation and rdf:annotationNodeID cannot be used together');
159
+ const reifier = attrs.has(`${RDF}annotation`) ? resolve(attrs.get(`${RDF}annotation`), context)
160
+ : attrs.has(`${RDF}annotationNodeID`) ? node(attrs.get(`${RDF}annotationNodeID`)) : null;
161
+ if (reifier) emit(reifier, rdf('reifies'), st('triple', s, p, o), target);
162
+ };
163
+ const only = (attrs, allowed, element) => {
164
+ for (const name of attrs.keys()) {
165
+ if (!name.startsWith(RDF) || !allowed.includes(name.slice(RDF.length))) fail(`<${element.name}> cannot have the attribute ${name.startsWith(RDF) ? `rdf:${name.slice(RDF.length)}` : name}`);
166
+ }
167
+ };
168
+
169
+ // A property element of subject: one triple, and those of its object.
170
+ // Returns the rdf:li counter of the subject's node element.
171
+ const propertyElement = (element, subject, parent, li, target) => {
172
+ let name = element.ns + element.local;
173
+ if (name === `${RDF}li`) name = `${RDF}_${++li}`;
174
+ else if (name.startsWith(RDF) && (CORE.has(element.local) || OLD.has(element.local) || element.local === 'Description')) {
175
+ fail(`rdf:${element.local} cannot name a property element`);
176
+ }
177
+ const p = iri(name);
178
+ const { context, attrs } = contextOf(element, parent);
179
+ const children = elements(element);
180
+ const decorations = ['ID', 'annotation', 'annotationNodeID'];
181
+ const link = (object) => {
182
+ emit(subject, p, object, target);
183
+ decorate(subject, p, object, attrs, context, target);
184
+ return li;
185
+ };
186
+ if (attrs.has(`${RDF}parseType`)) {
187
+ const kind = attrs.get(`${RDF}parseType`);
188
+ attrs.delete(`${RDF}parseType`);
189
+ only(attrs, decorations, element);
190
+ if (kind === 'Resource') {
191
+ const object = fresh();
192
+ link(object);
193
+ let inner = 0;
194
+ for (const child of children) inner = propertyElement(child, object, context, inner, target);
195
+ return li;
196
+ }
197
+ if (kind === 'Collection') {
198
+ const items = children.map((child) => nodeElement(child, context, target));
199
+ const cells = items.map(() => fresh());
200
+ items.forEach((item, i) => {
201
+ emit(cells[i], rdf('first'), item, target);
202
+ emit(cells[i], rdf('rest'), cells[i + 1] ?? rdf('nil'), target);
203
+ });
204
+ return link(cells[0] ?? rdf('nil'));
205
+ }
206
+ if (kind === 'Triple') {
207
+ // Before RDF 1.2, a triple term is ignored.
208
+ if (!rdf12(context)) return li;
209
+ if (children.length !== 1) fail('rdf:parseType="Triple" holds one node element');
210
+ const inner = [];
211
+ nodeElement(children[0], context, inner);
212
+ if (inner.length !== 1) fail('rdf:parseType="Triple" describes exactly one triple');
213
+ return link(st('triple', ...inner[0].slice(0, 3)));
214
+ }
215
+ // Literal, and any other parse type, is an XML literal of the content.
216
+ return link(literal(xmlLiteral(element), null, `${RDF}XMLLiteral`));
217
+ }
218
+ if (children.length) {
219
+ if (children.length > 1) fail(`<${element.name}> holds more than one node element`);
220
+ only(attrs, decorations, element);
221
+ return link(nodeElement(children[0], context, target));
222
+ }
223
+ // A literal: text, or an empty element with only a datatype.
224
+ const rest = new Map([...attrs].filter(([k]) => !(k.startsWith(RDF) && decorations.includes(k.slice(RDF.length)))));
225
+ const value = textOf(element);
226
+ if (value !== '' || (rest.size === 1 && rest.has(`${RDF}datatype`))) {
227
+ only(attrs, [...decorations, 'datatype'], element);
228
+ return link(attrs.has(`${RDF}datatype`) ? literal(value, null, resolveIriRef(attrs.get(`${RDF}datatype`), context.base ?? '')) : plain(value, context));
229
+ }
230
+ // An empty property element: an empty literal, or a resource that the
231
+ // remaining attributes describe.
232
+ if (rest.size === 0) return link(plain('', context));
233
+ if (rest.has(`${RDF}resource`) && rest.has(`${RDF}nodeID`)) fail(`<${element.name}> has both rdf:resource and rdf:nodeID`);
234
+ if (rest.has(`${RDF}datatype`)) fail(`<${element.name}> has rdf:datatype and resource attributes`);
235
+ const object = rest.has(`${RDF}resource`) ? resolve(rest.get(`${RDF}resource`), context)
236
+ : rest.has(`${RDF}nodeID`) ? node(rest.get(`${RDF}nodeID`)) : fresh();
237
+ rest.delete(`${RDF}resource`);
238
+ rest.delete(`${RDF}nodeID`);
239
+ link(object);
240
+ propertyAttributes(object, rest, context, target);
241
+ return li;
242
+ };
243
+
244
+ // A document element: rdf:RDF with node elements, or one node element.
245
+ const document = (root, top) => {
246
+ if (root.ns === RDF && root.local === 'RDF') {
247
+ const { context, attrs } = contextOf(root, top);
248
+ if (attrs.size) fail(`rdf:RDF cannot have the attribute ${[...attrs.keys()][0]}`);
249
+ for (const child of elements(root)) nodeElement(child, context);
250
+ if (/\S/.test(textOf(root))) fail('rdf:RDF holds node elements, not text');
251
+ } else nodeElement(root, top);
252
+ return { quads: out };
253
+ };
254
+ return { document, contextOf };
255
+ }
256
+
257
+ function prefixesOf(root) {
258
+ const out = {};
259
+ for (const [name, ns] of Object.entries(root.declared)) if (name) out[name] = ns;
260
+ return out;
261
+ }
262
+
263
+ // The content of an rdf:parseType="Literal" element in exclusive XML
264
+ // canonical form, with comments: each element declares the namespaces it and
265
+ // its attributes use that no output ancestor has declared alike.
266
+ // https://www.w3.org/TR/xml-exc-c14n/
267
+ function xmlLiteral(element) {
268
+ const escapeText = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
269
+ const escapeAttr = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;')
270
+ .replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
271
+ const prefixOf = (name) => (name.includes(':') ? name.slice(0, name.indexOf(':')) : '');
272
+ const write = (node, rendered) => {
273
+ if (node.type === 'text') return escapeText(node.value);
274
+ if (node.type === 'comment') return `<!--${node.value}-->`;
275
+ if (node.type === 'pi') return `<?${node.target}${node.value ? ` ${node.value}` : ''}?>`;
276
+ const used = new Map([[prefixOf(node.name), node.ns]]);
277
+ for (const a of node.attrs) if (a.name.includes(':')) used.set(prefixOf(a.name), a.ns);
278
+ const declarations = [];
279
+ const inScope = new Map(rendered);
280
+ for (const [prefix, ns] of used) {
281
+ if (prefix === 'xml') continue;
282
+ if ((rendered.get(prefix) ?? '') === ns && (prefix === '' ? true : rendered.has(prefix))) continue;
283
+ if (prefix === '' && ns === '' && !rendered.get('')) continue;
284
+ declarations.push([prefix, ns]);
285
+ inScope.set(prefix, ns);
286
+ }
287
+ declarations.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
288
+ const attrs = [...node.attrs].sort((a, b) => (a.ns === b.ns ? (a.local < b.local ? -1 : 1) : a.ns < b.ns ? -1 : 1));
289
+ const open = `<${node.name}${declarations.map(([prefix, ns]) => ` ${prefix ? `xmlns:${prefix}` : 'xmlns'}="${escapeAttr(ns)}"`).join('')}` +
290
+ `${attrs.map((a) => ` ${a.name}="${escapeAttr(a.value)}"`).join('')}>`;
291
+ return open + node.children.map((child) => write(child, inScope)).join('') + `</${node.name}>`;
292
+ };
293
+ return element.children.map((child) => write(child, new Map())).join('');
294
+ }
295
+
296
+ // RDF/XML out: neutral quads (rdf.js) of the default graph as one rdf:RDF
297
+ // document, a node element per subject. RDF/XML has no named graphs and no
298
+ // triple term subjects; a predicate must end in an XML name to be written.
299
+ // A triple term object needs rdf:version="1.2", a text direction its:dir.
300
+ export function writeRdfXml(quads, prefixes = {}) {
301
+ // Control characters are character references, which XML 1.1 allows.
302
+ let xml11 = false;
303
+ const escape = (s, attribute) => {
304
+ if (/[\u0000\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(s)) {
305
+ throw new SyntaxError('RDF/XML cannot write U+0000, U+FFFE, U+FFFF or a lone surrogate');
306
+ }
307
+ let out = s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
308
+ if (attribute) out = out.replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;');
309
+ return out.replace(/[\u0001-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F]/g, (c) => {
310
+ xml11 ||= c < ' ';
311
+ return `&#x${c.charCodeAt(0).toString(16).toUpperCase()};`;
312
+ });
313
+ };
314
+ const namespaces = new Map([['rdf', RDF]]);
315
+ for (const [name, ns] of Object.entries(prefixes)) if (/^[A-Za-z_][\w.-]*$/.test(name) && !/^xml/i.test(name) && name !== 'rdf') namespaces.set(name, ns);
316
+ let rdf12 = false, its = false;
317
+ const qname = (iri) => {
318
+ for (const [name, ns] of namespaces) if (iri.startsWith(ns) && isNcName(iri.slice(ns.length))) return `${name}:${iri.slice(ns.length)}`;
319
+ const m = /^(.*?)([A-Z_a-zÀ-�][\w.·À-�-]*)$/u.exec(iri);
320
+ if (!m || !m[1] || !isNcName(m[2])) throw new SyntaxError(`RDF/XML cannot write the predicate ${iri}, which does not end in an XML name`);
321
+ let name = `ns${namespaces.size}`;
322
+ while (namespaces.has(name)) name += '_';
323
+ namespaces.set(name, m[1]);
324
+ return `${name}:${m[2]}`;
325
+ };
326
+ const subjectAttribute = (t) => (t.termType === 'blank' ? `rdf:nodeID="${escape(t.value, true)}"` : `rdf:about="${escape(t.value, true)}"`);
327
+ const property = (p, o, indent) => {
328
+ const name = qname(p.value);
329
+ if (o.termType === 'iri') return `${indent}<${name} rdf:resource="${escape(o.value, true)}"/>`;
330
+ if (o.termType === 'blank') return `${indent}<${name} rdf:nodeID="${escape(o.value, true)}"/>`;
331
+ if (o.termType === 'triple') {
332
+ rdf12 = true;
333
+ if (o.subject.termType === 'triple') throw new SyntaxError('RDF/XML cannot write a triple term as a subject');
334
+ return [`${indent}<${name} rdf:parseType="Triple">`, `${indent} <rdf:Description ${subjectAttribute(o.subject)}>`,
335
+ property(o.predicate, o.object, `${indent} `), `${indent} </rdf:Description>`, `${indent}</${name}>`].join('\n');
336
+ }
337
+ if (o.datatype === `${RDF}XMLLiteral` && isXmlContent(o.value)) return `${indent}<${name} rdf:parseType="Literal">${o.value}</${name}>`;
338
+ let attributes = '';
339
+ if (o.language) {
340
+ attributes = ` xml:lang="${escape(o.language, true)}"`;
341
+ if (o.direction) {
342
+ rdf12 = its = true;
343
+ attributes += ` its:dir="${o.direction}"`;
344
+ }
345
+ } else if (o.datatype && o.datatype !== 'http://www.w3.org/2001/XMLSchema#string') {
346
+ attributes = ` rdf:datatype="${escape(o.datatype, true)}"`;
347
+ }
348
+ return `${indent}<${name}${attributes}>${escape(o.value, false)}</${name}>`;
349
+ };
350
+ const subjects = new Map();
351
+ for (const [s, p, o, g] of quads) {
352
+ if (g) throw new SyntaxError('RDF/XML has no named graphs; write TriG, N-Quads or JSON-LD');
353
+ if (s.termType === 'triple') throw new SyntaxError('RDF/XML cannot write a triple term as a subject');
354
+ const key = `${s.termType} ${s.value}`;
355
+ if (!subjects.has(key)) subjects.set(key, [s, []]);
356
+ subjects.get(key)[1].push(property(p, o, ' '));
357
+ }
358
+ const body = [...subjects.values()].map(([s, lines]) => [` <rdf:Description ${subjectAttribute(s)}>`, ...lines, ' </rdf:Description>'].join('\n'));
359
+ const declarations = [...namespaces].map(([name, ns]) => `xmlns:${name}="${escape(ns, true)}"`);
360
+ if (its) declarations.push(`xmlns:its="${ITS}"`, 'its:version="2.0"');
361
+ if (rdf12) declarations.push('rdf:version="1.2"');
362
+ return `<?xml version="${xml11 ? '1.1' : '1.0'}" encoding="utf-8"?>\n<rdf:RDF ${declarations.join('\n ')}>\n${body.map((b) => `${b}\n`).join('')}</rdf:RDF>\n`;
363
+ }