rdflib 2.2.10 → 2.2.12-5f141ca2

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 (190) hide show
  1. package/.babelrc +0 -0
  2. package/README.md +1 -0
  3. package/changes.txt +0 -0
  4. package/dist/rdflib.min.js +62 -0
  5. package/dist/rdflib.min.js.map +1 -0
  6. package/esm/blank-node.js +137 -0
  7. package/esm/class-order.js +12 -0
  8. package/esm/collection.js +173 -0
  9. package/esm/convert.js +61 -0
  10. package/esm/default-graph.js +57 -0
  11. package/esm/empty.js +46 -0
  12. package/esm/factories/canonical-data-factory.js +204 -0
  13. package/esm/factories/extended-term-factory.js +55 -0
  14. package/esm/factories/factory-types.js +18 -0
  15. package/esm/factories/rdflib-data-factory.js +55 -0
  16. package/esm/fetcher.js +2180 -0
  17. package/esm/formula.js +987 -0
  18. package/esm/index.js +64 -0
  19. package/esm/jsonldparser.js +122 -0
  20. package/esm/jsonparser.js +60 -0
  21. package/esm/literal.js +236 -0
  22. package/esm/log.js +13 -0
  23. package/esm/n3parser.js +1854 -0
  24. package/esm/named-node.js +154 -0
  25. package/esm/namespace.js +17 -0
  26. package/esm/node-internal.js +151 -0
  27. package/esm/node.js +46 -0
  28. package/esm/parse.js +138 -0
  29. package/esm/patch-parser.js +110 -0
  30. package/esm/query-to-sparql.js +83 -0
  31. package/esm/query.js +620 -0
  32. package/esm/rdfaparser.js +1197 -0
  33. package/esm/rdfxmlparser.js +588 -0
  34. package/esm/serialize.js +95 -0
  35. package/esm/serializer.js +1162 -0
  36. package/esm/sparql-to-query.js +566 -0
  37. package/esm/statement.js +128 -0
  38. package/esm/store.js +1306 -0
  39. package/esm/tf-types.js +1 -0
  40. package/esm/types.js +25 -0
  41. package/esm/update-manager.js +1252 -0
  42. package/esm/updates-via.js +197 -0
  43. package/esm/uri.js +245 -0
  44. package/esm/utils/default-graph-uri.js +4 -0
  45. package/esm/utils/termValue.js +8 -0
  46. package/esm/utils/terms.js +72 -0
  47. package/esm/utils-js.js +348 -0
  48. package/esm/utils.js +103 -0
  49. package/esm/variable.js +101 -0
  50. package/esm/xsd-internal.js +10 -0
  51. package/esm/xsd.js +15 -0
  52. package/lib/blank-node.d.ts +44 -0
  53. package/lib/blank-node.js +0 -0
  54. package/lib/class-order.d.ts +7 -0
  55. package/lib/class-order.js +0 -0
  56. package/lib/collection.d.ts +65 -0
  57. package/lib/collection.js +0 -0
  58. package/lib/convert.d.ts +2 -0
  59. package/lib/convert.js +0 -0
  60. package/lib/default-graph.d.ts +13 -0
  61. package/lib/default-graph.js +0 -0
  62. package/lib/empty.d.ts +11 -0
  63. package/lib/empty.js +0 -0
  64. package/lib/factories/canonical-data-factory.d.ts +6 -0
  65. package/lib/factories/canonical-data-factory.js +0 -0
  66. package/lib/factories/extended-term-factory.d.ts +13 -0
  67. package/lib/factories/extended-term-factory.js +0 -0
  68. package/lib/factories/factory-types.d.ts +67 -0
  69. package/lib/factories/factory-types.js +0 -0
  70. package/lib/factories/rdflib-data-factory.d.ts +4 -0
  71. package/lib/factories/rdflib-data-factory.js +0 -0
  72. package/lib/fetcher.d.ts +443 -0
  73. package/lib/fetcher.js +3 -2
  74. package/lib/formula.d.ts +327 -0
  75. package/lib/formula.js +0 -0
  76. package/lib/index.d.ts +40 -0
  77. package/lib/index.js +0 -0
  78. package/lib/jsonldparser.d.ts +13 -0
  79. package/lib/jsonldparser.js +0 -0
  80. package/lib/jsonparser.d.ts +4 -0
  81. package/lib/jsonparser.js +0 -0
  82. package/lib/literal.d.ts +67 -0
  83. package/lib/literal.js +0 -0
  84. package/lib/log.d.ts +15 -0
  85. package/lib/log.js +0 -0
  86. package/lib/n3parser.d.ts +62 -0
  87. package/lib/n3parser.js +1334 -1289
  88. package/lib/named-node.d.ts +44 -0
  89. package/lib/named-node.js +0 -0
  90. package/lib/namespace.d.ts +7 -0
  91. package/lib/namespace.js +0 -0
  92. package/lib/node-internal.d.ts +63 -0
  93. package/lib/node-internal.js +0 -0
  94. package/lib/node.d.ts +2 -0
  95. package/lib/node.js +0 -0
  96. package/lib/parse.d.ts +16 -0
  97. package/lib/parse.js +0 -0
  98. package/lib/patch-parser.d.ts +3 -0
  99. package/lib/patch-parser.js +0 -0
  100. package/lib/query-to-sparql.d.ts +1 -0
  101. package/lib/query-to-sparql.js +0 -0
  102. package/lib/query.d.ts +27 -0
  103. package/lib/query.js +0 -0
  104. package/lib/rdfaparser.d.ts +78 -0
  105. package/lib/rdfaparser.js +0 -0
  106. package/lib/rdfxmlparser.d.ts +60 -0
  107. package/lib/rdfxmlparser.js +430 -413
  108. package/lib/serialize.d.ts +23 -0
  109. package/lib/serialize.js +1 -1
  110. package/lib/serializer.d.ts +54 -0
  111. package/lib/serializer.js +851 -824
  112. package/lib/sparql-to-query.d.ts +6 -0
  113. package/lib/sparql-to-query.js +0 -0
  114. package/lib/statement.d.ts +55 -0
  115. package/lib/statement.js +0 -0
  116. package/lib/store.d.ts +302 -0
  117. package/lib/store.js +0 -0
  118. package/lib/tf-types.d.ts +151 -0
  119. package/lib/tf-types.js +0 -0
  120. package/lib/types.d.ts +68 -0
  121. package/lib/types.js +0 -0
  122. package/lib/update-manager.d.ts +198 -0
  123. package/lib/update-manager.js +0 -0
  124. package/lib/updates-via.d.ts +26 -0
  125. package/lib/updates-via.js +0 -0
  126. package/lib/uri.d.ts +33 -0
  127. package/lib/uri.js +0 -0
  128. package/lib/utils/default-graph-uri.d.ts +3 -0
  129. package/lib/utils/default-graph-uri.js +0 -0
  130. package/lib/utils/termValue.d.ts +3 -0
  131. package/lib/utils/termValue.js +0 -0
  132. package/lib/utils/terms.d.ts +33 -0
  133. package/lib/utils/terms.js +0 -0
  134. package/lib/utils-js.d.ts +50 -0
  135. package/lib/utils-js.js +0 -0
  136. package/lib/utils.d.ts +20 -0
  137. package/lib/utils.js +0 -0
  138. package/lib/variable.d.ts +29 -0
  139. package/lib/variable.js +0 -0
  140. package/lib/xsd-internal.d.ts +11 -0
  141. package/lib/xsd-internal.js +0 -0
  142. package/lib/xsd.d.ts +19 -0
  143. package/lib/xsd.js +8 -14
  144. package/package.json +3 -3
  145. package/src/blank-node.ts +0 -0
  146. package/src/class-order.ts +0 -0
  147. package/src/collection.ts +0 -0
  148. package/src/convert.js +0 -0
  149. package/src/default-graph.ts +0 -0
  150. package/src/empty.ts +0 -0
  151. package/src/factories/canonical-data-factory.ts +0 -0
  152. package/src/factories/extended-term-factory.ts +0 -0
  153. package/src/factories/factory-types.ts +0 -0
  154. package/src/factories/rdflib-data-factory.ts +0 -0
  155. package/src/fetcher.ts +6 -3
  156. package/src/formula.ts +0 -0
  157. package/src/index.ts +0 -0
  158. package/src/jsonldparser.js +0 -0
  159. package/src/jsonparser.js +0 -0
  160. package/src/literal.ts +0 -0
  161. package/src/log.js +0 -0
  162. package/src/n3parser.js +1114 -1110
  163. package/src/named-node.ts +0 -0
  164. package/src/namespace.ts +0 -0
  165. package/src/node-internal.ts +0 -0
  166. package/src/node.ts +0 -0
  167. package/src/parse.ts +0 -0
  168. package/src/patch-parser.js +0 -0
  169. package/src/query-to-sparql.js +0 -0
  170. package/src/query.js +0 -0
  171. package/src/rdfaparser.js +0 -0
  172. package/src/rdfxmlparser.js +22 -21
  173. package/src/serialize.ts +3 -3
  174. package/src/serializer.js +74 -62
  175. package/src/sparql-to-query.js +0 -0
  176. package/src/statement.ts +0 -0
  177. package/src/store.ts +0 -0
  178. package/src/tf-types.ts +0 -0
  179. package/src/types.ts +0 -0
  180. package/src/update-manager.ts +0 -0
  181. package/src/updates-via.js +0 -0
  182. package/src/uri.ts +0 -0
  183. package/src/utils/default-graph-uri.ts +0 -0
  184. package/src/utils/termValue.ts +0 -0
  185. package/src/utils/terms.ts +0 -0
  186. package/src/utils-js.js +0 -0
  187. package/src/utils.ts +0 -0
  188. package/src/variable.ts +0 -0
  189. package/src/xsd-internal.js +0 -0
  190. package/src/xsd.js +16 -14
@@ -0,0 +1,1252 @@
1
+ import _typeof from "@babel/runtime/helpers/typeof";
2
+ import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
3
+ import _createClass from "@babel/runtime/helpers/createClass";
4
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
5
+
6
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
7
+
8
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
9
+
10
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
11
+
12
+ /* @file Update Manager Class
13
+ **
14
+ ** 2007-07-15 originall sparl update module by Joe Presbrey <presbrey@mit.edu>
15
+ ** 2010-08-08 TimBL folded in Kenny's WEBDAV
16
+ ** 2010-12-07 TimBL addred local file write code
17
+ */
18
+ import IndexedFormula from './store';
19
+ import { docpart } from './uri';
20
+ import Fetcher from './fetcher';
21
+ import Namespace from './namespace';
22
+ import Serializer from './serializer';
23
+ import { join as uriJoin } from './uri';
24
+ import { isStore, isBlankNode } from './utils/terms';
25
+ import * as Util from './utils-js';
26
+ import { termValue } from './utils/termValue';
27
+
28
+ /**
29
+ * The UpdateManager is a helper object for a store.
30
+ * Just as a Fetcher provides the store with the ability to read and write,
31
+ * the Update Manager provides functionality for making small patches in real time,
32
+ * and also looking out for concurrent updates from other agents
33
+ */
34
+ var UpdateManager = /*#__PURE__*/function () {
35
+ /** Index of objects for coordinating incoming and outgoing patches */
36
+
37
+ /** Object of namespaces */
38
+
39
+ /**
40
+ * @param store - The quadstore to store data and metadata. Created if not passed.
41
+ */
42
+ function UpdateManager(store) {
43
+ _classCallCheck(this, UpdateManager);
44
+
45
+ _defineProperty(this, "store", void 0);
46
+
47
+ _defineProperty(this, "ifps", void 0);
48
+
49
+ _defineProperty(this, "fps", void 0);
50
+
51
+ _defineProperty(this, "patchControl", void 0);
52
+
53
+ _defineProperty(this, "ns", void 0);
54
+
55
+ store = store || new IndexedFormula();
56
+
57
+ if (store.updater) {
58
+ throw new Error("You can't have two UpdateManagers for the same store");
59
+ }
60
+
61
+ if (!store.fetcher) {
62
+ store.fetcher = new Fetcher(store);
63
+ }
64
+
65
+ this.store = store;
66
+ store.updater = this;
67
+ this.ifps = {};
68
+ this.fps = {};
69
+ this.ns = {};
70
+ this.ns.link = Namespace('http://www.w3.org/2007/ont/link#');
71
+ this.ns.http = Namespace('http://www.w3.org/2007/ont/http#');
72
+ this.ns.httph = Namespace('http://www.w3.org/2007/ont/httph#');
73
+ this.ns.ldp = Namespace('http://www.w3.org/ns/ldp#');
74
+ this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
75
+ this.ns.rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#');
76
+ this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
77
+ this.ns.owl = Namespace('http://www.w3.org/2002/07/owl#');
78
+ this.patchControl = [];
79
+ }
80
+
81
+ _createClass(UpdateManager, [{
82
+ key: "patchControlFor",
83
+ value: function patchControlFor(doc) {
84
+ if (!this.patchControl[doc.value]) {
85
+ this.patchControl[doc.value] = [];
86
+ }
87
+
88
+ return this.patchControl[doc.value];
89
+ }
90
+ }, {
91
+ key: "isHttpUri",
92
+ value: function isHttpUri(uri) {
93
+ return uri.slice(0, 4) === 'http';
94
+ }
95
+ /**
96
+ * Tests whether a file is editable.
97
+ * If the file has a specific annotation that it is machine written,
98
+ * for safety, it is editable (this doesn't actually check for write access)
99
+ * If the file has wac-allow and accept patch headers, those are respected.
100
+ * and local write access is determined by those headers.
101
+ * This version only looks at past HTTP requests, does not make new ones.
102
+ *
103
+ * @returns The method string SPARQL or DAV or
104
+ * LOCALFILE or false if known, undefined if not known.
105
+ */
106
+
107
+ }, {
108
+ key: "editable",
109
+ value: function editable(uri, kb) {
110
+ if (!uri) {
111
+ return false; // Eg subject is bnode, no known doc to write to
112
+ }
113
+
114
+ if (!kb) {
115
+ kb = this.store;
116
+ }
117
+
118
+ uri = termValue(uri);
119
+
120
+ if (!this.isHttpUri(uri)) {
121
+ if (kb.holds(this.store.rdfFactory.namedNode(uri), this.store.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.store.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#MachineEditableDocument'))) {
122
+ return 'LOCALFILE';
123
+ }
124
+ }
125
+
126
+ var request;
127
+ var definitive = false; // @ts-ignore passes a string to kb.each, which expects a term. Should this work?
128
+
129
+ var requests = kb.each(undefined, this.ns.link('requestedURI'), docpart(uri));
130
+ var method;
131
+
132
+ for (var r = 0; r < requests.length; r++) {
133
+ request = requests[r];
134
+
135
+ if (request !== undefined) {
136
+ var response = kb.any(request, this.ns.link('response'));
137
+
138
+ if (request !== undefined) {
139
+ var wacAllow = kb.anyValue(response, this.ns.httph('wac-allow'));
140
+
141
+ if (wacAllow) {
142
+ var _iterator = _createForOfIteratorHelper(wacAllow.split(',')),
143
+ _step;
144
+
145
+ try {
146
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
147
+ var bit = _step.value;
148
+ var lr = bit.split('=');
149
+
150
+ if (lr[0].includes('user') && !lr[1].includes('write') && !lr[1].includes('append')) {
151
+ // console.log(' editable? excluded by WAC-Allow: ', wacAllow)
152
+ return false;
153
+ }
154
+ }
155
+ } catch (err) {
156
+ _iterator.e(err);
157
+ } finally {
158
+ _iterator.f();
159
+ }
160
+ }
161
+
162
+ var acceptPatch = kb.each(response, this.ns.httph('accept-patch'));
163
+
164
+ if (acceptPatch.length) {
165
+ for (var i = 0; i < acceptPatch.length; i++) {
166
+ method = acceptPatch[i].value.trim();
167
+ if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL';
168
+ if (method.indexOf('application/sparql-update-single-match') >= 0) return 'SPARQL';
169
+ }
170
+ }
171
+
172
+ var authorVia = kb.each(response, this.ns.httph('ms-author-via'));
173
+
174
+ if (authorVia.length) {
175
+ for (var _i = 0; _i < authorVia.length; _i++) {
176
+ method = authorVia[_i].value.trim();
177
+
178
+ if (method.indexOf('SPARQL') >= 0) {
179
+ return 'SPARQL';
180
+ }
181
+
182
+ if (method.indexOf('DAV') >= 0) {
183
+ return 'DAV';
184
+ }
185
+ }
186
+ }
187
+
188
+ if (!this.isHttpUri(uri)) {
189
+ if (!wacAllow) return false;else return 'LOCALFILE';
190
+ }
191
+
192
+ var status = kb.each(response, this.ns.http('status'));
193
+
194
+ if (status.length) {
195
+ for (var _i2 = 0; _i2 < status.length; _i2++) {
196
+ // @ts-ignore since statuses should be TFTerms, this should always be false
197
+ if (status[_i2] === 200 || status[_i2] === 404) {
198
+ definitive = true; // return false // A definitive answer
199
+ }
200
+ }
201
+ }
202
+ } else {// console.log('UpdateManager.editable: No response for ' + uri + '\n')
203
+ }
204
+ }
205
+ }
206
+
207
+ if (requests.length === 0) {// console.log('UpdateManager.editable: No request for ' + uri + '\n')
208
+ } else {
209
+ if (definitive) {
210
+ return false; // We have got a request and it did NOT say editable => not editable
211
+ }
212
+ } // console.log('UpdateManager.editable: inconclusive for ' + uri + '\n')
213
+
214
+
215
+ return undefined; // We don't know (yet) as we haven't had a response (yet)
216
+ }
217
+ }, {
218
+ key: "anonymize",
219
+ value: function anonymize(obj) {
220
+ return obj.toNT().substr(0, 2) === '_:' && this.mentioned(obj) ? '?' + obj.toNT().substr(2) : obj.toNT();
221
+ }
222
+ }, {
223
+ key: "anonymizeNT",
224
+ value: function anonymizeNT(stmt) {
225
+ return this.anonymize(stmt.subject) + ' ' + this.anonymize(stmt.predicate) + ' ' + this.anonymize(stmt.object) + ' .';
226
+ }
227
+ /**
228
+ * Returns a list of all bnodes occurring in a statement
229
+ * @private
230
+ */
231
+
232
+ }, {
233
+ key: "statementBnodes",
234
+ value: function statementBnodes(st) {
235
+ return [st.subject, st.predicate, st.object].filter(function (x) {
236
+ return isBlankNode(x);
237
+ });
238
+ }
239
+ /**
240
+ * Returns a list of all bnodes occurring in a list of statements
241
+ * @private
242
+ */
243
+
244
+ }, {
245
+ key: "statementArrayBnodes",
246
+ value: function statementArrayBnodes(sts) {
247
+ var bnodes = [];
248
+
249
+ for (var i = 0; i < sts.length; i++) {
250
+ bnodes = bnodes.concat(this.statementBnodes(sts[i]));
251
+ }
252
+
253
+ bnodes.sort(); // in place sort - result may have duplicates
254
+
255
+ var bnodes2 = [];
256
+
257
+ for (var j = 0; j < bnodes.length; j++) {
258
+ if (j === 0 || !bnodes[j].equals(bnodes[j - 1])) {
259
+ bnodes2.push(bnodes[j]);
260
+ }
261
+ }
262
+
263
+ return bnodes2;
264
+ }
265
+ /**
266
+ * Makes a cached list of [Inverse-]Functional properties
267
+ * @private
268
+ */
269
+
270
+ }, {
271
+ key: "cacheIfps",
272
+ value: function cacheIfps() {
273
+ this.ifps = {};
274
+ var a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('InverseFunctionalProperty'));
275
+
276
+ for (var i = 0; i < a.length; i++) {
277
+ this.ifps[a[i].value] = true;
278
+ }
279
+
280
+ this.fps = {};
281
+ a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty'));
282
+
283
+ for (var _i3 = 0; _i3 < a.length; _i3++) {
284
+ this.fps[a[_i3].value] = true;
285
+ }
286
+ }
287
+ /**
288
+ * Returns a context to bind a given node, up to a given depth
289
+ * @private
290
+ */
291
+
292
+ }, {
293
+ key: "bnodeContext2",
294
+ value: function bnodeContext2(x, source, depth) {
295
+ // Return a list of statements which indirectly identify a node
296
+ // Depth > 1 if try further indirection.
297
+ // Return array of statements (possibly empty), or null if failure
298
+ var sts = this.store.statementsMatching(undefined, undefined, x, source); // incoming links
299
+
300
+ var y;
301
+ var res;
302
+
303
+ for (var i = 0; i < sts.length; i++) {
304
+ if (this.fps[sts[i].predicate.value]) {
305
+ y = sts[i].subject;
306
+
307
+ if (!y.isBlank) {
308
+ return [sts[i]];
309
+ }
310
+
311
+ if (depth) {
312
+ res = this.bnodeContext2(y, source, depth - 1);
313
+
314
+ if (res) {
315
+ return res.concat([sts[i]]);
316
+ }
317
+ }
318
+ }
319
+ } // outgoing links
320
+
321
+
322
+ sts = this.store.statementsMatching(x, undefined, undefined, source);
323
+
324
+ for (var _i4 = 0; _i4 < sts.length; _i4++) {
325
+ if (this.ifps[sts[_i4].predicate.value]) {
326
+ y = sts[_i4].object;
327
+
328
+ if (!y.isBlank) {
329
+ return [sts[_i4]];
330
+ }
331
+
332
+ if (depth) {
333
+ res = this.bnodeContext2(y, source, depth - 1);
334
+
335
+ if (res) {
336
+ return res.concat([sts[_i4]]);
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ return null; // Failure
343
+ }
344
+ /**
345
+ * Returns the smallest context to bind a given single bnode
346
+ * @private
347
+ */
348
+
349
+ }, {
350
+ key: "bnodeContext1",
351
+ value: function bnodeContext1(x, source) {
352
+ // Return a list of statements which indirectly identify a node
353
+ // Breadth-first
354
+ for (var depth = 0; depth < 3; depth++) {
355
+ // Try simple first
356
+ var con = this.bnodeContext2(x, source, depth);
357
+ if (con !== null) return con;
358
+ } // If we can't guarantee unique with logic just send all info about node
359
+
360
+
361
+ return this.store.connectedStatements(x, source); // was:
362
+ // throw new Error('Unable to uniquely identify bnode: ' + x.toNT())
363
+ }
364
+ /**
365
+ * @private
366
+ */
367
+
368
+ }, {
369
+ key: "mentioned",
370
+ value: function mentioned(x) {
371
+ return this.store.statementsMatching(x, null, null, null).length !== 0 || // Don't pin fresh bnodes
372
+ this.store.statementsMatching(null, x).length !== 0 || this.store.statementsMatching(null, null, x).length !== 0;
373
+ }
374
+ /**
375
+ * @private
376
+ */
377
+
378
+ }, {
379
+ key: "bnodeContext",
380
+ value: function bnodeContext(bnodes, doc) {
381
+ var context = [];
382
+
383
+ if (bnodes.length) {
384
+ this.cacheIfps();
385
+
386
+ for (var i = 0; i < bnodes.length; i++) {
387
+ // Does this occur in old graph?
388
+ var bnode = bnodes[i];
389
+ if (!this.mentioned(bnode)) continue;
390
+ context = context.concat(this.bnodeContext1(bnode, doc));
391
+ }
392
+ }
393
+
394
+ return context;
395
+ }
396
+ /**
397
+ * Returns the best context for a single statement
398
+ * @private
399
+ */
400
+
401
+ }, {
402
+ key: "statementContext",
403
+ value: function statementContext(st) {
404
+ var bnodes = this.statementBnodes(st);
405
+ return this.bnodeContext(bnodes, st.graph);
406
+ }
407
+ /**
408
+ * @private
409
+ */
410
+
411
+ }, {
412
+ key: "contextWhere",
413
+ value: function contextWhere(context) {
414
+ var updater = this;
415
+ return !context || context.length === 0 ? '' : 'WHERE { ' + context.map(function (x) {
416
+ return updater.anonymizeNT(x);
417
+ }).join('\n') + ' }\n';
418
+ }
419
+ /**
420
+ * @private
421
+ */
422
+
423
+ }, {
424
+ key: "fire",
425
+ value: function fire(uri, query, callbackFunction) {
426
+ var _this = this;
427
+
428
+ return Promise.resolve().then(function () {
429
+ if (!uri) {
430
+ throw new Error('No URI given for remote editing operation: ' + query);
431
+ } // console.log('UpdateManager: sending update to <' + uri + '>')
432
+
433
+
434
+ var options = {
435
+ noMeta: true,
436
+ contentType: 'application/sparql-update',
437
+ body: query
438
+ };
439
+ return _this.store.fetcher.webOperation('PATCH', uri, options);
440
+ }).then(function (response) {
441
+ if (!response.ok) {
442
+ var _message = 'UpdateManager: update failed for <' + uri + '> status=' + response.status + ', ' + response.statusText + '\n for query: ' + query; // console.log(message)
443
+
444
+
445
+ throw new Error(_message);
446
+ } // console.log('UpdateManager: update Ok for <' + uri + '>')
447
+
448
+
449
+ callbackFunction(uri, response.ok, response.responseText, response);
450
+ }).catch(function (err) {
451
+ callbackFunction(uri, false, err.message, err);
452
+ });
453
+ } // ARE THESE THEE FUNCTIONS USED? DEPROCATE?
454
+
455
+ /** return a statemnet updating function
456
+ *
457
+ * This does NOT update the statement.
458
+ * It returns an object which includes
459
+ * function which can be used to change the object of the statement.
460
+ */
461
+
462
+ }, {
463
+ key: "update_statement",
464
+ value: function update_statement(statement) {
465
+ if (statement && !statement.graph) {
466
+ return;
467
+ }
468
+
469
+ var updater = this;
470
+ var context = this.statementContext(statement);
471
+ return {
472
+ statement: statement ? [statement.subject, statement.predicate, statement.object, statement.graph] : undefined,
473
+ statementNT: statement ? this.anonymizeNT(statement) : undefined,
474
+ where: updater.contextWhere(context),
475
+ set_object: function set_object(obj, callbackFunction) {
476
+ var query = this.where;
477
+ query += 'DELETE DATA { ' + this.statementNT + ' } ;\n';
478
+ query += 'INSERT DATA { ' + // @ts-ignore `this` might refer to the wrong scope. Does this work?
479
+ this.anonymize(this.statement[0]) + ' ' + // @ts-ignore
480
+ this.anonymize(this.statement[1]) + ' ' + // @ts-ignore
481
+ this.anonymize(obj) + ' ' + ' . }\n';
482
+ updater.fire(this.statement[3].value, query, callbackFunction);
483
+ }
484
+ };
485
+ }
486
+ }, {
487
+ key: "insert_statement",
488
+ value: function insert_statement(st, callbackFunction) {
489
+ var st0 = st instanceof Array ? st[0] : st;
490
+ var query = this.contextWhere(this.statementContext(st0));
491
+
492
+ if (st instanceof Array) {
493
+ var stText = '';
494
+
495
+ for (var i = 0; i < st.length; i++) {
496
+ stText += st[i] + '\n';
497
+ }
498
+
499
+ query += 'INSERT DATA { ' + stText + ' }\n';
500
+ } else {
501
+ query += 'INSERT DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n';
502
+ }
503
+
504
+ this.fire(st0.graph.value, query, callbackFunction);
505
+ }
506
+ }, {
507
+ key: "delete_statement",
508
+ value: function delete_statement(st, callbackFunction) {
509
+ var st0 = st instanceof Array ? st[0] : st;
510
+ var query = this.contextWhere(this.statementContext(st0));
511
+
512
+ if (st instanceof Array) {
513
+ var stText = '';
514
+
515
+ for (var i = 0; i < st.length; i++) {
516
+ stText += st[i] + '\n';
517
+ }
518
+
519
+ query += 'DELETE DATA { ' + stText + ' }\n';
520
+ } else {
521
+ query += 'DELETE DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n';
522
+ }
523
+
524
+ this.fire(st0.graph.value, query, callbackFunction);
525
+ } /// //////////////////////
526
+
527
+ /**
528
+ * Requests a now or future action to refresh changes coming downstream
529
+ * This is designed to allow the system to re-request the server version,
530
+ * when a websocket has pinged to say there are changes.
531
+ * If the websocket, by contrast, has sent a patch, then this may not be necessary.
532
+ *
533
+ * @param doc
534
+ * @param action
535
+ */
536
+
537
+ }, {
538
+ key: "requestDownstreamAction",
539
+ value: function requestDownstreamAction(doc, action) {
540
+ var control = this.patchControlFor(doc);
541
+
542
+ if (!control.pendingUpstream) {
543
+ action(doc);
544
+ } else {
545
+ if (control.downstreamAction) {
546
+ if ('' + control.downstreamAction !== '' + action) {
547
+ // Kludge compare
548
+ throw new Error("Can't wait for > 1 different downstream actions");
549
+ }
550
+ } else {
551
+ control.downstreamAction = action;
552
+ }
553
+ }
554
+ }
555
+ /**
556
+ * We want to start counting websocket notifications
557
+ * to distinguish the ones from others from our own.
558
+ */
559
+
560
+ }, {
561
+ key: "clearUpstreamCount",
562
+ value: function clearUpstreamCount(doc) {
563
+ var control = this.patchControlFor(doc);
564
+ control.upstreamCount = 0;
565
+ }
566
+ }, {
567
+ key: "getUpdatesVia",
568
+ value: function getUpdatesVia(doc) {
569
+ var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via');
570
+ if (!linkHeaders || !linkHeaders.length) return null;
571
+ return linkHeaders[0].trim();
572
+ }
573
+ }, {
574
+ key: "addDownstreamChangeListener",
575
+ value: function addDownstreamChangeListener(doc, listener) {
576
+ var _this2 = this;
577
+
578
+ var control = this.patchControlFor(doc);
579
+
580
+ if (!control.downstreamChangeListeners) {
581
+ control.downstreamChangeListeners = [];
582
+ }
583
+
584
+ control.downstreamChangeListeners.push(listener);
585
+ this.setRefreshHandler(doc, function (doc) {
586
+ _this2.reloadAndSync(doc);
587
+ });
588
+ }
589
+ }, {
590
+ key: "reloadAndSync",
591
+ value: function reloadAndSync(doc) {
592
+ var control = this.patchControlFor(doc);
593
+ var updater = this;
594
+
595
+ if (control.reloading) {
596
+ // console.log(' Already reloading - note this load may be out of date')
597
+ control.outOfDate = true;
598
+ return; // once only needed @@ Not true, has changed again
599
+ }
600
+
601
+ control.reloading = true;
602
+ var retryTimeout = 1000; // ms
603
+
604
+ var tryReload = function tryReload() {
605
+ // console.log('try reload - timeout = ' + retryTimeout)
606
+ updater.reload(updater.store, doc, function (ok, message, response) {
607
+ if (ok) {
608
+ if (control.downstreamChangeListeners) {
609
+ for (var i = 0; i < control.downstreamChangeListeners.length; i++) {
610
+ // console.log(' Calling downstream listener ' + i)
611
+ control.downstreamChangeListeners[i]();
612
+ }
613
+ }
614
+
615
+ control.reloading = false;
616
+
617
+ if (control.outOfDate) {
618
+ // console.log(' Extra reload because of extra update.')
619
+ control.outOfDate = false;
620
+ tryReload();
621
+ }
622
+ } else {
623
+ control.reloading = false;
624
+
625
+ if (response.status === 0) {
626
+ // console.log('Network error refreshing the data. Retrying in ' +
627
+ // retryTimeout / 1000)
628
+ control.reloading = true;
629
+ retryTimeout = retryTimeout * 2;
630
+ setTimeout(tryReload, retryTimeout);
631
+ } else {// console.log('Error ' + (response as Response).status + 'refreshing the data:' +
632
+ // message + '. Stopped' + doc)
633
+ }
634
+ }
635
+ });
636
+ };
637
+
638
+ tryReload();
639
+ }
640
+ /**
641
+ * Sets up websocket to listen on
642
+ *
643
+ * There is coordination between upstream changes and downstream ones
644
+ * so that a reload is not done in the middle of an upstream patch.
645
+ * If you use this API then you get called when a change happens, and you
646
+ * have to reload the file yourself, and then refresh the UI.
647
+ * Alternative is addDownstreamChangeListener(), where you do not
648
+ * have to do the reload yourself. Do mot mix them.
649
+ *
650
+ * kb contains the HTTP metadata from previous operations
651
+ *
652
+ * @param doc
653
+ * @param handler
654
+ *
655
+ * @returns {boolean}
656
+ */
657
+
658
+ }, {
659
+ key: "setRefreshHandler",
660
+ value: function setRefreshHandler(doc, handler) {
661
+ var wssURI = this.getUpdatesVia(doc); // relative
662
+ // var kb = this.store
663
+
664
+ var theHandler = handler;
665
+ var self = this;
666
+ var updater = this;
667
+ var retryTimeout = 1500; // *2 will be 3 Seconds, 6, 12, etc
668
+
669
+ var retries = 0;
670
+
671
+ if (!wssURI) {
672
+ // console.log('Server does not support live updates through Updates-Via :-(')
673
+ return false;
674
+ }
675
+
676
+ wssURI = uriJoin(wssURI, doc.value);
677
+ var validWssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:'); // console.log('Web socket URI ' + wssURI)
678
+
679
+ var openWebsocket = function openWebsocket() {
680
+ // From https://github.com/solid/solid-spec#live-updates
681
+ var socket;
682
+
683
+ if (typeof WebSocket !== 'undefined') {
684
+ socket = new WebSocket(validWssURI);
685
+ } else if (typeof window !== 'undefined' && window.WebSocket) {
686
+ socket = window.WebSocket(validWssURI);
687
+ } else {
688
+ // console.log('Live update disabled, as WebSocket not supported by platform :-(')
689
+ return;
690
+ }
691
+
692
+ socket.onopen = function () {
693
+ // console.log(' websocket open')
694
+ retryTimeout = 1500; // reset timeout to fast on success
695
+
696
+ this.send('sub ' + doc.value);
697
+
698
+ if (retries) {
699
+ // console.log('Web socket has been down, better check for any news.')
700
+ updater.requestDownstreamAction(doc, theHandler);
701
+ }
702
+ };
703
+
704
+ var control = self.patchControlFor(doc);
705
+ control.upstreamCount = 0;
706
+
707
+ socket.onerror = function onerror(err) {// console.log('Error on Websocket:', err)
708
+ }; // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
709
+ //
710
+ // 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created.
711
+ // 1001 CLOSE_GOING_AWAY The endpoint is going away, either
712
+ // because of a server failure or because the browser is navigating away from the page that opened the connection.
713
+ // 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error.
714
+ // 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint
715
+ // received data of a type it cannot accept (for example, a text-only endpoint received binary data).
716
+ // 1004 Reserved. A meaning might be defined in the future.
717
+ // 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected.
718
+ // 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally (
719
+ //
720
+ //
721
+
722
+
723
+ socket.onclose = function (event) {
724
+ // console.log('*** Websocket closed with code ' + event.code +
725
+ // ", reason '" + event.reason + "' clean = " + event.wasClean)
726
+ retryTimeout *= 2;
727
+ retries += 1; // console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?)
728
+
729
+ setTimeout(function () {
730
+ // console.log('Trying websocket again')
731
+ openWebsocket();
732
+ }, retryTimeout);
733
+ };
734
+
735
+ socket.onmessage = function (msg) {
736
+ if (msg.data && msg.data.slice(0, 3) === 'pub') {
737
+ if ('upstreamCount' in control) {
738
+ control.upstreamCount -= 1;
739
+
740
+ if (control.upstreamCount >= 0) {
741
+ // console.log('just an echo: ' + control.upstreamCount)
742
+ return; // Just an echo
743
+ }
744
+ } // console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0')
745
+
746
+
747
+ control.upstreamCount = 0;
748
+ self.requestDownstreamAction(doc, theHandler);
749
+ }
750
+ };
751
+ }; // openWebsocket
752
+
753
+
754
+ openWebsocket();
755
+ return true;
756
+ }
757
+ /**
758
+ * This high-level function updates the local store iff the web is changed successfully.
759
+ * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
760
+ * The `why` property of each statement must be the give the web document to be updated.
761
+ * The statements to be deleted and inserted may span more than one web document.
762
+ * @param deletions - Statement or statements to be deleted.
763
+ * @param insertions - Statement or statements to be inserted.
764
+ * @returns a promise
765
+ */
766
+
767
+ }, {
768
+ key: "updateMany",
769
+ value: function updateMany(deletions) {
770
+ var insertions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
771
+ var docs = deletions.concat(insertions).map(function (st) {
772
+ return st.why;
773
+ });
774
+ var thisUpdater = this;
775
+ var uniqueDocs = [];
776
+ docs.forEach(function (doc) {
777
+ if (!uniqueDocs.find(function (uniqueDoc) {
778
+ return uniqueDoc.equals(doc);
779
+ })) uniqueDocs.push(doc);
780
+ });
781
+ var updates = uniqueDocs.map(function (doc) {
782
+ return thisUpdater.update(deletions.filter(function (st) {
783
+ return st.why.equals(doc);
784
+ }), insertions.filter(function (st) {
785
+ return st.why.equals(doc);
786
+ }));
787
+ });
788
+
789
+ if (updates.length > 1) {
790
+ console.log("@@ updateMany to ".concat(updates.length, ": ").concat(uniqueDocs));
791
+ }
792
+
793
+ return Promise.all(updates);
794
+ }
795
+ /**
796
+ * This high-level function updates the local store iff the web is changed successfully.
797
+ * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
798
+ * The `why` property of each statement must be the same and give the web document to be updated.
799
+ * @param deletions - Statement or statements to be deleted.
800
+ * @param insertions - Statement or statements to be inserted.
801
+ * @param callback - called as callbackFunction(uri, success, errorbody)
802
+ * OR returns a promise
803
+ */
804
+
805
+ }, {
806
+ key: "update",
807
+ value: function update(deletions, insertions, callback, secondTry) {
808
+ var _this3 = this;
809
+
810
+ if (!callback) {
811
+ var thisUpdater = this;
812
+ return new Promise(function (resolve, reject) {
813
+ // Promise version
814
+ thisUpdater.update(deletions, insertions, function (uri, ok, errorBody) {
815
+ if (!ok) {
816
+ reject(new Error(errorBody));
817
+ } else {
818
+ resolve();
819
+ }
820
+ }); // callbackFunction
821
+ }); // promise
822
+ } // if
823
+
824
+
825
+ try {
826
+ var kb = this.store;
827
+ var ds = !deletions ? [] : isStore(deletions) ? deletions.statements : deletions instanceof Array ? deletions : [deletions];
828
+ var is = !insertions ? [] : isStore(insertions) ? insertions.statements : insertions instanceof Array ? insertions : [insertions];
829
+
830
+ if (!(ds instanceof Array)) {
831
+ throw new Error('Type Error ' + _typeof(ds) + ': ' + ds);
832
+ }
833
+
834
+ if (!(is instanceof Array)) {
835
+ throw new Error('Type Error ' + _typeof(is) + ': ' + is);
836
+ }
837
+
838
+ if (ds.length === 0 && is.length === 0) {
839
+ return callback(null, true); // success -- nothing needed to be done.
840
+ }
841
+
842
+ var doc = ds.length ? ds[0].graph : is[0].graph;
843
+
844
+ if (!doc) {
845
+ var _message2 = 'Error patching: statement does not specify which document to patch:' + ds[0] + ', ' + is[0]; // console.log(message)
846
+
847
+
848
+ throw new Error(_message2);
849
+ }
850
+
851
+ var control = this.patchControlFor(doc);
852
+ var startTime = Date.now();
853
+ var props = ['subject', 'predicate', 'object', 'why'];
854
+ var verbs = ['insert', 'delete'];
855
+ var clauses = {
856
+ 'delete': ds,
857
+ 'insert': is
858
+ };
859
+ verbs.map(function (verb) {
860
+ clauses[verb].map(function (st) {
861
+ if (!doc.equals(st.graph)) {
862
+ throw new Error('update: destination ' + doc + ' inconsistent with delete quad ' + st.graph);
863
+ }
864
+
865
+ props.map(function (prop) {
866
+ if (typeof st[prop] === 'undefined') {
867
+ throw new Error('update: undefined ' + prop + ' of statement.');
868
+ }
869
+ });
870
+ });
871
+ });
872
+ var protocol = this.editable(doc.value, kb);
873
+
874
+ if (protocol === false) {
875
+ throw new Error('Update: Can\'t make changes in uneditable ' + doc);
876
+ }
877
+
878
+ if (protocol === undefined) {
879
+ // Not enough metadata
880
+ if (secondTry) {
881
+ throw new Error('Update: Loaded ' + doc + "but stil can't figure out what editing protcol it supports.");
882
+ } // console.log(`Update: have not loaded ${doc} before: loading now...`);
883
+
884
+
885
+ this.store.fetcher.load(doc).then(function (response) {
886
+ _this3.update(deletions, insertions, callback, true);
887
+ }, function (err) {
888
+ if (err.response.status === 404) {
889
+ // nonexistent files are fine
890
+ _this3.update(deletions, insertions, callback, true);
891
+ } else {
892
+ throw new Error("Update: Can't get updatability status ".concat(doc, " before patching: ").concat(err));
893
+ }
894
+ });
895
+ return;
896
+ } else if (protocol.indexOf('SPARQL') >= 0) {
897
+ var bnodes = [];
898
+ if (ds.length) bnodes = this.statementArrayBnodes(ds);
899
+ if (is.length) bnodes = bnodes.concat(this.statementArrayBnodes(is));
900
+ var context = this.bnodeContext(bnodes, doc);
901
+ var whereClause = this.contextWhere(context);
902
+ var query = '';
903
+
904
+ if (whereClause.length) {
905
+ // Is there a WHERE clause?
906
+ if (ds.length) {
907
+ query += 'DELETE { ';
908
+
909
+ for (var i = 0; i < ds.length; i++) {
910
+ query += this.anonymizeNT(ds[i]) + '\n';
911
+ }
912
+
913
+ query += ' }\n';
914
+ }
915
+
916
+ if (is.length) {
917
+ query += 'INSERT { ';
918
+
919
+ for (var _i5 = 0; _i5 < is.length; _i5++) {
920
+ query += this.anonymizeNT(is[_i5]) + '\n';
921
+ }
922
+
923
+ query += ' }\n';
924
+ }
925
+
926
+ query += whereClause;
927
+ } else {
928
+ // no where clause
929
+ if (ds.length) {
930
+ query += 'DELETE DATA { ';
931
+
932
+ for (var _i6 = 0; _i6 < ds.length; _i6++) {
933
+ query += this.anonymizeNT(ds[_i6]) + '\n';
934
+ }
935
+
936
+ query += ' } \n';
937
+ }
938
+
939
+ if (is.length) {
940
+ if (ds.length) query += ' ; ';
941
+ query += 'INSERT DATA { ';
942
+
943
+ for (var _i7 = 0; _i7 < is.length; _i7++) {
944
+ query += this.anonymizeNT(is[_i7]) + '\n';
945
+ }
946
+
947
+ query += ' }\n';
948
+ }
949
+ } // Track pending upstream patches until they have finished their callbackFunction
950
+
951
+
952
+ control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1;
953
+
954
+ if ('upstreamCount' in control) {
955
+ control.upstreamCount += 1; // count changes we originated ourselves
956
+ // console.log('upstream count up to : ' + control.upstreamCount)
957
+ }
958
+
959
+ this.fire(doc.value, query, function (uri, success, body, response) {
960
+ response.elapsedTimeMs = Date.now() - startTime;
961
+ console.log(' UpdateManager: Return ' + (success ? 'success ' : 'FAILURE ') + response.status + ' elapsed ' + response.elapsedTimeMs + 'ms');
962
+
963
+ if (success) {
964
+ try {
965
+ kb.remove(ds);
966
+ } catch (e) {
967
+ success = false;
968
+ body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e;
969
+ } // Add in any case -- help recover from weirdness??
970
+
971
+
972
+ for (var _i8 = 0; _i8 < is.length; _i8++) {
973
+ kb.add(is[_i8].subject, is[_i8].predicate, is[_i8].object, doc);
974
+ }
975
+ }
976
+
977
+ callback(uri, success, body, response);
978
+ control.pendingUpstream -= 1; // When upstream patches have been sent, reload state if downstream waiting
979
+
980
+ if (control.pendingUpstream === 0 && control.downstreamAction) {
981
+ var downstreamAction = control.downstreamAction;
982
+ delete control.downstreamAction; // console.log('delayed downstream action:')
983
+
984
+ downstreamAction(doc);
985
+ }
986
+ });
987
+ } else if (protocol.indexOf('DAV') >= 0) {
988
+ this.updateDav(doc, ds, is, callback);
989
+ } else {
990
+ if (protocol.indexOf('LOCALFILE') >= 0) {
991
+ try {
992
+ this.updateLocalFile(doc, ds, is, callback);
993
+ } catch (e) {
994
+ callback(doc.value, false, 'Exception trying to write back file <' + doc.value + '>\n' // + tabulator.Util.stackString(e))
995
+ );
996
+ }
997
+ } else {
998
+ throw new Error("Unhandled edit method: '" + protocol + "' for " + doc);
999
+ }
1000
+ }
1001
+ } catch (e) {
1002
+ callback(undefined, false, 'Exception in update: ' + e + '\n' + Util.stackString(e));
1003
+ }
1004
+ }
1005
+ }, {
1006
+ key: "updateDav",
1007
+ value: function updateDav(doc, ds, is, callbackFunction) {
1008
+ var kb = this.store; // The code below is derived from Kenny's UpdateCenter.js
1009
+
1010
+ var request = kb.any(doc, this.ns.link('request'));
1011
+
1012
+ if (!request) {
1013
+ throw new Error('No record of our HTTP GET request for document: ' + doc);
1014
+ } // should not happen
1015
+
1016
+
1017
+ var response = kb.any(request, this.ns.link('response'));
1018
+
1019
+ if (!response) {
1020
+ return null; // throw "No record HTTP GET response for document: "+doc
1021
+ }
1022
+
1023
+ var contentType = kb.the(response, this.ns.httph('content-type')).value; // prepare contents of revised document
1024
+
1025
+ var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy!
1026
+
1027
+ for (var i = 0; i < ds.length; i++) {
1028
+ Util.RDFArrayRemove(newSts, ds[i]);
1029
+ }
1030
+
1031
+ for (var _i9 = 0; _i9 < is.length; _i9++) {
1032
+ newSts.push(is[_i9]);
1033
+ }
1034
+
1035
+ var documentString = this.serialize(doc.value, newSts, contentType); // Write the new version back
1036
+
1037
+ var candidateTarget = kb.the(response, this.ns.httph('content-location'));
1038
+ var targetURI;
1039
+
1040
+ if (candidateTarget) {
1041
+ targetURI = uriJoin(candidateTarget.value, targetURI);
1042
+ }
1043
+
1044
+ var options = {
1045
+ contentType: contentType,
1046
+ noMeta: true,
1047
+ body: documentString
1048
+ };
1049
+ return kb.fetcher.webOperation('PUT', targetURI, options).then(function (response) {
1050
+ if (!response.ok) {
1051
+ throw new Error(response.error);
1052
+ }
1053
+
1054
+ for (var _i10 = 0; _i10 < ds.length; _i10++) {
1055
+ kb.remove(ds[_i10]);
1056
+ }
1057
+
1058
+ for (var _i11 = 0; _i11 < is.length; _i11++) {
1059
+ kb.add(is[_i11].subject, is[_i11].predicate, is[_i11].object, doc);
1060
+ }
1061
+
1062
+ callbackFunction(doc.value, response.ok, response.responseText, response);
1063
+ }).catch(function (err) {
1064
+ callbackFunction(doc.value, false, err.message, err);
1065
+ });
1066
+ }
1067
+ /**
1068
+ * Likely deprecated, since this lib no longer deals with browser extension
1069
+ *
1070
+ * @param doc
1071
+ * @param ds
1072
+ * @param is
1073
+ * @param callbackFunction
1074
+ */
1075
+
1076
+ }, {
1077
+ key: "updateLocalFile",
1078
+ value: function updateLocalFile(doc, ds, is, callbackFunction) {
1079
+ var kb = this.store; // console.log('Writing back to local file\n')
1080
+ // prepare contents of revised document
1081
+
1082
+ var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy!
1083
+
1084
+ for (var i = 0; i < ds.length; i++) {
1085
+ Util.RDFArrayRemove(newSts, ds[i]);
1086
+ }
1087
+
1088
+ for (var _i12 = 0; _i12 < is.length; _i12++) {
1089
+ newSts.push(is[_i12]);
1090
+ } // serialize to the appropriate format
1091
+
1092
+
1093
+ var dot = doc.value.lastIndexOf('.');
1094
+
1095
+ if (dot < 1) {
1096
+ throw new Error('Rewriting file: No filename extension: ' + doc.value);
1097
+ }
1098
+
1099
+ var ext = doc.value.slice(dot + 1);
1100
+ var contentType = Fetcher.CONTENT_TYPE_BY_EXT[ext];
1101
+
1102
+ if (!contentType) {
1103
+ throw new Error('File extension .' + ext + ' not supported for data write');
1104
+ }
1105
+
1106
+ var documentString = this.serialize(doc.value, newSts, contentType);
1107
+ kb.fetcher.webOperation('PUT', doc.value, {
1108
+ "body": documentString,
1109
+ contentType: contentType
1110
+ }).then(function (response) {
1111
+ if (!response.ok) return callbackFunction(doc.value, false, response.error);
1112
+
1113
+ for (var _i13 = 0; _i13 < ds.length; _i13++) {
1114
+ kb.remove(ds[_i13]);
1115
+ }
1116
+
1117
+ for (var _i14 = 0; _i14 < is.length; _i14++) {
1118
+ kb.add(is[_i14].subject, is[_i14].predicate, is[_i14].object, doc);
1119
+ }
1120
+
1121
+ callbackFunction(doc.value, true, ''); // success!
1122
+ });
1123
+ }
1124
+ /**
1125
+ * @throws {Error} On unsupported content type
1126
+ *
1127
+ * @returns {string}
1128
+ */
1129
+
1130
+ }, {
1131
+ key: "serialize",
1132
+ value: function serialize(uri, data, contentType) {
1133
+ var kb = this.store;
1134
+ var documentString;
1135
+
1136
+ if (typeof data === 'string') {
1137
+ return data;
1138
+ } // serialize to the appropriate format
1139
+
1140
+
1141
+ var sz = Serializer(kb);
1142
+ sz.suggestNamespaces(kb.namespaces);
1143
+ sz.setBase(uri);
1144
+
1145
+ switch (contentType) {
1146
+ case 'text/xml':
1147
+ case 'application/rdf+xml':
1148
+ documentString = sz.statementsToXML(data);
1149
+ break;
1150
+
1151
+ case 'text/n3':
1152
+ case 'text/turtle':
1153
+ case 'application/x-turtle': // Legacy
1154
+
1155
+ case 'application/n3':
1156
+ // Legacy
1157
+ documentString = sz.statementsToN3(data);
1158
+ break;
1159
+
1160
+ default:
1161
+ throw new Error('Content-type ' + contentType + ' not supported for data serialization');
1162
+ }
1163
+
1164
+ return documentString;
1165
+ }
1166
+ /**
1167
+ * This is suitable for an initial creation of a document.
1168
+ */
1169
+
1170
+ }, {
1171
+ key: "put",
1172
+ value: function put(doc, data, contentType, callback) {
1173
+ var _this4 = this;
1174
+
1175
+ var kb = this.store;
1176
+ var documentString;
1177
+ return Promise.resolve().then(function () {
1178
+ documentString = _this4.serialize(doc.value, data, contentType);
1179
+ return kb.fetcher.webOperation('PUT', doc.value, {
1180
+ contentType: contentType,
1181
+ body: documentString
1182
+ });
1183
+ }).then(function (response) {
1184
+ if (!response.ok) {
1185
+ return callback(doc.value, response.ok, response.error, response);
1186
+ }
1187
+
1188
+ delete kb.fetcher.nonexistent[doc.value];
1189
+ delete kb.fetcher.requested[doc.value]; // @@ could this mess with the requested state machine? if a fetch is in progress
1190
+
1191
+ if (typeof data !== 'string') {
1192
+ data.map(function (st) {
1193
+ kb.addStatement(st);
1194
+ });
1195
+ }
1196
+
1197
+ callback(doc.value, response.ok, '', response);
1198
+ }).catch(function (err) {
1199
+ callback(doc.value, false, err.message);
1200
+ });
1201
+ }
1202
+ /**
1203
+ * Reloads a document.
1204
+ *
1205
+ * Fast and cheap, no metadata. Measure times for the document.
1206
+ * Load it provisionally.
1207
+ * Don't delete the statements before the load, or it will leave a broken
1208
+ * document in the meantime.
1209
+ *
1210
+ * @param kb
1211
+ * @param doc {RDFlibNamedNode}
1212
+ * @param callbackFunction
1213
+ */
1214
+
1215
+ }, {
1216
+ key: "reload",
1217
+ value: function reload(kb, doc, callbackFunction) {
1218
+ var startTime = Date.now(); // force sets no-cache and
1219
+
1220
+ var options = {
1221
+ force: true,
1222
+ noMeta: true,
1223
+ clearPreviousData: true
1224
+ };
1225
+ kb.fetcher.nowOrWhenFetched(doc.value, options, function (ok, body, response) {
1226
+ if (!ok) {
1227
+ // console.log(' ERROR reloading data: ' + body)
1228
+ callbackFunction(false, 'Error reloading data: ' + body, response); //@ts-ignore Where does onErrorWasCalled come from?
1229
+ } else if (response.onErrorWasCalled || response.status !== 200) {
1230
+ // console.log(' Non-HTTP error reloading data! onErrorWasCalled=' +
1231
+ //@ts-ignore Where does onErrorWasCalled come from?
1232
+ // response.onErrorWasCalled + ' status: ' + response.status)
1233
+ callbackFunction(false, 'Non-HTTP error reloading data: ' + body, response);
1234
+ } else {
1235
+ var elapsedTimeMs = Date.now() - startTime;
1236
+ if (!doc.reloadTimeTotal) doc.reloadTimeTotal = 0;
1237
+ if (!doc.reloadTimeCount) doc.reloadTimeCount = 0;
1238
+ doc.reloadTimeTotal += elapsedTimeMs;
1239
+ doc.reloadTimeCount += 1; // console.log(' Fetch took ' + elapsedTimeMs + 'ms, av. of ' +
1240
+ // doc.reloadTimeCount + ' = ' +
1241
+ // (doc.reloadTimeTotal / doc.reloadTimeCount) + 'ms.')
1242
+
1243
+ callbackFunction(true);
1244
+ }
1245
+ });
1246
+ }
1247
+ }]);
1248
+
1249
+ return UpdateManager;
1250
+ }();
1251
+
1252
+ export { UpdateManager as default };