rdflib 2.2.22-4e175603 → 2.2.22-53d65d90

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.
Files changed (95) hide show
  1. package/dist/rdflib.min.js +1 -1
  2. package/dist/rdflib.min.js.LICENSE.txt +4 -0
  3. package/dist/rdflib.min.js.map +1 -1
  4. package/esm/blank-node.js +90 -61
  5. package/esm/class-order.js +1 -1
  6. package/esm/collection.js +106 -70
  7. package/esm/default-graph.js +33 -13
  8. package/esm/empty.js +26 -8
  9. package/esm/factories/canonical-data-factory.js +30 -33
  10. package/esm/factories/extended-term-factory.js +14 -18
  11. package/esm/factories/factory-types.js +1 -1
  12. package/esm/factories/rdflib-data-factory.js +11 -9
  13. package/esm/fetcher.js +1644 -1355
  14. package/esm/formula.js +740 -632
  15. package/esm/index.js +51 -31
  16. package/esm/jsonldparser.js +26 -19
  17. package/esm/jsonparser.js +1 -1
  18. package/esm/lists.js +86 -38
  19. package/esm/literal.js +157 -120
  20. package/esm/log.js +7 -7
  21. package/esm/n3parser.js +1085 -1008
  22. package/esm/named-node.js +99 -69
  23. package/esm/namespace.js +4 -2
  24. package/esm/node-internal.js +98 -74
  25. package/esm/node.js +1 -1
  26. package/esm/parse.js +3 -3
  27. package/esm/patch-parser.js +1 -1
  28. package/esm/query.js +16 -15
  29. package/esm/rdfaparser.js +846 -781
  30. package/esm/rdfxmlparser.js +365 -348
  31. package/esm/serialize.js +4 -20
  32. package/esm/serializer.js +886 -821
  33. package/esm/statement.js +72 -52
  34. package/esm/store.js +924 -822
  35. package/esm/types.js +21 -21
  36. package/esm/update-manager.js +983 -882
  37. package/esm/updates-via.js +134 -104
  38. package/esm/uri.js +3 -3
  39. package/esm/utils/default-graph-uri.js +2 -2
  40. package/esm/utils/terms.js +5 -4
  41. package/esm/utils-js.js +5 -5
  42. package/esm/utils.js +6 -6
  43. package/esm/variable.js +58 -32
  44. package/esm/xsd.js +2 -2
  45. package/lib/blank-node.js +88 -60
  46. package/lib/class-order.js +1 -1
  47. package/lib/collection.js +104 -69
  48. package/lib/default-graph.js +32 -13
  49. package/lib/empty.js +25 -8
  50. package/lib/factories/canonical-data-factory.js +32 -35
  51. package/lib/factories/extended-term-factory.js +14 -18
  52. package/lib/factories/factory-types.js +1 -1
  53. package/lib/factories/rdflib-data-factory.js +11 -9
  54. package/lib/fetcher.js +1646 -1385
  55. package/lib/formula.d.ts +1 -1
  56. package/lib/formula.js +739 -632
  57. package/lib/index.js +87 -66
  58. package/lib/jsonldparser.js +26 -19
  59. package/lib/jsonparser.js +1 -1
  60. package/lib/lists.js +86 -54
  61. package/lib/literal.js +156 -120
  62. package/lib/log.js +7 -7
  63. package/lib/n3parser.js +1089 -1010
  64. package/lib/named-node.js +98 -69
  65. package/lib/namespace.js +4 -2
  66. package/lib/node-internal.js +96 -73
  67. package/lib/node.js +1 -1
  68. package/lib/parse.js +6 -5
  69. package/lib/patch-parser.js +1 -1
  70. package/lib/query.js +18 -19
  71. package/lib/rdfaparser.js +848 -783
  72. package/lib/rdfxmlparser.js +366 -350
  73. package/lib/serialize.d.ts +1 -1
  74. package/lib/serialize.js +4 -21
  75. package/lib/serializer.d.ts +1 -0
  76. package/lib/serializer.js +890 -825
  77. package/lib/statement.js +74 -54
  78. package/lib/store.d.ts +1 -1
  79. package/lib/store.js +926 -844
  80. package/lib/types.js +21 -21
  81. package/lib/update-manager.d.ts +1 -1
  82. package/lib/update-manager.js +959 -865
  83. package/lib/updates-via.js +134 -105
  84. package/lib/uri.js +3 -3
  85. package/lib/utils/default-graph-uri.js +2 -2
  86. package/lib/utils/terms.js +6 -4
  87. package/lib/utils-js.js +9 -8
  88. package/lib/utils.js +6 -6
  89. package/lib/variable.js +60 -34
  90. package/lib/xsd.js +2 -2
  91. package/package.json +6 -6
  92. package/src/jsonldparser.js +1 -1
  93. package/src/serialize.ts +4 -14
  94. package/src/serializer.js +24 -0
  95. package/src/update-manager.ts +8 -2
package/esm/serializer.js CHANGED
@@ -1,3 +1,5 @@
1
+ import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
2
+ import _createClass from "@babel/runtime/helpers/createClass";
1
3
  import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
4
  /* Serialization of RDF Graphs
3
5
  **
@@ -13,12 +15,15 @@ import * as Util from './utils-js';
13
15
  import CanonicalDataFactory from './factories/canonical-data-factory';
14
16
  import { createXSD } from './xsd';
15
17
  import solidNs from 'solid-namespace';
18
+ // import * as jsonld from 'jsonld'
19
+ import * as ttl2jsonld from '@frogcat/ttl2jsonld';
16
20
  export default function createSerializer(store) {
17
21
  return new Serializer(store);
18
22
  }
19
23
  ;
20
- export class Serializer {
21
- constructor(store) {
24
+ export var Serializer = /*#__PURE__*/function () {
25
+ function Serializer(store) {
26
+ _classCallCheck(this, Serializer);
22
27
  _defineProperty(this, "_notQNameChars", '\t\r\n !"#$%&\'()*.,+/;<=>?@[\\]^`{|}~');
23
28
  _defineProperty(this, "_notNameChars", this._notQNameChars + ':');
24
29
  _defineProperty(this, "validPrefix", new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/));
@@ -28,10 +33,10 @@ export class Serializer {
28
33
  this.base = null;
29
34
  this.prefixes = []; // suggested prefixes
30
35
  this.namespaces = []; // complementary
31
- const nsKeys = Object.keys(solidNs());
32
- for (const i in nsKeys) {
33
- const uri = solidNs()[nsKeys[i]]('');
34
- const prefix = nsKeys[i];
36
+ var nsKeys = Object.keys(solidNs());
37
+ for (var i in nsKeys) {
38
+ var uri = solidNs()[nsKeys[i]]('');
39
+ var prefix = nsKeys[i];
35
40
  this.prefixes[uri] = prefix;
36
41
  this.namespaces[prefix] = uri;
37
42
  }
@@ -47,922 +52,982 @@ export class Serializer {
47
52
  this.rdfFactory = store.rdfFactory || CanonicalDataFactory;
48
53
  this.xsd = createXSD(this.rdfFactory);
49
54
  }
50
- setBase(base) {
51
- this.base = base;
52
- return this;
53
- }
54
- setFlags(flags) {
55
- this.flags = flags || '';
56
- return this;
57
- }
58
- toStr(x) {
59
- var s = x.toNT();
60
- if (x.termType === 'Graph') {
61
- this.formulas[s] = x; // remember as reverse does not work
55
+ _createClass(Serializer, [{
56
+ key: "setBase",
57
+ value: function setBase(base) {
58
+ this.base = base;
59
+ return this;
62
60
  }
63
-
64
- return s;
65
- }
66
- fromStr(s) {
67
- if (s[0] === '{') {
68
- var x = this.formulas[s];
69
- if (!x) console.log('No formula object for ' + s);
70
- return x;
61
+ }, {
62
+ key: "setFlags",
63
+ value: function setFlags(flags) {
64
+ this.flags = flags || '';
65
+ return this;
71
66
  }
72
- return this.store.fromNT(s);
73
- }
67
+ }, {
68
+ key: "toStr",
69
+ value: function toStr(x) {
70
+ var s = x.toNT();
71
+ if (x.termType === 'Graph') {
72
+ this.formulas[s] = x; // remember as reverse does not work
73
+ }
74
74
 
75
- /**
76
- * Defines a set of [prefix, namespace] pairs to be used by this Serializer instance.
77
- * Overrides previous prefixes if any
78
- * @param namespaces
79
- * @return {Serializer}
80
- */
81
- setNamespaces(namespaces) {
82
- for (var px in namespaces) {
83
- this.setPrefix(px, namespaces[px]);
75
+ return s;
84
76
  }
85
- return this;
86
- }
87
-
88
- /**
89
- * Defines a namespace prefix, overriding any existing prefix for that URI
90
- * @param prefix
91
- * @param uri
92
- */
93
- setPrefix(prefix, uri) {
94
- if (prefix.slice(0, 7) === 'default') return; // Try to weed these out
95
- if (prefix.slice(0, 2) === 'ns') return; // From others inferior algos
96
- if (!prefix || !uri) return; // empty strings not suitable
97
-
98
- // remove any existing prefix targeting this uri
99
- // for (let existingPrefix in this.namespaces) {
100
- // if (this.namespaces[existingPrefix] == uri)
101
- // delete this.namespaces[existingPrefix];
102
- // }
103
-
104
- // remove any existing mapping for this prefix
105
- for (let existingNs in this.prefixes) {
106
- if (this.prefixes[existingNs] == prefix) delete this.prefixes[existingNs];
77
+ }, {
78
+ key: "fromStr",
79
+ value: function fromStr(s) {
80
+ if (s[0] === '{') {
81
+ var x = this.formulas[s];
82
+ if (!x) console.log('No formula object for ' + s);
83
+ return x;
84
+ }
85
+ return this.store.fromNT(s);
107
86
  }
108
- this.prefixes[uri] = prefix;
109
- this.namespaces[prefix] = uri;
110
- }
111
-
112
- /* Accumulate Namespaces
113
- **
114
- ** These are only hints. If two overlap, only one gets used
115
- ** There is therefore no guarantee in general.
116
- */
117
- suggestPrefix(prefix, uri) {
118
- if (prefix.slice(0, 7) === 'default') return; // Try to weed these out
119
- if (prefix.slice(0, 2) === 'ns') return; // From others inferior algos
120
- if (!prefix || !uri) return; // empty strings not suitable
121
- if (prefix in this.namespaces || uri in this.prefixes) return; // already used
122
- this.prefixes[uri] = prefix;
123
- this.namespaces[prefix] = uri;
124
- }
125
87
 
126
- // Takes a namespace -> prefix map
127
- suggestNamespaces(namespaces) {
128
- for (var px in namespaces) {
129
- this.suggestPrefix(px, namespaces[px]);
130
- }
131
- return this;
132
- }
133
- checkIntegrity() {
134
- var p, ns;
135
- for (p in this.namespaces) {
136
- if (this.prefixes[this.namespaces[p]] !== p) {
137
- throw new Error('Serializer integity error 1: ' + p + ', ' + this.namespaces[p] + ', ' + this.prefixes[this.namespaces[p]] + '!');
88
+ /**
89
+ * Defines a set of [prefix, namespace] pairs to be used by this Serializer instance.
90
+ * Overrides previous prefixes if any
91
+ * @param namespaces
92
+ * @return {Serializer}
93
+ */
94
+ }, {
95
+ key: "setNamespaces",
96
+ value: function setNamespaces(namespaces) {
97
+ for (var px in namespaces) {
98
+ this.setPrefix(px, namespaces[px]);
138
99
  }
100
+ return this;
139
101
  }
140
- for (ns in this.prefixes) {
141
- if (this.namespaces[this.prefixes[ns]] !== ns) {
142
- throw new Error('Serializer integity error 2: ' + ns + ', ' + this.prefixs[ns] + ', ' + this.namespaces[this.prefixes[ns]] + '!');
102
+
103
+ /**
104
+ * Defines a namespace prefix, overriding any existing prefix for that URI
105
+ * @param prefix
106
+ * @param uri
107
+ */
108
+ }, {
109
+ key: "setPrefix",
110
+ value: function setPrefix(prefix, uri) {
111
+ if (prefix.slice(0, 7) === 'default') return; // Try to weed these out
112
+ if (prefix.slice(0, 2) === 'ns') return; // From others inferior algos
113
+ if (!prefix || !uri) return; // empty strings not suitable
114
+
115
+ // remove any existing prefix targeting this uri
116
+ // for (let existingPrefix in this.namespaces) {
117
+ // if (this.namespaces[existingPrefix] == uri)
118
+ // delete this.namespaces[existingPrefix];
119
+ // }
120
+
121
+ // remove any existing mapping for this prefix
122
+ for (var existingNs in this.prefixes) {
123
+ if (this.prefixes[existingNs] == prefix) delete this.prefixes[existingNs];
143
124
  }
125
+ this.prefixes[uri] = prefix;
126
+ this.namespaces[prefix] = uri;
144
127
  }
145
- }
146
128
 
147
- // Make up an unused prefix for a random namespace
148
- makeUpPrefix(uri) {
149
- var p = uri;
150
- function canUseMethod(pp) {
151
- if (!this.validPrefix.test(pp)) return false; // bad format
152
- if (pp === 'ns') return false; // boring
153
- if (pp in this.namespaces) return false; // already used
154
- this.prefixes[uri] = pp;
155
- this.namespaces[pp] = uri;
156
- return pp;
129
+ /* Accumulate Namespaces
130
+ **
131
+ ** These are only hints. If two overlap, only one gets used
132
+ ** There is therefore no guarantee in general.
133
+ */
134
+ }, {
135
+ key: "suggestPrefix",
136
+ value: function suggestPrefix(prefix, uri) {
137
+ if (prefix.slice(0, 7) === 'default') return; // Try to weed these out
138
+ if (prefix.slice(0, 2) === 'ns') return; // From others inferior algos
139
+ if (!prefix || !uri) return; // empty strings not suitable
140
+ if (prefix in this.namespaces || uri in this.prefixes) return; // already used
141
+ this.prefixes[uri] = prefix;
142
+ this.namespaces[prefix] = uri;
157
143
  }
158
- var canUse = canUseMethod.bind(this);
159
- if ('#/'.indexOf(p[p.length - 1]) >= 0) p = p.slice(0, -1);
160
- var slash = p.lastIndexOf('/');
161
- if (slash >= 0) p = p.slice(slash + 1);
162
- var i = 0;
163
- while (i < p.length) {
164
- if (this.prefixchars.indexOf(p[i])) {
165
- i++;
166
- } else {
167
- break;
144
+
145
+ // Takes a namespace -> prefix map
146
+ }, {
147
+ key: "suggestNamespaces",
148
+ value: function suggestNamespaces(namespaces) {
149
+ for (var px in namespaces) {
150
+ this.suggestPrefix(px, namespaces[px]);
168
151
  }
152
+ return this;
169
153
  }
170
- p = p.slice(0, i);
171
- if (p.length < 6 && canUse(p)) return p; // exact is best
172
- if (canUse(p.slice(0, 3))) return p.slice(0, 3);
173
- if (canUse(p.slice(0, 2))) return p.slice(0, 2);
174
- if (canUse(p.slice(0, 4))) return p.slice(0, 4);
175
- if (canUse(p.slice(0, 1))) return p.slice(0, 1);
176
- if (canUse(p.slice(0, 5))) return p.slice(0, 5);
177
- if (!this.validPrefix.test(p)) {
178
- p = 'n'; // Otherwise the loop below may never termimnate
154
+ }, {
155
+ key: "checkIntegrity",
156
+ value: function checkIntegrity() {
157
+ var p, ns;
158
+ for (p in this.namespaces) {
159
+ if (this.prefixes[this.namespaces[p]] !== p) {
160
+ throw new Error('Serializer integity error 1: ' + p + ', ' + this.namespaces[p] + ', ' + this.prefixes[this.namespaces[p]] + '!');
161
+ }
162
+ }
163
+ for (ns in this.prefixes) {
164
+ if (this.namespaces[this.prefixes[ns]] !== ns) {
165
+ throw new Error('Serializer integity error 2: ' + ns + ', ' + this.prefixs[ns] + ', ' + this.namespaces[this.prefixes[ns]] + '!');
166
+ }
167
+ }
179
168
  }
180
169
 
181
- for (var j = 0;; j++) if (canUse(p.slice(0, 3) + j)) return p.slice(0, 3) + j;
182
- }
183
- rootSubjects(sts) {
184
- var incoming = {};
185
- var subjects = {};
186
- var allBnodes = {};
187
-
188
- /* This scan is to find out which nodes will have to be the roots of trees
189
- ** in the serialized form. This will be any symbols, and any bnodes
190
- ** which hve more or less than one incoming arc, and any bnodes which have
191
- ** one incoming arc but it is an uninterrupted loop of such nodes back to itself.
192
- ** This should be kept linear time with repect to the number of statements.
193
- ** Note it does not use any indexing of the store.
194
- */
195
- for (var i = 0; i < sts.length; i++) {
196
- var st = sts[i];
197
- var checkMentions = function (x) {
198
- if (!incoming.hasOwnProperty(x)) incoming[x] = [];
199
- incoming[x].push(st.subject); // List of things which will cause this to be printed
200
- };
201
-
202
- var st2 = [st.subject, st.predicate, st.object];
203
- st2.map(function (y) {
204
- if (y.termType === 'BlankNode') {
205
- allBnodes[y.toNT()] = true;
206
- } else if (y.termType === 'Collection') {
207
- y.elements.forEach(function (z) {
208
- checkMentions(z); // bnodes in collections important
209
- });
170
+ // Make up an unused prefix for a random namespace
171
+ }, {
172
+ key: "makeUpPrefix",
173
+ value: function makeUpPrefix(uri) {
174
+ var p = uri;
175
+ function canUseMethod(pp) {
176
+ if (!this.validPrefix.test(pp)) return false; // bad format
177
+ if (pp === 'ns') return false; // boring
178
+ if (pp in this.namespaces) return false; // already used
179
+ this.prefixes[uri] = pp;
180
+ this.namespaces[pp] = uri;
181
+ return pp;
182
+ }
183
+ var canUse = canUseMethod.bind(this);
184
+ if ('#/'.indexOf(p[p.length - 1]) >= 0) p = p.slice(0, -1);
185
+ var slash = p.lastIndexOf('/');
186
+ if (slash >= 0) p = p.slice(slash + 1);
187
+ var i = 0;
188
+ while (i < p.length) {
189
+ if (this.prefixchars.indexOf(p[i])) {
190
+ i++;
191
+ } else {
192
+ break;
210
193
  }
211
- });
194
+ }
195
+ p = p.slice(0, i);
196
+ if (p.length < 6 && canUse(p)) return p; // exact is best
197
+ if (canUse(p.slice(0, 3))) return p.slice(0, 3);
198
+ if (canUse(p.slice(0, 2))) return p.slice(0, 2);
199
+ if (canUse(p.slice(0, 4))) return p.slice(0, 4);
200
+ if (canUse(p.slice(0, 1))) return p.slice(0, 1);
201
+ if (canUse(p.slice(0, 5))) return p.slice(0, 5);
202
+ if (!this.validPrefix.test(p)) {
203
+ p = 'n'; // Otherwise the loop below may never termimnate
204
+ }
212
205
 
213
- checkMentions(sts[i].object);
214
- var ss = subjects[this.toStr(st.subject)]; // Statements with this as subject
215
- if (!ss) ss = [];
216
- ss.push(st);
217
- subjects[this.toStr(st.subject)] = ss; // Make hash. @@ too slow for formula?
206
+ for (var j = 0;; j++) if (canUse(p.slice(0, 3) + j)) return p.slice(0, 3) + j;
218
207
  }
208
+ }, {
209
+ key: "rootSubjects",
210
+ value: function rootSubjects(sts) {
211
+ var incoming = {};
212
+ var subjects = {};
213
+ var allBnodes = {};
219
214
 
220
- var roots = [];
221
- for (var xNT in subjects) {
222
- if (!subjects.hasOwnProperty(xNT)) continue;
223
- var y = this.fromStr(xNT);
224
- if (y.termType !== 'BlankNode' || !incoming[y] || incoming[y].length !== 1) {
225
- roots.push(y);
226
- continue;
227
- }
228
- }
229
- this.incoming = incoming; // Keep for serializing @@ Bug for nested formulas
215
+ /* This scan is to find out which nodes will have to be the roots of trees
216
+ ** in the serialized form. This will be any symbols, and any bnodes
217
+ ** which hve more or less than one incoming arc, and any bnodes which have
218
+ ** one incoming arc but it is an uninterrupted loop of such nodes back to itself.
219
+ ** This should be kept linear time with repect to the number of statements.
220
+ ** Note it does not use any indexing of the store.
221
+ */
222
+ for (var i = 0; i < sts.length; i++) {
223
+ var st = sts[i];
224
+ var checkMentions = function checkMentions(x) {
225
+ if (!incoming.hasOwnProperty(x)) incoming[x] = [];
226
+ incoming[x].push(st.subject); // List of things which will cause this to be printed
227
+ };
230
228
 
231
- // Now do the scan using existing roots
232
- var rootsHash = {};
233
- for (var k = 0; k < roots.length; k++) {
234
- rootsHash[roots[k].toNT()] = true;
235
- }
236
- return {
237
- 'roots': roots,
238
- 'subjects': subjects,
239
- 'rootsHash': rootsHash,
240
- 'incoming': incoming
241
- };
242
- }
229
+ var st2 = [st.subject, st.predicate, st.object];
230
+ st2.map(function (y) {
231
+ if (y.termType === 'BlankNode') {
232
+ allBnodes[y.toNT()] = true;
233
+ } else if (y.termType === 'Collection') {
234
+ y.elements.forEach(function (z) {
235
+ checkMentions(z); // bnodes in collections important
236
+ });
237
+ }
238
+ });
243
239
 
244
- // //////////////////////////////////////////////////////
240
+ checkMentions(sts[i].object);
241
+ var ss = subjects[this.toStr(st.subject)]; // Statements with this as subject
242
+ if (!ss) ss = [];
243
+ ss.push(st);
244
+ subjects[this.toStr(st.subject)] = ss; // Make hash. @@ too slow for formula?
245
+ }
245
246
 
246
- toN3(f) {
247
- return this.statementsToN3(f.statements);
248
- }
249
- explicitURI(uri) {
250
- if (this.flags.indexOf('r') < 0 && this.base) {
251
- uri = Uri.refTo(this.base, uri);
252
- } else if (this.flags.indexOf('u') >= 0) {
253
- // Unicode encoding NTriples style
254
- uri = backslashUify(uri);
255
- } else {
256
- uri = hexify(uri);
257
- }
258
- return '<' + uri + '>';
259
- }
260
- statementsToNTriples(sts) {
261
- var sorted = sts.slice();
262
- sorted.sort();
263
- var str = '';
264
- var rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
265
- var self = this;
266
- var kb = this.store;
267
- var factory = this.rdfFactory;
268
- var termToNT = function (x) {
269
- if (x.termType !== 'Collection') {
270
- return self.atomicTermToN3(x);
271
- }
272
- var list = x.elements;
273
- var rest = kb.sym(rdfns + 'nill');
274
- for (var i = list.length - 1; i >= 0; i--) {
275
- var bnode = factory.blankNode();
276
- str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'first')) + ' ' + termToNT(list[i]) + '.\n';
277
- str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'rest')) + ' ' + termToNT(rest) + '.\n';
278
- rest = bnode;
279
- }
280
- return self.atomicTermToN3(rest);
281
- };
282
- for (var i = 0; i < sorted.length; i++) {
283
- var st = sorted[i];
284
- var s = '';
285
- s += termToNT(st.subject) + ' ';
286
- s += termToNT(st.predicate) + ' ';
287
- s += termToNT(st.object) + ' ';
288
- if (this.flags.indexOf('q') >= 0) {
289
- // Do quads not nrtiples
290
- s += termToNT(st.why) + ' ';
291
- }
292
- s += '.\n';
293
- str += s;
294
- }
295
- return str;
296
- }
297
- statementsToN3(sts) {
298
- var indent = 4;
299
- var width = 80;
300
- var kb = this.store;
301
- // A URI Map alows us to put the type statemnts at the top.
302
- var uriMap = {
303
- 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': 'aaa:00'
304
- };
305
- var SPO = function (x, y) {
306
- // Do limited canonicalization of bnodes
307
- return Util.heavyCompareSPO(x, y, kb, uriMap);
308
- };
309
- sts.sort(SPO);
310
- if (this.base && !this.defaultNamespace) {
311
- this.defaultNamespace = this.base + '#';
312
- }
313
- var predMap = {};
314
- if (this.flags.indexOf('s') < 0) {
315
- predMap['http://www.w3.org/2002/07/owl#sameAs'] = '=';
247
+ var roots = [];
248
+ for (var xNT in subjects) {
249
+ if (!subjects.hasOwnProperty(xNT)) continue;
250
+ var y = this.fromStr(xNT);
251
+ if (y.termType !== 'BlankNode' || !incoming[y] || incoming[y].length !== 1) {
252
+ roots.push(y);
253
+ continue;
254
+ }
255
+ }
256
+ this.incoming = incoming; // Keep for serializing @@ Bug for nested formulas
257
+
258
+ // Now do the scan using existing roots
259
+ var rootsHash = {};
260
+ for (var k = 0; k < roots.length; k++) {
261
+ rootsHash[roots[k].toNT()] = true;
262
+ }
263
+ return {
264
+ 'roots': roots,
265
+ 'subjects': subjects,
266
+ 'rootsHash': rootsHash,
267
+ 'incoming': incoming
268
+ };
316
269
  }
317
- if (this.flags.indexOf('t') < 0) {
318
- predMap['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] = 'a';
270
+
271
+ // //////////////////////////////////////////////////////
272
+ }, {
273
+ key: "toN3",
274
+ value: function toN3(f) {
275
+ return this.statementsToN3(f.statements);
319
276
  }
320
- if (this.flags.indexOf('i') < 0) {
321
- predMap['http://www.w3.org/2000/10/swap/log#implies'] = '=>';
277
+ }, {
278
+ key: "explicitURI",
279
+ value: function explicitURI(uri) {
280
+ if (this.flags.indexOf('r') < 0 && this.base) {
281
+ uri = Uri.refTo(this.base, uri);
282
+ } else if (this.flags.indexOf('u') >= 0) {
283
+ // Unicode encoding NTriples style
284
+ uri = backslashUify(uri);
285
+ } else {
286
+ uri = hexify(uri);
287
+ }
288
+ return '<' + uri + '>';
322
289
  }
323
- // //////////////////////// Arrange the bits of text
324
-
325
- var spaces = function (n) {
326
- var s = '';
327
- for (var i = 0; i < n; i++) s += ' ';
328
- return s;
329
- };
330
- var treeToLine = function (tree) {
290
+ }, {
291
+ key: "statementsToNTriples",
292
+ value: function statementsToNTriples(sts) {
293
+ var sorted = sts.slice();
294
+ sorted.sort();
331
295
  var str = '';
332
- for (var i = 0; i < tree.length; i++) {
333
- var branch = tree[i];
334
- var s2 = typeof branch === 'string' ? branch : treeToLine(branch);
335
- // Note the space before the dot in case statement ends with 123 or colon. which is in fact allowed but be conservative.
336
- if (i !== 0) {
337
- var ch = str.slice(-1) || ' ';
338
- if (s2 === ',' || s2 === ';') {
339
- // no gap
340
- } else if (s2 === '.' && !'0123456789.:'.includes(ch)) {// no gap except after number and colon
341
- // no gap
342
- } else {
343
- str += ' '; // separate from previous token
344
- }
296
+ var rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
297
+ var self = this;
298
+ var kb = this.store;
299
+ var factory = this.rdfFactory;
300
+ var termToNT = function termToNT(x) {
301
+ if (x.termType !== 'Collection') {
302
+ return self.atomicTermToN3(x);
345
303
  }
346
-
347
- str += s2;
304
+ var list = x.elements;
305
+ var rest = kb.sym(rdfns + 'nill');
306
+ for (var i = list.length - 1; i >= 0; i--) {
307
+ var bnode = factory.blankNode();
308
+ str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'first')) + ' ' + termToNT(list[i]) + '.\n';
309
+ str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'rest')) + ' ' + termToNT(rest) + '.\n';
310
+ rest = bnode;
311
+ }
312
+ return self.atomicTermToN3(rest);
313
+ };
314
+ for (var i = 0; i < sorted.length; i++) {
315
+ var st = sorted[i];
316
+ var s = '';
317
+ s += termToNT(st.subject) + ' ';
318
+ s += termToNT(st.predicate) + ' ';
319
+ s += termToNT(st.object) + ' ';
320
+ if (this.flags.indexOf('q') >= 0) {
321
+ // Do quads not nrtiples
322
+ s += termToNT(st.why) + ' ';
323
+ }
324
+ s += '.\n';
325
+ str += s;
348
326
  }
349
327
  return str;
350
- };
328
+ }
329
+ }, {
330
+ key: "statementsToN3",
331
+ value: function statementsToN3(sts) {
332
+ var indent = 4;
333
+ var width = 80;
334
+ var kb = this.store;
335
+ // A URI Map alows us to put the type statemnts at the top.
336
+ var uriMap = {
337
+ 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': 'aaa:00'
338
+ };
339
+ var SPO = function SPO(x, y) {
340
+ // Do limited canonicalization of bnodes
341
+ return Util.heavyCompareSPO(x, y, kb, uriMap);
342
+ };
343
+ sts.sort(SPO);
344
+ if (this.base && !this.defaultNamespace) {
345
+ this.defaultNamespace = this.base + '#';
346
+ }
347
+ var predMap = {};
348
+ if (this.flags.indexOf('s') < 0) {
349
+ predMap['http://www.w3.org/2002/07/owl#sameAs'] = '=';
350
+ }
351
+ if (this.flags.indexOf('t') < 0) {
352
+ predMap['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] = 'a';
353
+ }
354
+ if (this.flags.indexOf('i') < 0) {
355
+ predMap['http://www.w3.org/2000/10/swap/log#implies'] = '=>';
356
+ }
357
+ // //////////////////////// Arrange the bits of text
351
358
 
352
- // Convert a nested tree of lists and strings to a string
353
- var treeToString = function (tree, level) {
354
- var str = '';
355
- var lastLength = 100000;
356
- if (level === undefined) level = -1;
357
- for (var i = 0; i < tree.length; i++) {
358
- var branch = tree[i];
359
- if (typeof branch !== 'string') {
360
- var substr = treeToString(branch, level + 1);
361
- if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) {
362
- // Don't mess up multiline strings
363
- var line = treeToLine(branch);
364
- if (line.length < width - indent * level) {
365
- branch = line; // Note! treat as string below
366
- substr = '';
359
+ var spaces = function spaces(n) {
360
+ var s = '';
361
+ for (var i = 0; i < n; i++) s += ' ';
362
+ return s;
363
+ };
364
+ var treeToLine = function treeToLine(tree) {
365
+ var str = '';
366
+ for (var i = 0; i < tree.length; i++) {
367
+ var branch = tree[i];
368
+ var s2 = typeof branch === 'string' ? branch : treeToLine(branch);
369
+ // Note the space before the dot in case statement ends with 123 or colon. which is in fact allowed but be conservative.
370
+ if (i !== 0) {
371
+ var ch = str.slice(-1) || ' ';
372
+ if (s2 === ',' || s2 === ';') {
373
+ // no gap
374
+ } else if (s2 === '.' && !'0123456789.:'.includes(ch)) {// no gap except after number and colon
375
+ // no gap
376
+ } else {
377
+ str += ' '; // separate from previous token
367
378
  }
368
379
  }
369
- if (substr) lastLength = 10000;
370
- str += substr;
371
- }
372
- if (typeof branch === 'string') {
373
- if (branch.length === 1 && str.slice(-1) === '\n') {
374
- if (',.;'.indexOf(branch) >= 0) {
375
- str = str.slice(0, -1);
376
- // be conservative and ensure a whitespace between some chars and a final dot, as in treeToLine above
377
- if (branch == '.' && '0123456789.:'.includes(str.charAt(str.length - 1))) {
378
- str += ' ';
379
- lastLength += 1;
380
+
381
+ str += s2;
382
+ }
383
+ return str;
384
+ };
385
+
386
+ // Convert a nested tree of lists and strings to a string
387
+ var treeToString = function treeToString(tree, level) {
388
+ var str = '';
389
+ var lastLength = 100000;
390
+ if (level === undefined) level = -1;
391
+ for (var i = 0; i < tree.length; i++) {
392
+ var branch = tree[i];
393
+ if (typeof branch !== 'string') {
394
+ var substr = treeToString(branch, level + 1);
395
+ if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) {
396
+ // Don't mess up multiline strings
397
+ var line = treeToLine(branch);
398
+ if (line.length < width - indent * level) {
399
+ branch = line; // Note! treat as string below
400
+ substr = '';
380
401
  }
381
- str += branch + '\n'; // slip punct'n on end
382
- lastLength += 1;
383
- continue;
384
402
  }
403
+ if (substr) lastLength = 10000;
404
+ str += substr;
385
405
  }
386
- if (lastLength < indent * level + 4 ||
387
- // if new line not necessary
388
- lastLength + branch.length + 1 < width && ';.'.indexOf(str[str.length - 2]) < 0) {
389
- // or the string fits on last line
390
- str = str.slice(0, -1) + ' ' + branch + '\n'; // then continue on this line
391
- lastLength += branch.length + 1;
392
- } else {
393
- let line = spaces(indent * level) + branch;
394
- str += line + '\n';
395
- lastLength = line.length;
396
- if (level < 0) {
397
- str += '\n'; // extra blank line
398
- lastLength = 100000; // don't touch
406
+ if (typeof branch === 'string') {
407
+ if (branch.length === 1 && str.slice(-1) === '\n') {
408
+ if (',.;'.indexOf(branch) >= 0) {
409
+ str = str.slice(0, -1);
410
+ // be conservative and ensure a whitespace between some chars and a final dot, as in treeToLine above
411
+ if (branch == '.' && '0123456789.:'.includes(str.charAt(str.length - 1))) {
412
+ str += ' ';
413
+ lastLength += 1;
414
+ }
415
+ str += branch + '\n'; // slip punct'n on end
416
+ lastLength += 1;
417
+ continue;
418
+ }
419
+ }
420
+ if (lastLength < indent * level + 4 ||
421
+ // if new line not necessary
422
+ lastLength + branch.length + 1 < width && ';.'.indexOf(str[str.length - 2]) < 0) {
423
+ // or the string fits on last line
424
+ str = str.slice(0, -1) + ' ' + branch + '\n'; // then continue on this line
425
+ lastLength += branch.length + 1;
426
+ } else {
427
+ var _line = spaces(indent * level) + branch;
428
+ str += _line + '\n';
429
+ lastLength = _line.length;
430
+ if (level < 0) {
431
+ str += '\n'; // extra blank line
432
+ lastLength = 100000; // don't touch
433
+ }
399
434
  }
400
435
  }
401
436
  }
402
- }
403
437
 
404
- return str;
405
- };
406
-
407
- // //////////////////////////////////////////// Structure for N3
408
- // Convert a set of statements into a nested tree of lists and strings
409
- function statementListToTreeMethod(statements) {
410
- var stats = this.rootSubjects(statements);
411
- var roots = stats.roots;
412
- var results = [];
413
- for (var i = 0; i < roots.length; i++) {
414
- var root = roots[i];
415
- results.push(subjectTree(root, stats));
416
- }
417
- return results;
418
- }
419
- var statementListToTree = statementListToTreeMethod.bind(this);
438
+ return str;
439
+ };
420
440
 
421
- // The tree for a subject
422
- function subjectTree(subject, stats) {
423
- if (subject.termType === 'BlankNode' && !stats.incoming[subject]) {
424
- return objectTree(subject, stats, true).concat(['.']); // Anonymous bnode subject
441
+ // //////////////////////////////////////////// Structure for N3
442
+ // Convert a set of statements into a nested tree of lists and strings
443
+ function statementListToTreeMethod(statements) {
444
+ var stats = this.rootSubjects(statements);
445
+ var roots = stats.roots;
446
+ var results = [];
447
+ for (var i = 0; i < roots.length; i++) {
448
+ var root = roots[i];
449
+ results.push(subjectTree(root, stats));
450
+ }
451
+ return results;
425
452
  }
453
+ var statementListToTree = statementListToTreeMethod.bind(this);
426
454
 
427
- return [termToN3(subject, stats)].concat([propertyTree(subject, stats)]).concat(['.']);
428
- }
429
- // The property tree for a single subject or anonymous node
430
- function propertyTreeMethod(subject, stats) {
431
- var results = [];
432
- var lastPred = null;
433
- var sts = stats.subjects[this.toStr(subject)] || []; // relevant statements
434
- if (typeof sts === 'undefined') {
435
- throw new Error('Cant find statements for ' + subject);
436
- }
437
- var objects = [];
438
- for (var i = 0; i < sts.length; i++) {
439
- var st = sts[i];
440
- if (st.predicate.uri === lastPred) {
441
- objects.push(',');
442
- } else {
443
- if (lastPred) {
444
- results = results.concat([objects]).concat([';']);
445
- objects = [];
446
- }
447
- results.push(predMap[st.predicate.uri] ? predMap[st.predicate.uri] : termToN3(st.predicate, stats));
455
+ // The tree for a subject
456
+ function subjectTree(subject, stats) {
457
+ if (subject.termType === 'BlankNode' && !stats.incoming[subject]) {
458
+ return objectTree(subject, stats, true).concat(['.']); // Anonymous bnode subject
448
459
  }
449
- lastPred = st.predicate.uri;
450
- objects.push(objectTree(st.object, stats));
460
+
461
+ return [termToN3(subject, stats)].concat([propertyTree(subject, stats)]).concat(['.']);
451
462
  }
452
- results = results.concat([objects]);
453
- return results;
454
- }
455
- var propertyTree = propertyTreeMethod.bind(this);
456
- function objectTreeMethod(obj, stats, force) {
457
- if (obj.termType === 'BlankNode' && (force || stats.rootsHash[obj.toNT()] === undefined)) {
458
- // if not a root
459
- if (stats.subjects[this.toStr(obj)]) {
460
- return ['[', propertyTree(obj, stats), ']'];
461
- } else {
462
- return '[]';
463
+ // The property tree for a single subject or anonymous node
464
+ function propertyTreeMethod(subject, stats) {
465
+ var results = [];
466
+ var lastPred = null;
467
+ var sts = stats.subjects[this.toStr(subject)] || []; // relevant statements
468
+ if (typeof sts === 'undefined') {
469
+ throw new Error('Cant find statements for ' + subject);
463
470
  }
471
+ var objects = [];
472
+ for (var i = 0; i < sts.length; i++) {
473
+ var st = sts[i];
474
+ if (st.predicate.uri === lastPred) {
475
+ objects.push(',');
476
+ } else {
477
+ if (lastPred) {
478
+ results = results.concat([objects]).concat([';']);
479
+ objects = [];
480
+ }
481
+ results.push(predMap[st.predicate.uri] ? predMap[st.predicate.uri] : termToN3(st.predicate, stats));
482
+ }
483
+ lastPred = st.predicate.uri;
484
+ objects.push(objectTree(st.object, stats));
485
+ }
486
+ results = results.concat([objects]);
487
+ return results;
464
488
  }
465
- return termToN3(obj, stats);
466
- }
467
- var objectTree = objectTreeMethod.bind(this);
468
- function termToN3Method(expr, stats) {
469
- //
470
- var i, res;
471
- switch (expr.termType) {
472
- case 'Graph':
473
- res = ['{'];
474
- res = res.concat(statementListToTree(expr.statements));
475
- return res.concat(['}']);
476
- case 'Collection':
477
- res = ['('];
478
- for (i = 0; i < expr.elements.length; i++) {
479
- res.push([objectTree(expr.elements[i], stats)]);
489
+ var propertyTree = propertyTreeMethod.bind(this);
490
+ function objectTreeMethod(obj, stats, force) {
491
+ if (obj.termType === 'BlankNode' && (force || stats.rootsHash[obj.toNT()] === undefined)) {
492
+ // if not a root
493
+ if (stats.subjects[this.toStr(obj)]) {
494
+ return ['[', propertyTree(obj, stats), ']'];
495
+ } else {
496
+ return '[]';
480
497
  }
481
- res.push(')');
482
- return res;
483
- default:
484
- return this.atomicTermToN3(expr);
498
+ }
499
+ return termToN3(obj, stats);
485
500
  }
486
- }
487
- Serializer.prototype.termToN3 = termToN3;
488
- var termToN3 = termToN3Method.bind(this);
489
- function prefixDirectivesMethod() {
490
- var str = '';
491
- if (this.defaultNamespace) {
492
- str += '@prefix : ' + this.explicitURI(this.defaultNamespace) + '.\n';
501
+ var objectTree = objectTreeMethod.bind(this);
502
+ function termToN3Method(expr, stats) {
503
+ //
504
+ var i, res;
505
+ switch (expr.termType) {
506
+ case 'Graph':
507
+ res = ['{'];
508
+ res = res.concat(statementListToTree(expr.statements));
509
+ return res.concat(['}']);
510
+ case 'Collection':
511
+ res = ['('];
512
+ for (i = 0; i < expr.elements.length; i++) {
513
+ res.push([objectTree(expr.elements[i], stats)]);
514
+ }
515
+ res.push(')');
516
+ return res;
517
+ default:
518
+ return this.atomicTermToN3(expr);
519
+ }
493
520
  }
494
- for (var ns in this.prefixes) {
495
- if (!this.prefixes.hasOwnProperty(ns)) continue;
496
- if (!this.namespacesUsed[ns]) continue;
497
- str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) + '.\n';
521
+ Serializer.prototype.termToN3 = termToN3;
522
+ var termToN3 = termToN3Method.bind(this);
523
+ function prefixDirectivesMethod() {
524
+ var str = '';
525
+ if (this.defaultNamespace) {
526
+ str += '@prefix : ' + this.explicitURI(this.defaultNamespace) + '.\n';
527
+ }
528
+ for (var ns in this.prefixes) {
529
+ if (!this.prefixes.hasOwnProperty(ns)) continue;
530
+ if (!this.namespacesUsed[ns]) continue;
531
+ str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) + '.\n';
532
+ }
533
+ return str + '\n';
498
534
  }
499
- return str + '\n';
535
+ var prefixDirectives = prefixDirectivesMethod.bind(this);
536
+ // Body of statementsToN3:
537
+ var tree = statementListToTree(sts);
538
+ return prefixDirectives() + treeToString(tree);
500
539
  }
501
- var prefixDirectives = prefixDirectivesMethod.bind(this);
502
- // Body of statementsToN3:
503
- var tree = statementListToTree(sts);
504
- return prefixDirectives() + treeToString(tree);
505
- }
506
- // //////////////////////////////////////////// Atomic Terms
507
-
508
- // Deal with term level things and nesting with no bnode structure
509
- atomicTermToN3(expr, stats) {
510
- switch (expr.termType) {
511
- case 'BlankNode':
512
- case 'Variable':
513
- return expr.toNT();
514
- case 'Literal':
515
- var val = expr.value;
516
- if (typeof val !== 'string') {
517
- throw new TypeError('Value of RDF literal node must be a string');
518
- }
519
- // var val = expr.value.toString() // should be a string already
520
- if (expr.datatype && this.flags.indexOf('x') < 0) {
521
- // Supress native numbers
522
- switch (expr.datatype.uri) {
523
- case 'http://www.w3.org/2001/XMLSchema#integer':
524
- return val;
525
- case 'http://www.w3.org/2001/XMLSchema#decimal':
526
- // In Turtle, must have dot
527
- if (val.indexOf('.') < 0) val += '.0';
528
- return val;
529
- case 'http://www.w3.org/2001/XMLSchema#double':
530
- {
531
- // Must force use of 'e'
532
- const eNotation = val.toLowerCase().indexOf('e') > 0;
533
- if (val.indexOf('.') < 0 && !eNotation) val += '.0';
534
- if (!eNotation) val += 'e0';
540
+ // //////////////////////////////////////////// Atomic Terms
541
+
542
+ // Deal with term level things and nesting with no bnode structure
543
+ }, {
544
+ key: "atomicTermToN3",
545
+ value: function atomicTermToN3(expr, stats) {
546
+ switch (expr.termType) {
547
+ case 'BlankNode':
548
+ case 'Variable':
549
+ return expr.toNT();
550
+ case 'Literal':
551
+ var val = expr.value;
552
+ if (typeof val !== 'string') {
553
+ throw new TypeError('Value of RDF literal node must be a string');
554
+ }
555
+ // var val = expr.value.toString() // should be a string already
556
+ if (expr.datatype && this.flags.indexOf('x') < 0) {
557
+ // Supress native numbers
558
+ switch (expr.datatype.uri) {
559
+ case 'http://www.w3.org/2001/XMLSchema#integer':
535
560
  return val;
536
- }
537
- case 'http://www.w3.org/2001/XMLSchema#boolean':
538
- return expr.value === '1' ? 'true' : 'false';
561
+ case 'http://www.w3.org/2001/XMLSchema#decimal':
562
+ // In Turtle, must have dot
563
+ if (val.indexOf('.') < 0) val += '.0';
564
+ return val;
565
+ case 'http://www.w3.org/2001/XMLSchema#double':
566
+ {
567
+ // Must force use of 'e'
568
+ var eNotation = val.toLowerCase().indexOf('e') > 0;
569
+ if (val.indexOf('.') < 0 && !eNotation) val += '.0';
570
+ if (!eNotation) val += 'e0';
571
+ return val;
572
+ }
573
+ case 'http://www.w3.org/2001/XMLSchema#boolean':
574
+ return expr.value === '1' ? 'true' : 'false';
575
+ }
539
576
  }
540
- }
541
- var str = this.stringToN3(expr.value);
542
- if (expr.language) {
543
- str += '@' + expr.language;
544
- } else if (!expr.datatype.equals(this.xsd.string)) {
545
- str += '^^' + this.atomicTermToN3(expr.datatype, stats);
546
- }
547
- return str;
548
- case 'NamedNode':
549
- return this.symbolToN3(expr);
550
- case 'DefaultGraph':
551
- return '';
552
- default:
553
- throw new Error('Internal: atomicTermToN3 cannot handle ' + expr + ' of termType: ' + expr.termType);
577
+ var str = this.stringToN3(expr.value);
578
+ if (expr.language) {
579
+ str += '@' + expr.language;
580
+ } else if (!expr.datatype.equals(this.xsd.string)) {
581
+ str += '^^' + this.atomicTermToN3(expr.datatype, stats);
582
+ }
583
+ return str;
584
+ case 'NamedNode':
585
+ return this.symbolToN3(expr);
586
+ case 'DefaultGraph':
587
+ return '';
588
+ default:
589
+ throw new Error('Internal: atomicTermToN3 cannot handle ' + expr + ' of termType: ' + expr.termType);
590
+ }
554
591
  }
555
- }
556
592
 
557
- // stringToN3: String escaping for N3
558
-
559
- stringToN3(str, flags) {
560
- if (!flags) flags = 'e';
561
- var res = '';
562
- var i, j, k;
563
- var delim;
564
- var forbidden;
565
- if (str.length > 20 &&
566
- // Long enough to make sense
567
- str.slice(-1) !== '"' &&
568
- // corner case'
569
- flags.indexOf('n') < 0 && (
570
- // Force single line
571
- str.indexOf('\n') > 0 || str.indexOf('"') > 0)) {
572
- delim = '"""';
573
- forbidden = this.forbidden3;
574
- } else {
575
- delim = '"';
576
- forbidden = this.forbidden1;
577
- }
578
- for (i = 0; i < str.length;) {
579
- forbidden.lastIndex = 0;
580
- var m = forbidden.exec(str.slice(i));
581
- if (m == null) break;
582
- j = i + forbidden.lastIndex - 1;
583
- res += str.slice(i, j);
584
- var ch = str[j];
585
- if (ch === '"' && delim === '"""' && str.slice(j, j + 3) !== '"""') {
586
- res += ch;
593
+ // stringToN3: String escaping for N3
594
+ }, {
595
+ key: "stringToN3",
596
+ value: function stringToN3(str, flags) {
597
+ if (!flags) flags = 'e';
598
+ var res = '';
599
+ var i, j, k;
600
+ var delim;
601
+ var forbidden;
602
+ if (str.length > 20 &&
603
+ // Long enough to make sense
604
+ str.slice(-1) !== '"' &&
605
+ // corner case'
606
+ flags.indexOf('n') < 0 && (
607
+ // Force single line
608
+ str.indexOf('\n') > 0 || str.indexOf('"') > 0)) {
609
+ delim = '"""';
610
+ forbidden = this.forbidden3;
587
611
  } else {
588
- k = '\b\f\r\t\v\n\\"'.indexOf(ch); // No escaping of bell (7)?
589
- if (k >= 0) {
590
- res += '\\' + 'bfrtvn\\"'[k];
612
+ delim = '"';
613
+ forbidden = this.forbidden1;
614
+ }
615
+ for (i = 0; i < str.length;) {
616
+ forbidden.lastIndex = 0;
617
+ var m = forbidden.exec(str.slice(i));
618
+ if (m == null) break;
619
+ j = i + forbidden.lastIndex - 1;
620
+ res += str.slice(i, j);
621
+ var ch = str[j];
622
+ if (ch === '"' && delim === '"""' && str.slice(j, j + 3) !== '"""') {
623
+ res += ch;
591
624
  } else {
592
- if (flags.indexOf('e') >= 0) {
593
- // Unicode escaping in strings not unix style
594
- res += '\\u' + ('000' + ch.charCodeAt(0).toString(16).toLowerCase()).slice(-4);
625
+ k = '\b\f\r\t\v\n\\"'.indexOf(ch); // No escaping of bell (7)?
626
+ if (k >= 0) {
627
+ res += '\\' + 'bfrtvn\\"'[k];
595
628
  } else {
596
- // no 'e' flag
597
- res += ch;
629
+ if (flags.indexOf('e') >= 0) {
630
+ // Unicode escaping in strings not unix style
631
+ res += "\\u" + ('000' + ch.charCodeAt(0).toString(16).toLowerCase()).slice(-4);
632
+ } else {
633
+ // no 'e' flag
634
+ res += ch;
635
+ }
598
636
  }
599
637
  }
638
+ i = j + 1;
600
639
  }
601
- i = j + 1;
640
+ return delim + res + str.slice(i) + delim;
602
641
  }
603
- return delim + res + str.slice(i) + delim;
604
- }
605
- // A single symbol, either in <> or namespace notation
606
-
607
- symbolToN3(x) {
608
- // c.f. symbolString() in notation3.py
609
- var uri = x.uri;
610
- var j = uri.indexOf('#');
611
- if (j < 0 && this.flags.indexOf('/') < 0) {
612
- j = uri.lastIndexOf('/');
613
- }
614
- if (j >= 0 && this.flags.indexOf('p') < 0 && (
615
- // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?)
616
- uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) {
617
- var canSplit = true;
618
- for (var k = j + 1; k < uri.length; k++) {
619
- if (this._notNameChars.indexOf(uri[k]) >= 0) {
620
- canSplit = false;
621
- break;
622
- }
642
+ // A single symbol, either in <> or namespace notation
643
+ }, {
644
+ key: "symbolToN3",
645
+ value: function symbolToN3(x) {
646
+ // c.f. symbolString() in notation3.py
647
+ var uri = x.uri;
648
+ var j = uri.indexOf('#');
649
+ if (j < 0 && this.flags.indexOf('/') < 0) {
650
+ j = uri.lastIndexOf('/');
623
651
  }
624
- /*
625
- if (uri.slice(0, j + 1) === this.base + '#') { // base-relative
626
- if (canSplit) {
627
- return ':' + uri.slice(j + 1) // assume deafult ns is local
628
- } else {
629
- return '<#' + uri.slice(j + 1) + '>'
652
+ if (j >= 0 && this.flags.indexOf('p') < 0 && (
653
+ // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?)
654
+ uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) {
655
+ var canSplit = true;
656
+ for (var k = j + 1; k < uri.length; k++) {
657
+ if (this._notNameChars.indexOf(uri[k]) >= 0) {
658
+ canSplit = false;
659
+ break;
660
+ }
661
+ }
662
+ /*
663
+ if (uri.slice(0, j + 1) === this.base + '#') { // base-relative
664
+ if (canSplit) {
665
+ return ':' + uri.slice(j + 1) // assume deafult ns is local
666
+ } else {
667
+ return '<#' + uri.slice(j + 1) + '>'
668
+ }
630
669
  }
670
+ */
671
+ if (canSplit) {
672
+ var localid = uri.slice(j + 1);
673
+ var namesp = uri.slice(0, j + 1);
674
+ if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) {
675
+ // d -> suppress default
676
+ if (this.flags.indexOf('k') >= 0 && this.keyords.indexOf(localid) < 0) {
677
+ return localid;
631
678
  }
632
- */
633
- if (canSplit) {
634
- var localid = uri.slice(j + 1);
635
- var namesp = uri.slice(0, j + 1);
636
- if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) {
637
- // d -> suppress default
638
- if (this.flags.indexOf('k') >= 0 && this.keyords.indexOf(localid) < 0) {
639
- return localid;
679
+ return ':' + localid;
640
680
  }
641
- return ':' + localid;
642
- }
643
- // this.checkIntegrity() // @@@ Remove when not testing
644
- var prefix = this.prefixes[namesp];
645
- if (!prefix) prefix = this.makeUpPrefix(namesp);
646
- if (prefix) {
647
- this.namespacesUsed[namesp] = true;
648
- return prefix + ':' + localid;
681
+ // this.checkIntegrity() // @@@ Remove when not testing
682
+ var prefix = this.prefixes[namesp];
683
+ if (!prefix) prefix = this.makeUpPrefix(namesp);
684
+ if (prefix) {
685
+ this.namespacesUsed[namesp] = true;
686
+ return prefix + ':' + localid;
687
+ }
688
+ // Fall though if can't do qname
649
689
  }
650
- // Fall though if can't do qname
651
690
  }
652
- }
653
-
654
- return this.explicitURI(uri);
655
- }
656
691
 
657
- // /////////////////////////// Quad store serialization
692
+ return this.explicitURI(uri);
693
+ }
658
694
 
659
- // @para. write - a function taking a single string to be output
660
- //
661
- writeStore(write) {
662
- var kb = this.store;
663
- var fetcher = kb.fetcher;
664
- var session = fetcher && fetcher.appNode;
695
+ // /////////////////////////// Quad store serialization
665
696
 
666
- // The core data
697
+ // @para. write - a function taking a single string to be output
698
+ //
699
+ }, {
700
+ key: "writeStore",
701
+ value: function writeStore(write) {
702
+ var kb = this.store;
703
+ var fetcher = kb.fetcher;
704
+ var session = fetcher && fetcher.appNode;
667
705
 
668
- var sources = this.store.index[3];
669
- for (var s in sources) {
670
- // -> assume we can use -> as short for log:semantics
671
- var source = kb.fromNT(s);
672
- if (session && source.equals(session)) continue;
673
- write('\n' + this.atomicTermToN3(source) + ' ' + this.atomicTermToN3(kb.sym('http://www.w3.org/2000/10/swap/log#semantics')) + ' { ' + this.statementsToN3(kb.statementsMatching(undefined, undefined, undefined, source)) + ' }.\n');
674
- }
706
+ // The core data
675
707
 
676
- // The metadata from HTTP interactions:
708
+ var sources = this.store.index[3];
709
+ for (var s in sources) {
710
+ // -> assume we can use -> as short for log:semantics
711
+ var source = kb.fromNT(s);
712
+ if (session && source.equals(session)) continue;
713
+ write('\n' + this.atomicTermToN3(source) + ' ' + this.atomicTermToN3(kb.sym('http://www.w3.org/2000/10/swap/log#semantics')) + ' { ' + this.statementsToN3(kb.statementsMatching(undefined, undefined, undefined, source)) + ' }.\n');
714
+ }
677
715
 
678
- kb.statementsMatching(undefined, kb.sym('http://www.w3.org/2007/ont/link#requestedURI')).map(function (st) {
679
- write('\n<' + st.object.value + '> log:metadata {\n');
680
- var sts = kb.statementsMatching(undefined, undefined, undefined, st.subject);
681
- write(this.statementsToN3(this.statementsToN3(sts)));
682
- write('}.\n');
683
- });
716
+ // The metadata from HTTP interactions:
684
717
 
685
- // Inferences we have made ourselves not attributable to anyone else
718
+ kb.statementsMatching(undefined, kb.sym('http://www.w3.org/2007/ont/link#requestedURI')).map(function (st) {
719
+ write('\n<' + st.object.value + '> log:metadata {\n');
720
+ var sts = kb.statementsMatching(undefined, undefined, undefined, st.subject);
721
+ write(this.statementsToN3(this.statementsToN3(sts)));
722
+ write('}.\n');
723
+ });
686
724
 
687
- var metaSources = [];
688
- if (session) metaSources.push(session);
689
- var metadata = [];
690
- metaSources.map(function (source) {
691
- metadata = metadata.concat(kb.statementsMatching(undefined, undefined, undefined, source));
692
- });
693
- write(this.statementsToN3(metadata));
694
- }
725
+ // Inferences we have made ourselves not attributable to anyone else
695
726
 
696
- // ////////////////////////////////////////////// XML serialization
727
+ var metaSources = [];
728
+ if (session) metaSources.push(session);
729
+ var metadata = [];
730
+ metaSources.map(function (source) {
731
+ metadata = metadata.concat(kb.statementsMatching(undefined, undefined, undefined, source));
732
+ });
733
+ write(this.statementsToN3(metadata));
734
+ }
697
735
 
698
- statementsToXML(sts) {
699
- var indent = 4;
700
- var width = 80;
701
- var namespaceCounts = []; // which have been used
702
- namespaceCounts['http://www.w3.org/1999/02/22-rdf-syntax-ns#'] = true;
703
- var liPrefix = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#_'; // prefix for ordered list items
736
+ // ////////////////////////////////////////////// XML serialization
737
+ }, {
738
+ key: "statementsToXML",
739
+ value: function statementsToXML(sts) {
740
+ var indent = 4;
741
+ var width = 80;
742
+ var namespaceCounts = []; // which have been used
743
+ namespaceCounts['http://www.w3.org/1999/02/22-rdf-syntax-ns#'] = true;
744
+ var liPrefix = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#_'; // prefix for ordered list items
704
745
 
705
- // //////////////////////// Arrange the bits of XML text
746
+ // //////////////////////// Arrange the bits of XML text
706
747
 
707
- var spaces = function (n) {
708
- var s = '';
709
- for (var i = 0; i < n; i++) s += ' ';
710
- return s;
711
- };
712
- var XMLtreeToLine = function (tree) {
713
- var str = '';
714
- for (var i = 0; i < tree.length; i++) {
715
- var branch = tree[i];
716
- var s2 = typeof branch === 'string' ? branch : XMLtreeToLine(branch);
717
- str += s2;
718
- }
719
- return str;
720
- };
748
+ var spaces = function spaces(n) {
749
+ var s = '';
750
+ for (var i = 0; i < n; i++) s += ' ';
751
+ return s;
752
+ };
753
+ var XMLtreeToLine = function XMLtreeToLine(tree) {
754
+ var str = '';
755
+ for (var i = 0; i < tree.length; i++) {
756
+ var branch = tree[i];
757
+ var s2 = typeof branch === 'string' ? branch : XMLtreeToLine(branch);
758
+ str += s2;
759
+ }
760
+ return str;
761
+ };
721
762
 
722
- // Convert a nested tree of lists and strings to a string
723
- var XMLtreeToString = function (tree, level) {
724
- var str = '';
725
- var line;
726
- var lastLength = 100000;
727
- if (!level) level = 0;
728
- for (var i = 0; i < tree.length; i++) {
729
- var branch = tree[i];
730
- if (typeof branch !== 'string') {
731
- var substr = XMLtreeToString(branch, level + 1);
732
- if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) {
733
- // Don't mess up multiline strings
734
- line = XMLtreeToLine(branch);
735
- if (line.length < width - indent * level) {
736
- branch = ' ' + line; // @@ Hack: treat as string below
737
- substr = '';
763
+ // Convert a nested tree of lists and strings to a string
764
+ var XMLtreeToString = function XMLtreeToString(tree, level) {
765
+ var str = '';
766
+ var line;
767
+ var lastLength = 100000;
768
+ if (!level) level = 0;
769
+ for (var i = 0; i < tree.length; i++) {
770
+ var branch = tree[i];
771
+ if (typeof branch !== 'string') {
772
+ var substr = XMLtreeToString(branch, level + 1);
773
+ if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) {
774
+ // Don't mess up multiline strings
775
+ line = XMLtreeToLine(branch);
776
+ if (line.length < width - indent * level) {
777
+ branch = ' ' + line; // @@ Hack: treat as string below
778
+ substr = '';
779
+ }
738
780
  }
781
+ if (substr) lastLength = 10000;
782
+ str += substr;
739
783
  }
740
- if (substr) lastLength = 10000;
741
- str += substr;
742
- }
743
- if (typeof branch === 'string') {
744
- if (lastLength < indent * level + 4) {
745
- // continue
746
- str = str.slice(0, -1) + ' ' + branch + '\n';
747
- lastLength += branch.length + 1;
748
- } else {
749
- line = spaces(indent * level) + branch;
750
- str += line + '\n';
751
- lastLength = line.length;
784
+ if (typeof branch === 'string') {
785
+ if (lastLength < indent * level + 4) {
786
+ // continue
787
+ str = str.slice(0, -1) + ' ' + branch + '\n';
788
+ lastLength += branch.length + 1;
789
+ } else {
790
+ line = spaces(indent * level) + branch;
791
+ str += line + '\n';
792
+ lastLength = line.length;
793
+ }
794
+ } else {// not string
752
795
  }
753
- } else {// not string
754
796
  }
797
+ return str;
798
+ };
799
+ function statementListToXMLTreeMethod(statements) {
800
+ this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
801
+ var stats = this.rootSubjects(statements);
802
+ var roots = stats.roots;
803
+ var results = [];
804
+ for (var i = 0; i < roots.length; i++) {
805
+ var root = roots[i];
806
+ results.push(subjectXMLTree(root, stats));
807
+ }
808
+ return results;
755
809
  }
756
- return str;
757
- };
758
- function statementListToXMLTreeMethod(statements) {
759
- this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
760
- var stats = this.rootSubjects(statements);
761
- var roots = stats.roots;
762
- var results = [];
763
- for (var i = 0; i < roots.length; i++) {
764
- var root = roots[i];
765
- results.push(subjectXMLTree(root, stats));
766
- }
767
- return results;
768
- }
769
- var statementListToXMLTree = statementListToXMLTreeMethod.bind(this);
770
- function escapeForXML(str) {
771
- if (typeof str === 'undefined') return '@@@undefined@@@@';
772
- return str.replace(/[&<"]/g, function (m) {
773
- switch (m[0]) {
774
- case '&':
775
- return '&amp;';
776
- case '<':
777
- return '&lt;';
778
- case '"':
779
- return '&quot;';
780
- // '
810
+ var statementListToXMLTree = statementListToXMLTreeMethod.bind(this);
811
+ function escapeForXML(str) {
812
+ if (typeof str === 'undefined') return '@@@undefined@@@@';
813
+ return str.replace(/[&<"]/g, function (m) {
814
+ switch (m[0]) {
815
+ case '&':
816
+ return '&amp;';
817
+ case '<':
818
+ return '&lt;';
819
+ case '"':
820
+ return '&quot;';
821
+ // '
822
+ }
823
+ });
824
+ }
825
+
826
+ function relURIMethod(term) {
827
+ return escapeForXML(this.base ? Util.uri.refTo(this.base, term.uri) : term.uri);
828
+ }
829
+ var relURI = relURIMethod.bind(this);
830
+
831
+ // The tree for a subject
832
+ function subjectXMLTreeMethod(subject, stats) {
833
+ var results = [];
834
+ var type, t, st, pred;
835
+ var sts = stats.subjects[this.toStr(subject)]; // relevant statements
836
+ if (typeof sts === 'undefined') {
837
+ // empty bnode
838
+ return propertyXMLTree(subject, stats);
781
839
  }
782
- });
783
- }
784
840
 
785
- function relURIMethod(term) {
786
- return escapeForXML(this.base ? Util.uri.refTo(this.base, term.uri) : term.uri);
787
- }
788
- var relURI = relURIMethod.bind(this);
789
-
790
- // The tree for a subject
791
- function subjectXMLTreeMethod(subject, stats) {
792
- var results = [];
793
- var type, t, st, pred;
794
- var sts = stats.subjects[this.toStr(subject)]; // relevant statements
795
- if (typeof sts === 'undefined') {
796
- // empty bnode
797
- return propertyXMLTree(subject, stats);
798
- }
799
-
800
- // Sort only on the predicate, leave the order at object
801
- // level undisturbed. This leaves multilingual content in
802
- // the order of entry (for partner literals), which helps
803
- // readability.
804
- //
805
- // For the predicate sort, we attempt to split the uri
806
- // as a hint to the sequence
807
- sts.sort(function (a, b) {
808
- var ap = a.predicate.uri;
809
- var bp = b.predicate.uri;
810
- if (ap.substring(0, liPrefix.length) === liPrefix || bp.substring(0, liPrefix.length) === liPrefix) {
811
- // we're only interested in sorting list items
812
- return ap.localeCompare(bp);
813
- }
814
- var as = ap.substring(liPrefix.length);
815
- var bs = bp.substring(liPrefix.length);
816
- var an = parseInt(as, 10);
817
- var bn = parseInt(bs, 10);
818
- if (isNaN(an) || isNaN(bn) || an !== as || bn !== bs) {
819
- // we only care about integers
820
- return ap.localeCompare(bp);
821
- }
822
- return an - bn;
823
- });
824
- for (var i = 0; i < sts.length; i++) {
825
- st = sts[i];
826
- // look for a type
827
- if (st.predicate.uri === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && !type && st.object.termType === 'NamedNode') {
828
- type = st.object;
829
- continue; // don't include it as a child element
830
- }
831
-
832
- // see whether predicate can be replaced with "li"
833
- pred = st.predicate;
834
- if (pred.uri.substr(0, liPrefix.length) === liPrefix) {
835
- var number = pred.uri.substr(liPrefix.length);
836
- // make sure these are actually numeric list items
837
- var intNumber = parseInt(number, 10);
838
- if (number === intNumber.toString()) {
839
- // was numeric; don't need to worry about ordering since we've already
840
- // sorted the statements
841
- pred = this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#li');
841
+ // Sort only on the predicate, leave the order at object
842
+ // level undisturbed. This leaves multilingual content in
843
+ // the order of entry (for partner literals), which helps
844
+ // readability.
845
+ //
846
+ // For the predicate sort, we attempt to split the uri
847
+ // as a hint to the sequence
848
+ sts.sort(function (a, b) {
849
+ var ap = a.predicate.uri;
850
+ var bp = b.predicate.uri;
851
+ if (ap.substring(0, liPrefix.length) === liPrefix || bp.substring(0, liPrefix.length) === liPrefix) {
852
+ // we're only interested in sorting list items
853
+ return ap.localeCompare(bp);
842
854
  }
843
- }
844
- t = qname(pred);
845
- switch (st.object.termType) {
846
- case 'BlankNode':
847
- if (stats.incoming[st.object].length === 1) {
848
- // there should always be something in the incoming array for a bnode
849
- results = results.concat(['<' + t + ' rdf:parseType="Resource">', subjectXMLTree(st.object, stats), '</' + t + '>']);
850
- } else {
851
- results = results.concat(['<' + t + ' rdf:nodeID="' + st.object.toNT().slice(2) + '"/>']);
855
+ var as = ap.substring(liPrefix.length);
856
+ var bs = bp.substring(liPrefix.length);
857
+ var an = parseInt(as, 10);
858
+ var bn = parseInt(bs, 10);
859
+ if (isNaN(an) || isNaN(bn) || an !== as || bn !== bs) {
860
+ // we only care about integers
861
+ return ap.localeCompare(bp);
862
+ }
863
+ return an - bn;
864
+ });
865
+ for (var i = 0; i < sts.length; i++) {
866
+ st = sts[i];
867
+ // look for a type
868
+ if (st.predicate.uri === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && !type && st.object.termType === 'NamedNode') {
869
+ type = st.object;
870
+ continue; // don't include it as a child element
871
+ }
872
+
873
+ // see whether predicate can be replaced with "li"
874
+ pred = st.predicate;
875
+ if (pred.uri.substr(0, liPrefix.length) === liPrefix) {
876
+ var number = pred.uri.substr(liPrefix.length);
877
+ // make sure these are actually numeric list items
878
+ var intNumber = parseInt(number, 10);
879
+ if (number === intNumber.toString()) {
880
+ // was numeric; don't need to worry about ordering since we've already
881
+ // sorted the statements
882
+ pred = this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#li');
852
883
  }
853
- break;
854
- case 'NamedNode':
855
- results = results.concat(['<' + t + ' rdf:resource="' + relURI(st.object) + '"/>']);
856
- break;
857
- case 'Literal':
858
- results = results.concat(['<' + t + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.uri) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '</' + t + '>']);
859
- break;
860
- case 'Collection':
861
- results = results.concat(['<' + t + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '</' + t + '>']);
862
- break;
863
- default:
864
- throw new Error("Can't serialize object of type " + st.object.termType + ' into XML');
865
- } // switch
866
- }
884
+ }
885
+ t = qname(pred);
886
+ switch (st.object.termType) {
887
+ case 'BlankNode':
888
+ if (stats.incoming[st.object].length === 1) {
889
+ // there should always be something in the incoming array for a bnode
890
+ results = results.concat(['<' + t + ' rdf:parseType="Resource">', subjectXMLTree(st.object, stats), '</' + t + '>']);
891
+ } else {
892
+ results = results.concat(['<' + t + ' rdf:nodeID="' + st.object.toNT().slice(2) + '"/>']);
893
+ }
894
+ break;
895
+ case 'NamedNode':
896
+ results = results.concat(['<' + t + ' rdf:resource="' + relURI(st.object) + '"/>']);
897
+ break;
898
+ case 'Literal':
899
+ results = results.concat(['<' + t + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.uri) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '</' + t + '>']);
900
+ break;
901
+ case 'Collection':
902
+ results = results.concat(['<' + t + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '</' + t + '>']);
903
+ break;
904
+ default:
905
+ throw new Error("Can't serialize object of type " + st.object.termType + ' into XML');
906
+ } // switch
907
+ }
867
908
 
868
- var tag = type ? qname(type) : 'rdf:Description';
869
- var attrs = '';
870
- if (subject.termType === 'BlankNode') {
871
- if (!stats.incoming[subject] || stats.incoming[subject].length !== 1) {
872
- // not an anonymous bnode
873
- attrs = ' rdf:nodeID="' + subject.toNT().slice(2) + '"';
909
+ var tag = type ? qname(type) : 'rdf:Description';
910
+ var attrs = '';
911
+ if (subject.termType === 'BlankNode') {
912
+ if (!stats.incoming[subject] || stats.incoming[subject].length !== 1) {
913
+ // not an anonymous bnode
914
+ attrs = ' rdf:nodeID="' + subject.toNT().slice(2) + '"';
915
+ }
916
+ } else {
917
+ attrs = ' rdf:about="' + relURI(subject) + '"';
874
918
  }
875
- } else {
876
- attrs = ' rdf:about="' + relURI(subject) + '"';
919
+ return ['<' + tag + attrs + '>'].concat([results]).concat(['</' + tag + '>']);
877
920
  }
878
- return ['<' + tag + attrs + '>'].concat([results]).concat(['</' + tag + '>']);
879
- }
880
- var subjectXMLTree = subjectXMLTreeMethod.bind(this);
881
- function collectionXMLTree(subject, stats) {
882
- var res = [];
883
- for (var i = 0; i < subject.elements.length; i++) {
884
- res.push(subjectXMLTree(subject.elements[i], stats));
921
+ var subjectXMLTree = subjectXMLTreeMethod.bind(this);
922
+ function collectionXMLTree(subject, stats) {
923
+ var res = [];
924
+ for (var i = 0; i < subject.elements.length; i++) {
925
+ res.push(subjectXMLTree(subject.elements[i], stats));
926
+ }
927
+ return res;
885
928
  }
886
- return res;
887
- }
888
929
 
889
- // The property tree for a single subject or anonymos node
890
- function propertyXMLTreeMethod(subject, stats) {
891
- var results = [];
892
- var sts = stats.subjects[this.toStr(subject)]; // relevant statements
893
- if (!sts) return results; // No relevant statements
894
- sts.sort();
895
- for (var i = 0; i < sts.length; i++) {
896
- var st = sts[i];
897
- switch (st.object.termType) {
898
- case 'BlankNode':
899
- if (stats.rootsHash[st.object.toNT()]) {
900
- // This bnode has been done as a root -- no content here @@ what bout first time
901
- results = results.concat(['<' + qname(st.predicate) + ' rdf:nodeID="' + st.object.toNT().slice(2) + '">', '</' + qname(st.predicate) + '>']);
902
- } else {
903
- results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Resource">', propertyXMLTree(st.object, stats), '</' + qname(st.predicate) + '>']);
904
- }
905
- break;
906
- case 'NamedNode':
907
- results = results.concat(['<' + qname(st.predicate) + ' rdf:resource="' + relURI(st.object) + '"/>']);
908
- break;
909
- case 'Literal':
910
- results = results.concat(['<' + qname(st.predicate) + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.value) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '</' + qname(st.predicate) + '>']);
911
- break;
912
- case 'Collection':
913
- results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '</' + qname(st.predicate) + '>']);
914
- break;
915
- default:
916
- throw new Error("Can't serialize object of type " + st.object.termType + ' into XML');
917
- } // switch
918
- }
930
+ // The property tree for a single subject or anonymos node
931
+ function propertyXMLTreeMethod(subject, stats) {
932
+ var results = [];
933
+ var sts = stats.subjects[this.toStr(subject)]; // relevant statements
934
+ if (!sts) return results; // No relevant statements
935
+ sts.sort();
936
+ for (var i = 0; i < sts.length; i++) {
937
+ var st = sts[i];
938
+ switch (st.object.termType) {
939
+ case 'BlankNode':
940
+ if (stats.rootsHash[st.object.toNT()]) {
941
+ // This bnode has been done as a root -- no content here @@ what bout first time
942
+ results = results.concat(['<' + qname(st.predicate) + ' rdf:nodeID="' + st.object.toNT().slice(2) + '">', '</' + qname(st.predicate) + '>']);
943
+ } else {
944
+ results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Resource">', propertyXMLTree(st.object, stats), '</' + qname(st.predicate) + '>']);
945
+ }
946
+ break;
947
+ case 'NamedNode':
948
+ results = results.concat(['<' + qname(st.predicate) + ' rdf:resource="' + relURI(st.object) + '"/>']);
949
+ break;
950
+ case 'Literal':
951
+ results = results.concat(['<' + qname(st.predicate) + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.value) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '</' + qname(st.predicate) + '>']);
952
+ break;
953
+ case 'Collection':
954
+ results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '</' + qname(st.predicate) + '>']);
955
+ break;
956
+ default:
957
+ throw new Error("Can't serialize object of type " + st.object.termType + ' into XML');
958
+ } // switch
959
+ }
919
960
 
920
- return results;
921
- }
922
- var propertyXMLTree = propertyXMLTreeMethod.bind(this);
923
- function qnameMethod(term) {
924
- var uri = term.uri;
925
- var j = uri.indexOf('#');
926
- if (j < 0 && this.flags.indexOf('/') < 0) {
927
- j = uri.lastIndexOf('/');
961
+ return results;
928
962
  }
929
- if (j < 0) throw new Error('Cannot make qname out of <' + uri + '>');
930
- for (var k = j + 1; k < uri.length; k++) {
931
- if (this._notNameChars.indexOf(uri[k]) >= 0) {
932
- throw new Error('Invalid character "' + uri[k] + '" cannot be in XML qname for URI: ' + uri);
963
+ var propertyXMLTree = propertyXMLTreeMethod.bind(this);
964
+ function qnameMethod(term) {
965
+ var uri = term.uri;
966
+ var j = uri.indexOf('#');
967
+ if (j < 0 && this.flags.indexOf('/') < 0) {
968
+ j = uri.lastIndexOf('/');
933
969
  }
970
+ if (j < 0) throw new Error('Cannot make qname out of <' + uri + '>');
971
+ for (var k = j + 1; k < uri.length; k++) {
972
+ if (this._notNameChars.indexOf(uri[k]) >= 0) {
973
+ throw new Error('Invalid character "' + uri[k] + '" cannot be in XML qname for URI: ' + uri);
974
+ }
975
+ }
976
+ var localid = uri.slice(j + 1);
977
+ var namesp = uri.slice(0, j + 1);
978
+ if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) {
979
+ // d -> suppress default
980
+ return localid;
981
+ }
982
+ var prefix = this.prefixes[namesp];
983
+ if (!prefix) prefix = this.makeUpPrefix(namesp);
984
+ namespaceCounts[namesp] = true;
985
+ return prefix + ':' + localid;
934
986
  }
935
- var localid = uri.slice(j + 1);
936
- var namesp = uri.slice(0, j + 1);
937
- if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) {
938
- // d -> suppress default
939
- return localid;
940
- }
941
- var prefix = this.prefixes[namesp];
942
- if (!prefix) prefix = this.makeUpPrefix(namesp);
943
- namespaceCounts[namesp] = true;
944
- return prefix + ':' + localid;
945
- }
946
- var qname = qnameMethod.bind(this);
987
+ var qname = qnameMethod.bind(this);
947
988
 
948
- // Body of toXML:
989
+ // Body of toXML:
949
990
 
950
- var tree = statementListToXMLTree(sts);
951
- var str = '<rdf:RDF';
952
- if (this.defaultNamespace) {
953
- str += ' xmlns="' + escapeForXML(this.defaultNamespace) + '"';
954
- }
955
- for (var ns in namespaceCounts) {
956
- if (!namespaceCounts.hasOwnProperty(ns)) continue;
957
- // Rel uris in xml ns is not strictly allowed in the XMLNS spec but needed in practice often
958
- var ns2 = this.base && this.flags.includes('z') ? Util.uri.refTo(this.base, ns) : ns;
959
- str += '\n xmlns:' + this.prefixes[ns] + '="' + escapeForXML(ns2) + '"';
991
+ var tree = statementListToXMLTree(sts);
992
+ var str = '<rdf:RDF';
993
+ if (this.defaultNamespace) {
994
+ str += ' xmlns="' + escapeForXML(this.defaultNamespace) + '"';
995
+ }
996
+ for (var ns in namespaceCounts) {
997
+ if (!namespaceCounts.hasOwnProperty(ns)) continue;
998
+ // Rel uris in xml ns is not strictly allowed in the XMLNS spec but needed in practice often
999
+ var ns2 = this.base && this.flags.includes('z') ? Util.uri.refTo(this.base, ns) : ns;
1000
+ str += '\n xmlns:' + this.prefixes[ns] + '="' + escapeForXML(ns2) + '"';
1001
+ }
1002
+ str += '>';
1003
+ var tree2 = [str, tree, '</rdf:RDF>']; // @@ namespace declrations
1004
+ return XMLtreeToString(tree2, -1);
1005
+ } // End @@ body
1006
+ }, {
1007
+ key: "statementsToJsonld",
1008
+ value: function statementsToJsonld(sts) {
1009
+ // ttl2jsonld creates context keys for all ttl prefix
1010
+ // context keys must be full IRI
1011
+ function findId(itemObj) {
1012
+ if (itemObj['@id']) {
1013
+ var item = itemObj['@id'].split(':');
1014
+ if (keys[item[0]]) itemObj['@id'] = jsonldObj['@context'][item[0]] + item[1];
1015
+ }
1016
+ var itemValues = Object.values(itemObj);
1017
+ for (var i in itemValues) {
1018
+ if (typeof itemValues[i] !== 'string') {
1019
+ // @list contains array
1020
+ findId(itemValues[i]);
1021
+ }
1022
+ }
1023
+ }
1024
+ var turtleDoc = this.statementsToN3(sts);
1025
+ var jsonldObj = ttl2jsonld.parse(turtleDoc);
1026
+ return JSON.stringify(jsonldObj, null, 2);
960
1027
  }
961
- str += '>';
962
- var tree2 = [str, tree, '</rdf:RDF>']; // @@ namespace declrations
963
- return XMLtreeToString(tree2, -1);
964
- } // End @@ body
965
- }
1028
+ }]);
1029
+ return Serializer;
1030
+ }();
966
1031
 
967
1032
  // String escaping utilities
968
1033
 
@@ -976,9 +1041,9 @@ function backslashUify(str) {
976
1041
  for (var i = 0; i < str.length; i++) {
977
1042
  k = str.charCodeAt(i);
978
1043
  if (k > 65535) {
979
- res += '\\U' + ('00000000' + k.toString(16)).slice(-8); // convert to upper?
1044
+ res += "\\U" + ('00000000' + k.toString(16)).slice(-8); // convert to upper?
980
1045
  } else if (k > 126) {
981
- res += '\\u' + ('0000' + k.toString(16)).slice(-4);
1046
+ res += "\\u" + ('0000' + k.toString(16)).slice(-4);
982
1047
  } else {
983
1048
  res += str[i];
984
1049
  }