Debian Codegraph @

src/N3Writer.js

raw
1 // **N3Writer** writes N3 documents.
2 import namespaces from './IRIs';
3 import { default as N3DataFactory, Term } from './N3DataFactory';
4 import { isDefaultGraph } from './N3Util';
5
6 const DEFAULTGRAPH = N3DataFactory.defaultGraph();
7
8 const { rdf, xsd } = namespaces;
9
10 // Characters in literals that require escaping
11 const escape = /["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,
12 escapeAll = /["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,
13 escapedCharacters = {
14 '\\': '\\\\', '"': '\\"', '\t': '\\t',
15 '\n': '\\n', '\r': '\\r', '\b': '\\b', '\f': '\\f',
16 };
17
18 // ## Placeholder class to represent already pretty-printed terms
19 class SerializedTerm extends Term {
20 // Pretty-printed nodes are not equal to any other node
21 // (e.g., [] does not equal [])
22 equals() {
23 return false;
24 }
25 }
26
27 // ## Constructor
28 export default class N3Writer {
29 constructor(outputStream, options) {
30 // ### `_prefixRegex` matches a prefixed name or IRI that begins with one of the added prefixes
31 this._prefixRegex = /$0^/;
32
33 // Shift arguments if the first argument is not a stream
34 if (outputStream && typeof outputStream.write !== 'function')
35 options = outputStream, outputStream = null;
36 options = options || {};
37 this._lists = options.lists;
38
39 // If no output stream given, send the output as string through the end callback
40 if (!outputStream) {
41 let output = '';
42 this._outputStream = {
43 write(chunk, encoding, done) { output += chunk; done && done(); },
44 end: done => { done && done(null, output); },
45 };
46 this._endStream = true;
47 }
48 else {
49 this._outputStream = outputStream;
50 this._endStream = options.end === undefined ? true : !!options.end;
51 }
52
53 // Initialize writer, depending on the format
54 this._subject = null;
55 if (!(/triple|quad/i).test(options.format)) {
56 this._lineMode = false;
57 this._graph = DEFAULTGRAPH;
58 this._prefixIRIs = Object.create(null);
59 options.prefixes && this.addPrefixes(options.prefixes);
60 if (options.baseIRI) {
61 this._baseMatcher = new RegExp(`^${escapeRegex(options.baseIRI)
62 }${options.baseIRI.endsWith('/') ? '' : '[#?]'}`);
63 this._baseLength = options.baseIRI.length;
64 }
65 }
66 else {
67 this._lineMode = true;
68 this._writeQuad = this._writeQuadLine;
69 }
70 }
71
72 // ## Private methods
73
74 // ### Whether the current graph is the default graph
75 get _inDefaultGraph() {
76 return DEFAULTGRAPH.equals(this._graph);
77 }
78
79 // ### `_write` writes the argument to the output stream
80 _write(string, callback) {
81 this._outputStream.write(string, 'utf8', callback);
82 }
83
84 // ### `_writeQuad` writes the quad to the output stream
85 _writeQuad(subject, predicate, object, graph, done) {
86 try {
87 // Write the graph's label if it has changed
88 if (!graph.equals(this._graph)) {
89 // Close the previous graph and start the new one
90 this._write((this._subject === null ? '' : (this._inDefaultGraph ? '.\n' : '\n}\n')) +
91 (DEFAULTGRAPH.equals(graph) ? '' : `${this._encodeIriOrBlank(graph)} {\n`));
92 this._graph = graph;
93 this._subject = null;
94 }
95 // Don't repeat the subject if it's the same
96 if (subject.equals(this._subject)) {
97 // Don't repeat the predicate if it's the same
98 if (predicate.equals(this._predicate))
99 this._write(`, ${this._encodeObject(object)}`, done);
100 // Same subject, different predicate
101 else
102 this._write(`;\n ${
103 this._encodePredicate(this._predicate = predicate)} ${
104 this._encodeObject(object)}`, done);
105 }
106 // Different subject; write the whole quad
107 else
108 this._write(`${(this._subject === null ? '' : '.\n') +
109 this._encodeSubject(this._subject = subject)} ${
110 this._encodePredicate(this._predicate = predicate)} ${
111 this._encodeObject(object)}`, done);
112 }
113 catch (error) { done && done(error); }
114 }
115
116 // ### `_writeQuadLine` writes the quad to the output stream as a single line
117 _writeQuadLine(subject, predicate, object, graph, done) {
118 // Write the quad without prefixes
119 delete this._prefixMatch;
120 this._write(this.quadToString(subject, predicate, object, graph), done);
121 }
122
123 // ### `quadToString` serializes a quad as a string
124 quadToString(subject, predicate, object, graph) {
125 return `${this._encodeSubject(subject)} ${
126 this._encodeIriOrBlank(predicate)} ${
127 this._encodeObject(object)
128 }${graph && graph.value ? ` ${this._encodeIriOrBlank(graph)} .\n` : ' .\n'}`;
129 }
130
131 // ### `quadsToString` serializes an array of quads as a string
132 quadsToString(quads) {
133 return quads.map(t => {
134 return this.quadToString(t.subject, t.predicate, t.object, t.graph);
135 }).join('');
136 }
137
138 // ### `_encodeSubject` represents a subject
139 _encodeSubject(entity) {
140 return entity.termType === 'Quad' ?
141 this._encodeQuad(entity) : this._encodeIriOrBlank(entity);
142 }
143
144 // ### `_encodeIriOrBlank` represents an IRI or blank node
145 _encodeIriOrBlank(entity) {
146 // A blank node or list is represented as-is
147 if (entity.termType !== 'NamedNode') {
148 // If it is a list head, pretty-print it
149 if (this._lists && (entity.value in this._lists))
150 entity = this.list(this._lists[entity.value]);
151 return 'id' in entity ? entity.id : `_:${entity.value}`;
152 }
153 let iri = entity.value;
154 // Use relative IRIs if requested and possible
155 if (this._baseMatcher && this._baseMatcher.test(iri))
156 iri = iri.substr(this._baseLength);
157 // Escape special characters
158 if (escape.test(iri))
159 iri = iri.replace(escapeAll, characterReplacer);
160 // Try to represent the IRI as prefixed name
161 const prefixMatch = this._prefixRegex.exec(iri);
162 return !prefixMatch ? `<${iri}>` :
163 (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);
164 }
165
166 // ### `_encodeLiteral` represents a literal
167 _encodeLiteral(literal) {
168 // Escape special characters
169 let value = literal.value;
170 if (escape.test(value))
171 value = value.replace(escapeAll, characterReplacer);
172
173 // Write a language-tagged literal
174 if (literal.language)
175 return `"${value}"@${literal.language}`;
176
177 // Write dedicated literals per data type
178 if (this._lineMode) {
179 // Only abbreviate strings in N-Triples or N-Quads
180 if (literal.datatype.value === xsd.string)
181 return `"${value}"`;
182 }
183 else {
184 // Use common datatype abbreviations in Turtle or TriG
185 switch (literal.datatype.value) {
186 case xsd.string:
187 return `"${value}"`;
188 case xsd.boolean:
189 if (value === 'true' || value === 'false')
190 return value;
191 break;
192 case xsd.integer:
193 if (/^[+-]?\d+$/.test(value))
194 return value;
195 break;
196 case xsd.decimal:
197 if (/^[+-]?\d*\.\d+$/.test(value))
198 return value;
199 break;
200 case xsd.double:
201 if (/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(value))
202 return value;
203 break;
204 }
205 }
206
207 // Write a regular datatyped literal
208 return `"${value}"^^${this._encodeIriOrBlank(literal.datatype)}`;
209 }
210
211 // ### `_encodePredicate` represents a predicate
212 _encodePredicate(predicate) {
213 return predicate.value === rdf.type ? 'a' : this._encodeIriOrBlank(predicate);
214 }
215
216 // ### `_encodeObject` represents an object
217 _encodeObject(object) {
218 switch (object.termType) {
219 case 'Quad':
220 return this._encodeQuad(object);
221 case 'Literal':
222 return this._encodeLiteral(object);
223 default:
224 return this._encodeIriOrBlank(object);
225 }
226 }
227
228 // ### `_encodeQuad` encodes an RDF* quad
229 _encodeQuad({ subject, predicate, object, graph }) {
230 return `<<${
231 this._encodeSubject(subject)} ${
232 this._encodePredicate(predicate)} ${
233 this._encodeObject(object)}${
234 isDefaultGraph(graph) ? '' : ` ${this._encodeIriOrBlank(graph)}`}>>`;
235 }
236
237 // ### `_blockedWrite` replaces `_write` after the writer has been closed
238 _blockedWrite() {
239 throw new Error('Cannot write because the writer has been closed.');
240 }
241
242 // ### `addQuad` adds the quad to the output stream
243 addQuad(subject, predicate, object, graph, done) {
244 // The quad was given as an object, so shift parameters
245 if (object === undefined)
246 this._writeQuad(subject.subject, subject.predicate, subject.object, subject.graph, predicate);
247 // The optional `graph` parameter was not provided
248 else if (typeof graph === 'function')
249 this._writeQuad(subject, predicate, object, DEFAULTGRAPH, graph);
250 // The `graph` parameter was provided
251 else
252 this._writeQuad(subject, predicate, object, graph || DEFAULTGRAPH, done);
253 }
254
255 // ### `addQuads` adds the quads to the output stream
256 addQuads(quads) {
257 for (let i = 0; i < quads.length; i++)
258 this.addQuad(quads[i]);
259 }
260
261 // ### `addPrefix` adds the prefix to the output stream
262 addPrefix(prefix, iri, done) {
263 const prefixes = {};
264 prefixes[prefix] = iri;
265 this.addPrefixes(prefixes, done);
266 }
267
268 // ### `addPrefixes` adds the prefixes to the output stream
269 addPrefixes(prefixes, done) {
270 // Ignore prefixes if not supported by the serialization
271 if (!this._prefixIRIs)
272 return done && done();
273
274 // Write all new prefixes
275 let hasPrefixes = false;
276 for (let prefix in prefixes) {
277 let iri = prefixes[prefix];
278 if (typeof iri !== 'string')
279 iri = iri.value;
280 hasPrefixes = true;
281 // Finish a possible pending quad
282 if (this._subject !== null) {
283 this._write(this._inDefaultGraph ? '.\n' : '\n}\n');
284 this._subject = null, this._graph = '';
285 }
286 // Store and write the prefix
287 this._prefixIRIs[iri] = (prefix += ':');
288 this._write(`@prefix ${prefix} <${iri}>.\n`);
289 }
290 // Recreate the prefix matcher
291 if (hasPrefixes) {
292 let IRIlist = '', prefixList = '';
293 for (const prefixIRI in this._prefixIRIs) {
294 IRIlist += IRIlist ? `|${prefixIRI}` : prefixIRI;
295 prefixList += (prefixList ? '|' : '') + this._prefixIRIs[prefixIRI];
296 }
297 IRIlist = escapeRegex(IRIlist, /[\]\/\(\)\*\+\?\.\\\$]/g, '\\$&');
298 this._prefixRegex = new RegExp(`^(?:${prefixList})[^\/]*$|` +
299 `^(${IRIlist})([_a-zA-Z][\\-_a-zA-Z0-9]*)$`);
300 }
301 // End a prefix block with a newline
302 this._write(hasPrefixes ? '\n' : '', done);
303 }
304
305 // ### `blank` creates a blank node with the given content
306 blank(predicate, object) {
307 let children = predicate, child, length;
308 // Empty blank node
309 if (predicate === undefined)
310 children = [];
311 // Blank node passed as blank(Term("predicate"), Term("object"))
312 else if (predicate.termType)
313 children = [{ predicate: predicate, object: object }];
314 // Blank node passed as blank({ predicate: predicate, object: object })
315 else if (!('length' in predicate))
316 children = [predicate];
317
318 switch (length = children.length) {
319 // Generate an empty blank node
320 case 0:
321 return new SerializedTerm('[]');
322 // Generate a non-nested one-triple blank node
323 case 1:
324 child = children[0];
325 if (!(child.object instanceof SerializedTerm))
326 return new SerializedTerm(`[ ${this._encodePredicate(child.predicate)} ${
327 this._encodeObject(child.object)} ]`);
328 // Generate a multi-triple or nested blank node
329 default:
330 let contents = '[';
331 // Write all triples in order
332 for (let i = 0; i < length; i++) {
333 child = children[i];
334 // Write only the object is the predicate is the same as the previous
335 if (child.predicate.equals(predicate))
336 contents += `, ${this._encodeObject(child.object)}`;
337 // Otherwise, write the predicate and the object
338 else {
339 contents += `${(i ? ';\n ' : '\n ') +
340 this._encodePredicate(child.predicate)} ${
341 this._encodeObject(child.object)}`;
342 predicate = child.predicate;
343 }
344 }
345 return new SerializedTerm(`${contents}\n]`);
346 }
347 }
348
349 // ### `list` creates a list node with the given content
350 list(elements) {
351 const length = elements && elements.length || 0, contents = new Array(length);
352 for (let i = 0; i < length; i++)
353 contents[i] = this._encodeObject(elements[i]);
354 return new SerializedTerm(`(${contents.join(' ')})`);
355 }
356
357 // ### `end` signals the end of the output stream
358 end(done) {
359 // Finish a possible pending quad
360 if (this._subject !== null) {
361 this._write(this._inDefaultGraph ? '.\n' : '\n}\n');
362 this._subject = null;
363 }
364 // Disallow further writing
365 this._write = this._blockedWrite;
366
367 // Try to end the underlying stream, ensuring done is called exactly one time
368 let singleDone = done && ((error, result) => { singleDone = null, done(error, result); });
369 if (this._endStream) {
370 try { return this._outputStream.end(singleDone); }
371 catch (error) { /* error closing stream */ }
372 }
373 singleDone && singleDone();
374 }
375 }
376
377 // Replaces a character by its escaped version
378 function characterReplacer(character) {
379 // Replace a single character by its escaped version
380 let result = escapedCharacters[character];
381 if (result === undefined) {
382 // Replace a single character with its 4-bit unicode escape sequence
383 if (character.length === 1) {
384 result = character.charCodeAt(0).toString(16);
385 result = '\\u0000'.substr(0, 6 - result.length) + result;
386 }
387 // Replace a surrogate pair with its 8-bit unicode escape sequence
388 else {
389 result = ((character.charCodeAt(0) - 0xD800) * 0x400 +
390 character.charCodeAt(1) + 0x2400).toString(16);
391 result = '\\U00000000'.substr(0, 10 - result.length) + result;
392 }
393 }
394 return result;
395 }
396
397 function escapeRegex(regex) {
398 return regex.replace(/[\]\/\(\)\*\+\?\.\\\$]/g, '\\$&');
399 }