terminusdb 12.0.2

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 (86) hide show
  1. package/Contributing.md +36 -0
  2. package/LICENSE +201 -0
  3. package/README.md +175 -0
  4. package/RELEASE_NOTES.md +462 -0
  5. package/dist/index.html +22 -0
  6. package/dist/terminusdb-client.min.js +3 -0
  7. package/dist/terminusdb-client.min.js.LICENSE.txt +188 -0
  8. package/dist/terminusdb-client.min.js.map +1 -0
  9. package/dist/typescript/index.d.ts +14 -0
  10. package/dist/typescript/lib/accessControl.d.ts +554 -0
  11. package/dist/typescript/lib/axiosInstance.d.ts +2 -0
  12. package/dist/typescript/lib/connectionConfig.d.ts +381 -0
  13. package/dist/typescript/lib/const.d.ts +54 -0
  14. package/dist/typescript/lib/dispatchRequest.d.ts +17 -0
  15. package/dist/typescript/lib/errorMessage.d.ts +25 -0
  16. package/dist/typescript/lib/query/woqlBuilder.d.ts +75 -0
  17. package/dist/typescript/lib/query/woqlCore.d.ts +341 -0
  18. package/dist/typescript/lib/query/woqlDoc.d.ts +63 -0
  19. package/dist/typescript/lib/query/woqlLibrary.d.ts +718 -0
  20. package/dist/typescript/lib/query/woqlPrinter.d.ts +71 -0
  21. package/dist/typescript/lib/query/woqlQuery.d.ts +833 -0
  22. package/dist/typescript/lib/typedef.d.ts +624 -0
  23. package/dist/typescript/lib/utils.d.ts +199 -0
  24. package/dist/typescript/lib/valueHash.d.ts +146 -0
  25. package/dist/typescript/lib/viewer/chartConfig.d.ts +62 -0
  26. package/dist/typescript/lib/viewer/chooserConfig.d.ts +38 -0
  27. package/dist/typescript/lib/viewer/documentFrame.d.ts +44 -0
  28. package/dist/typescript/lib/viewer/frameConfig.d.ts +74 -0
  29. package/dist/typescript/lib/viewer/frameRule.d.ts +145 -0
  30. package/dist/typescript/lib/viewer/graphConfig.d.ts +73 -0
  31. package/dist/typescript/lib/viewer/objectFrame.d.ts +212 -0
  32. package/dist/typescript/lib/viewer/streamConfig.d.ts +23 -0
  33. package/dist/typescript/lib/viewer/tableConfig.d.ts +66 -0
  34. package/dist/typescript/lib/viewer/terminusRule.d.ts +75 -0
  35. package/dist/typescript/lib/viewer/viewConfig.d.ts +47 -0
  36. package/dist/typescript/lib/viewer/woqlChart.d.ts +1 -0
  37. package/dist/typescript/lib/viewer/woqlChooser.d.ts +56 -0
  38. package/dist/typescript/lib/viewer/woqlGraph.d.ts +26 -0
  39. package/dist/typescript/lib/viewer/woqlPaging.d.ts +1 -0
  40. package/dist/typescript/lib/viewer/woqlResult.d.ts +128 -0
  41. package/dist/typescript/lib/viewer/woqlRule.d.ts +96 -0
  42. package/dist/typescript/lib/viewer/woqlStream.d.ts +31 -0
  43. package/dist/typescript/lib/viewer/woqlTable.d.ts +102 -0
  44. package/dist/typescript/lib/viewer/woqlView.d.ts +49 -0
  45. package/dist/typescript/lib/woql.d.ts +1267 -0
  46. package/dist/typescript/lib/woqlClient.d.ts +1216 -0
  47. package/index.js +28 -0
  48. package/lib/.eslintrc +1 -0
  49. package/lib/accessControl.js +988 -0
  50. package/lib/axiosInstance.js +5 -0
  51. package/lib/connectionConfig.js +765 -0
  52. package/lib/const.js +59 -0
  53. package/lib/dispatchRequest.js +236 -0
  54. package/lib/errorMessage.js +110 -0
  55. package/lib/query/woqlBuilder.js +234 -0
  56. package/lib/query/woqlCore.js +934 -0
  57. package/lib/query/woqlDoc.js +177 -0
  58. package/lib/query/woqlLibrary.js +1015 -0
  59. package/lib/query/woqlPrinter.js +476 -0
  60. package/lib/query/woqlQuery.js +1865 -0
  61. package/lib/typedef.js +248 -0
  62. package/lib/utils.js +817 -0
  63. package/lib/valueHash.js_old +581 -0
  64. package/lib/viewer/chartConfig.js +411 -0
  65. package/lib/viewer/chooserConfig.js +234 -0
  66. package/lib/viewer/documentFrame.js +206 -0
  67. package/lib/viewer/frameConfig.js +469 -0
  68. package/lib/viewer/frameRule.js +519 -0
  69. package/lib/viewer/graphConfig.js +345 -0
  70. package/lib/viewer/objectFrame.js +1550 -0
  71. package/lib/viewer/streamConfig.js +82 -0
  72. package/lib/viewer/tableConfig.js +310 -0
  73. package/lib/viewer/terminusRule.js +196 -0
  74. package/lib/viewer/viewConfig.js +219 -0
  75. package/lib/viewer/woqlChart.js +17 -0
  76. package/lib/viewer/woqlChooser.js +171 -0
  77. package/lib/viewer/woqlGraph.js +295 -0
  78. package/lib/viewer/woqlPaging.js +148 -0
  79. package/lib/viewer/woqlResult.js +258 -0
  80. package/lib/viewer/woqlRule.js +312 -0
  81. package/lib/viewer/woqlStream.js +27 -0
  82. package/lib/viewer/woqlTable.js +332 -0
  83. package/lib/viewer/woqlView.js +107 -0
  84. package/lib/woql.js +1693 -0
  85. package/lib/woqlClient.js +2091 -0
  86. package/package.json +110 -0
package/lib/const.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @file Terminus Constants
3
+ * @license Apache Version 2
4
+ * Constants representing API actions
5
+ */
6
+
7
+ module.exports = Object.freeze({
8
+ POST: 'POST',
9
+ GET: 'GET',
10
+ DELETE: 'DELETE',
11
+ PUT: 'PUT',
12
+ HEAD: 'HEAD',
13
+ QUERY_DOCUMENT: 'QUERY_DOCUMENT',
14
+ SQUASH_BRANCH: 'SQUASH_BRANCH',
15
+ UPDATE_SCHEMA: 'UPDATE_SCHEMA',
16
+ CONNECT: 'connect',
17
+ CREATE_DATABASE: 'create_database',
18
+ READ_DATABASE: 'read_database',
19
+ UPDATE_DATABASE: 'update_database',
20
+ CREATE_USER: 'create_user',
21
+ READ_USER: 'read_user',
22
+ UPDATE_USER: 'update_user',
23
+ CREATE_ORGANIZATION: 'create_organization',
24
+ READ_ORGANIZATION: 'read_organization',
25
+ UPDATE_ORGANIZATION: 'update_organization',
26
+ GET_ROLES: 'get_roles',
27
+ UPDATE_ROLES: 'update_roles',
28
+ CREATE_GRAPH: 'create_graph',
29
+ GET_TRIPLES: 'get_triples',
30
+ INSERT_TRIPLES: 'insert_triples',
31
+ UPDATE_TRIPLES: 'update_triples',
32
+ CLASS_FRAME: 'class_frame',
33
+ WOQL_QUERY: 'woql_query',
34
+ CLONE: 'clone',
35
+ CSV: 'csv',
36
+ WOQL: 'woql',
37
+ FRAME: 'frame',
38
+ PUSH: 'push',
39
+ PULL: 'pull',
40
+ FETCH: 'fetch',
41
+ REBASE: 'rebase',
42
+ RESET: 'reset',
43
+ BRANCH: 'branch',
44
+ REMOTE: 'remote',
45
+ CREATE_REMOTE: 'create_remote',
46
+ GET_REMOTE: 'get_remote',
47
+ UPDATE_REMOTE: 'update_remote',
48
+ DELETE_REMOTE: 'delete_remote',
49
+ RESET_BRANCH: 'reset_branch',
50
+ ADD_CSV: 'add_csv',
51
+ GET_CSV: 'get_csv',
52
+ UPDATE_CSV: 'update_csv',
53
+ MESSAGE: 'message',
54
+ ACTION: 'action',
55
+ INFO: 'info',
56
+ OPTIMIZE_SYSTEM: 'optimize_system',
57
+ GET_DIFF: 'getDiff',
58
+ PATCH: 'patch',
59
+ });
@@ -0,0 +1,236 @@
1
+ /* eslint-disable camelcase */
2
+ const pako = require('pako');
3
+ const axiosInstance = require('./axiosInstance');
4
+ const UTILS = require('./utils');
5
+ const CONST = require('./const');
6
+ const ErrorMessage = require('./errorMessage');
7
+ const { version } = require('../package.json');
8
+ // eslint-disable-next-line no-unused-vars
9
+ const typedef = require('./typedef');
10
+ /**
11
+ * base 64 encodes a string using either the btoa implementation if available or the Buffer object.
12
+ * @param {String} str string to be base 64 encoded
13
+ */
14
+ function btoaImplementation(str) {
15
+ try {
16
+ return btoa(str);
17
+ } catch (err) {
18
+ return Buffer.from(str).toString('base64');
19
+ }
20
+ }
21
+
22
+ /**
23
+ * @param {object} response
24
+ * @returns {object} Object having two properties result and dataVersion
25
+ */
26
+ function getResultWithDataVersion(response) {
27
+ return {
28
+ result: response.data,
29
+ dataVersion: response.headers['terminusdb-data-version']
30
+ ? response.headers['terminusdb-data-version']
31
+ : '',
32
+ };
33
+ }
34
+ /**
35
+ * Create the authorization header string
36
+ * @param {object} auth_obj
37
+ * @returns {object} Object with the Authorization header
38
+ */
39
+
40
+ function formatAuthHeader(auth_obj) {
41
+ if (!auth_obj) return '';
42
+ const authType = { jwt: 'Bearer', basic: 'Basic', apikey: 'Token' };
43
+ let auth_key = auth_obj.key;
44
+
45
+ if (auth_obj.type === 'basic') {
46
+ auth_key = btoaImplementation(`${auth_obj.user}:${auth_obj.key}`);
47
+ }
48
+ return `${authType[auth_obj.type]} ${auth_key}`;
49
+ }
50
+
51
+ function checkPayload(payload, options, compress) {
52
+ if (!payload || typeof payload !== 'object') return false;
53
+ const jsonStringPost = JSON.stringify(payload);
54
+ if (jsonStringPost && jsonStringPost.length > 1024 && compress) {
55
+ // eslint-disable-next-line no-param-reassign
56
+ options.headers['Content-Encoding'] = 'gzip';
57
+ return pako.gzip(jsonStringPost);
58
+ }
59
+ return false;
60
+ }
61
+
62
+ /**
63
+ * @file Dispatch Request
64
+ * @license Apache Version 2
65
+ * @description Functions for dispatching API requests via the axios library.
66
+ * @param {string} url API endpoint URL
67
+ * @param {string} action API action
68
+ * @param {object} payload data to be transmitted to endpoint
69
+ * @param {typedef.CredentialObj} local_auth the local authorization object
70
+ * @param {typedef.CredentialObj} remote_auth the remote authoriuzation object
71
+ * @param {object} customHeaders all the custom header to add to your call
72
+ * @param {boolean} [getDataVersion] If true the function will return object having result
73
+ * and dataVersion.
74
+ * @param {boolean} [compress] If true, compress the data with gzip if its size is bigger than 1024
75
+ */
76
+
77
+ // eslint-disable-next-line max-len
78
+ function DispatchRequest(url, action, payload, local_auth, remote_auth = null, customHeaders = null, getDataVersion = false, compress = false) {
79
+ /*
80
+ *CORS is only required when trying to fetch data from a browser,
81
+ *as browsers by default will block requests to different origins
82
+ */
83
+ const options = {
84
+ mode: 'cors', // no-cors, cors, *same-origin
85
+ redirect: 'follow', // manual, *follow, error
86
+ referrer: 'client',
87
+ maxContentLength: Infinity,
88
+ maxBodyLength: Infinity,
89
+ headers: {},
90
+ // url:url,
91
+ // no-referrer, *client
92
+ };
93
+ // Only allow self signed certs on 127.0.0.1
94
+ // and on node
95
+ if (url.startsWith('https://127.0.0.1') && typeof window === 'undefined') {
96
+ // eslint-disable-next-line global-require
97
+ const https = require('https');
98
+ const agent = new https.Agent({
99
+ rejectUnauthorized: false,
100
+ });
101
+ options.httpsAgent = agent;
102
+ }
103
+
104
+ /*
105
+ * I can call the local database using the local authorization key or
106
+ * a jwt token
107
+ */
108
+ /* if (local_auth && local_auth.type === 'basic') {
109
+ const encoded = btoaImplementation(`${local_auth.user}:${local_auth.key}`);
110
+ options.headers = { Authorization: `Basic ${encoded}` };
111
+ } else if (local_auth && local_auth.type === 'jwt') {
112
+ options.headers = { Authorization: `Bearer ${local_auth.key}` };
113
+ } else if (local_auth && local_auth.type === 'apikey') {
114
+ options.headers = { Authorization: `Token ${local_auth.key}` };
115
+ } */
116
+ /*
117
+ * I can call the local database or a custom installation using the local authorization key or
118
+ * I Can call TerminusX using the jwt token or an apiToken
119
+ */
120
+ if (local_auth && typeof local_auth === 'object') {
121
+ options.headers.Authorization = formatAuthHeader(local_auth);
122
+ }
123
+
124
+ /*
125
+ * pass the Authorization information of another
126
+ * terminusdb server to the local terminusdb
127
+ * for authentication you can use jwt or the apiKey token in TerminusX or
128
+ * the Basic autentication if is allowed in the custom server
129
+ */
130
+ if (remote_auth && typeof remote_auth === 'object') {
131
+ options.headers['Authorization-Remote'] = formatAuthHeader(remote_auth);
132
+ }
133
+
134
+ if (customHeaders && typeof customHeaders === 'object') {
135
+ // eslint-disable-next-line array-callback-return
136
+ Object.keys(customHeaders).map((key) => {
137
+ options.headers[key] = customHeaders[key];
138
+ });
139
+ }
140
+
141
+ if (typeof window === 'undefined') {
142
+ options.headers['User-Agent'] = `terminusdb-client-js/${version}`;
143
+ }
144
+
145
+ switch (action) {
146
+ case CONST.DELETE: {
147
+ if (payload) {
148
+ options.headers = options.headers ? options.headers : {};
149
+ options.headers['Content-Type'] = 'application/json; charset=utf-8';
150
+ options.data = payload;
151
+ }
152
+ return axiosInstance
153
+ .delete(url, options)
154
+ .then((response) => (getDataVersion ? getResultWithDataVersion(response) : response.data))
155
+ .catch((err) => {
156
+ throw ErrorMessage.apiErrorFormatted(url, options, err);
157
+ });
158
+ }
159
+ case CONST.HEAD: {
160
+ return axiosInstance
161
+ .head(url, options)
162
+ .then((response) => (getDataVersion ? getResultWithDataVersion(response) : response.data))
163
+ .catch((err) => {
164
+ throw ErrorMessage.apiErrorFormatted(url, options, err);
165
+ });
166
+ }
167
+ case CONST.GET: {
168
+ if (payload) {
169
+ const ext = UTILS.URIEncodePayload(payload);
170
+ // eslint-disable-next-line no-param-reassign
171
+ if (ext) url += `?${ext}`;
172
+ }
173
+ return axiosInstance
174
+ .get(url, options)
175
+ .then((response) => {
176
+ const r = getDataVersion ? getResultWithDataVersion(response) : response.data;
177
+ return r;
178
+ })
179
+ .catch((err) => {
180
+ throw ErrorMessage.apiErrorFormatted(url, options, err);
181
+ });
182
+ }
183
+ case CONST.ADD_CSV:
184
+ case CONST.INSERT_TRIPLES: {
185
+ options.headers = options.headers ? options.headers : {};
186
+ options.headers['Content-Type'] = 'application/form-data; charset=utf-8';
187
+ return axiosInstance
188
+ .put(url, payload, options)
189
+ .then((response) => (getDataVersion ? getResultWithDataVersion(response) : response.data))
190
+ .catch((err) => {
191
+ throw ErrorMessage.apiErrorFormatted(url, options, err);
192
+ });
193
+ }
194
+ case CONST.PUT: {
195
+ options.headers = options.headers ? options.headers : {};
196
+ options.headers['Content-Type'] = 'application/json; charset=utf-8';
197
+ let compressedContent = null;
198
+ const jsonString = JSON.stringify(payload);
199
+
200
+ if (jsonString.length > 1024 && compress) {
201
+ options.headers['Content-Encoding'] = 'gzip';
202
+ compressedContent = pako.gzip(jsonString);
203
+ }
204
+ return axiosInstance
205
+ .put(url, compressedContent || payload, options)
206
+ .then((response) => (getDataVersion ? getResultWithDataVersion(response) : response.data))
207
+ .catch((err) => {
208
+ throw ErrorMessage.apiErrorFormatted(url, options, err);
209
+ });
210
+ }
211
+ case CONST.QUERY_DOCUMENT: {
212
+ options.headers = options.headers ? options.headers : {};
213
+ options.headers['X-HTTP-Method-Override'] = 'GET';
214
+ // eslint-disable-next-line no-fallthrough
215
+ }
216
+ // eslint-disable-next-line no-fallthrough
217
+ default: {
218
+ options.headers = options.headers ? options.headers : {};
219
+ if (!options.headers['content-type'] && !options.headers['Content-Type']) {
220
+ options.headers['Content-Type'] = 'application/json; charset=utf-8';
221
+ }
222
+ const compressedContentPost = checkPayload(payload, options, compress);
223
+ return axiosInstance
224
+ .post(url, compressedContentPost || payload || {}, options)
225
+ .then((response) => {
226
+ const r = getDataVersion ? getResultWithDataVersion(response) : response.data;
227
+ return r;
228
+ })
229
+ .catch((err) => {
230
+ throw ErrorMessage.apiErrorFormatted(url, options, err);
231
+ });
232
+ }
233
+ }
234
+ }
235
+
236
+ module.exports = DispatchRequest;
@@ -0,0 +1,110 @@
1
+ /* eslint-disable no-restricted-syntax */
2
+ /* eslint-disable prefer-destructuring */
3
+ /* eslint-disable no-use-before-define */
4
+ /* eslint-disable no-param-reassign */
5
+ function getErrorAsMessage(url, api, err) {
6
+ let str = '';
7
+ if (err.response) {
8
+ err = err.response;
9
+ if (err.data) str += `${formatErrorMessage(err.data)}`;
10
+ } else if (err.body) str += `${formatErrorMessage(err.body)}`;
11
+ url = url.split('?')[0];
12
+
13
+ if (err.status) str += `Code: ${err.status}`;
14
+ if (err.action) str += ` Action: ${err.action}`;
15
+ if (err.type) str += ` Type: ${err.type}`;
16
+ if (url) str += ` url: ${url}`;
17
+ if (api && api.method) str += ` method: ${api.method}`;
18
+ if (err.stack) str = [str, err.stack].join('\n');
19
+ return str;
20
+ }
21
+
22
+ function formatErrorMessage(msg) {
23
+ if (typeof msg === 'object') {
24
+ let nmsg = '';
25
+ for (const key of Object.keys(msg)) {
26
+ if (msg[key] && typeof msg[key] !== 'object') nmsg += `${key} ${msg[key]} `;
27
+ }
28
+ return nmsg;
29
+ }
30
+ return msg;
31
+ }
32
+
33
+ function accessDenied(action, db, server) {
34
+ const err = {};
35
+ err.status = 403;
36
+ err.url = (server || '') + (db || '');
37
+ err.type = 'client';
38
+ err.action = action;
39
+ err.body = `${err.action} not permitted for ${err.url}`;
40
+ return err;
41
+ }
42
+
43
+ function getAPIErrorMessage(url, api, err) {
44
+ return `API Error ${getErrorAsMessage(url, api, err)}`;
45
+ }
46
+
47
+ function getAccessDeniedMessage(url, api, err) {
48
+ return `Access Denied ${getErrorAsMessage(url, api, err)}`;
49
+ }
50
+
51
+ function getInvalidURIMessage(url, call) {
52
+ const str = `Invalid argument to
53
+ ${call}.
54
+ ${url}
55
+ is not a valid Terminus DB API endpoint`;
56
+ return str;
57
+ }
58
+
59
+ function getInvalidParameterMessage(call, msg) {
60
+ const str = `Invalid Parameter to
61
+ ${call}.
62
+ ${msg}`;
63
+ return str;
64
+ }
65
+
66
+ /**
67
+ * Utility functions for generating and retrieving error messages
68
+ * and storing error state
69
+ */
70
+
71
+ function parseAPIError(response) {
72
+ const err = {};
73
+ err.status = response.status;
74
+ err.type = response.type;
75
+ if (response.data && typeof response.data === 'object') {
76
+ let msg;
77
+ try {
78
+ msg = response.text();
79
+ } catch (e) {
80
+ try {
81
+ msg = response.json();
82
+ } catch (error) {
83
+ msg = response.toString();
84
+ }
85
+ }
86
+ err.body = msg;
87
+ } else if (response.data) err.body = response.data;
88
+ err.url = response.url;
89
+ err.headers = response.headers;
90
+ err.redirected = response.redirected;
91
+ return err;
92
+ }
93
+
94
+ function apiErrorFormatted(url, options, err) {
95
+ const e = new Error(getAPIErrorMessage(url, options, err));
96
+ if (err.response && err.response.data) e.data = err.response.data;
97
+ if (err.response && err.response.status) e.status = err.response.status;
98
+ return e;
99
+ }
100
+
101
+ module.exports = {
102
+ apiErrorFormatted,
103
+ getErrorAsMessage,
104
+ getAPIErrorMessage,
105
+ getAccessDeniedMessage,
106
+ accessDenied,
107
+ getInvalidURIMessage,
108
+ getInvalidParameterMessage,
109
+ parseAPIError,
110
+ };
@@ -0,0 +1,234 @@
1
+ /* eslint-disable guard-for-in */
2
+ /* eslint-disable no-restricted-syntax */
3
+ /* eslint-disable no-underscore-dangle */
4
+ /* eslint-disable no-self-assign */
5
+ /* eslint-disable camelcase */
6
+ /* eslint-disable no-param-reassign */
7
+ // WOQLQuery
8
+ /**
9
+ * module WOQLQuery
10
+ *
11
+ */
12
+
13
+ /**
14
+ * defines the internal functions of the woql query object - the
15
+ * language API is defined in WOQLQuery
16
+ * @module WOQLQuery
17
+ * @constructor
18
+ * @param {object} [query] json-ld query for initialisation
19
+ * @returns {WOQLQuery}
20
+ */
21
+
22
+ const WOQLQueryExt = require('./woqlQuery');
23
+
24
+ // eslint-disable-next-line no-unused-vars
25
+ const typedef = require('../typedef');
26
+ // const WOQLLibrary = require('./woqlLibrary');
27
+
28
+ class WOQLQuery extends WOQLQueryExt {
29
+ // eslint-disable-next-line no-useless-constructor
30
+ constructor(query) {
31
+ super(query);
32
+ }
33
+ }
34
+
35
+ // WOQLQuery.prototype.counter = 1;
36
+ /**
37
+ * @param {typedef.GraphRef} [Graph] - the resource identifier of a graph possible
38
+ * @param {string|Var} [Subj] - The IRI of a triple’s subject or a variable
39
+ * @param {string|Var} [Pred] - The IRI of a property or a variable
40
+ * @param {string|Var} [Obj] - The IRI of a node or a variable, or a literal
41
+ * @returns {WOQLQuery} - A WOQLQuery which contains the pattern matching expression
42
+ */
43
+ /**
44
+ * Simple composite functions which produce WOQL queries
45
+ */
46
+ WOQLQuery.prototype.star = function (Graph, Subj, Pred, Obj) {
47
+ Subj = Subj || 'v:Subject';
48
+ Pred = Pred || 'v:Predicate';
49
+ Obj = Obj || 'v:Object';
50
+ Graph = Graph || false;
51
+ if (Graph) {
52
+ return this.quad(Subj, Pred, Obj, Graph);
53
+ }
54
+ return this.triple(Subj, Pred, Obj);
55
+ };
56
+
57
+ /**
58
+ * @param {string|Var} [Subj] - The IRI of a triple’s subject or a variable
59
+ * @param {string|Var} [Pred] - The IRI of a property or a variable
60
+ * @param {string|Var} [Obj] - The IRI of a node or a variable, or a literal
61
+ * @param {typedef.GraphRef} [Graph] - the resource identifier of a graph possible
62
+ * @returns {WOQLQuery} - A WOQLQuery which contains the pattern matching expression
63
+ */
64
+
65
+ WOQLQuery.prototype.all = function (Subj, Pred, Obj, Graph) {
66
+ return this.star(Graph, Subj, Pred, Obj);
67
+ };
68
+
69
+ /**
70
+ * @param {string} s
71
+ * @returns {object}
72
+ */
73
+
74
+ WOQLQuery.prototype.string = function (s) {
75
+ return { '@type': 'xsd:string', '@value': String(s) };
76
+ };
77
+
78
+ /**
79
+ * @param {boolean} tf
80
+ * @returns {object}
81
+ */
82
+
83
+ WOQLQuery.prototype.boolean = function (tf) {
84
+ tf = tf || false;
85
+ return this.literal(tf, 'boolean');
86
+ };
87
+
88
+ /**
89
+ * @param {any} s - the value of the literal
90
+ * @param {string} t - the type of the literal, e.g. 'xsd:string', 'xsd:boolean'
91
+ * @returns {object} - a WOQL DataValue object with the given type and value
92
+ */
93
+ WOQLQuery.prototype.literal = function (s, t) {
94
+ t = t.indexOf(':') === -1 ? `xsd:${t}` : t;
95
+ return { '@type': t, '@value': s };
96
+ };
97
+
98
+ /**
99
+ * @param {string} s
100
+ * @returns {object}
101
+ */
102
+
103
+ WOQLQuery.prototype.iri = function (s) {
104
+ return {
105
+ '@type': 'NodeValue',
106
+ node: s,
107
+ };
108
+ };
109
+
110
+ /**
111
+ * Update a pattern matching rule for the triple (Subject, Predicate, oldObjValue) with the
112
+ * new one (Subject, Predicate, newObjValue)
113
+ * @param {string|Var} subject - The IRI of a triple’s subject or a variable
114
+ * @param {string|Var} predicate - The IRI of a property or a variable
115
+ * @param {string|Var} newObjValue - The value to update or a literal
116
+ * @param {string|Var} oldObjValue - The old value of the object
117
+ * @returns {WOQLQuery} A WOQLQuery which contains the a Update Triple Statement
118
+ */
119
+
120
+ WOQLQuery.prototype.update_triple = function (subject, predicate, newObjValue, oldObjValue) {
121
+ const tmp_name = oldObjValue || `v:AnyObject__${this.counter += 1}`;
122
+ return this.and(
123
+ new WOQLQuery().opt(
124
+ new WOQLQuery()
125
+ .triple(subject, predicate, tmp_name)
126
+ .delete_triple(subject, predicate, tmp_name)
127
+ .not()
128
+ .triple(subject, predicate, newObjValue),
129
+ ),
130
+ new WOQLQuery().add_triple(subject, predicate, newObjValue),
131
+ );
132
+ };
133
+
134
+ /**
135
+ * @description Update a pattern matching rule for the quad [S, P, O, G]
136
+ * (Subject, Predicate, Object, Graph)
137
+ * @param {string} subject - The IRI of a triple’s subject or a variable
138
+ * @param {string} predicate - The IRI of a property or a variable
139
+ * @param {string} newObject - The value to update or a literal
140
+ * @param {string} graph - the resource identifier of a graph possible value are
141
+ * schema/{main - myschema - *} | instance/{main - myschema - *} | inference/{main - myschema - *}
142
+ * @returns {WOQLQuery} A WOQLQuery which contains the a Update Quad Statement
143
+ */
144
+
145
+ WOQLQuery.prototype.update_quad = function (subject, predicate, newObject, graph) {
146
+ const tmp_name = `v:AnyObject__${this.counter += 1}`;
147
+ return this.and(
148
+ new WOQLQuery().opt(
149
+ new WOQLQuery()
150
+ .quad(subject, predicate, tmp_name, graph)
151
+ .delete_quad(subject, predicate, tmp_name, graph)
152
+ .not()
153
+ .quad(subject, predicate, newObject, graph),
154
+ ),
155
+ new WOQLQuery().add_quad(subject, predicate, newObject, graph),
156
+ );
157
+ };
158
+
159
+ /**
160
+ * Deletes all triples in the passed graph (defaults to instance/main)
161
+ * @param {typedef.GraphRef} [graphRef] - Resource String identifying the graph from
162
+ * which all triples will be removed
163
+ * @returns {WOQLQuery} - A WOQLQuery which contains the deletion expression
164
+ */
165
+
166
+ WOQLQuery.prototype.nuke = function (graphRef) {
167
+ if (graphRef) {
168
+ return this.quad('v:A', 'v:B', 'v:C', graphRef).delete_quad('v:A', 'v:B', 'v:C', graphRef);
169
+ }
170
+ return this.triple('v:A', 'v:B', 'v:C').delete_triple('v:A', 'v:B', 'v:C');
171
+ };
172
+
173
+ /**
174
+ * @param {string|Var} node - The IRI of a node or a variable containing an IRI which will
175
+ * be the subject of the builder functions
176
+ * @param {typedef.FuntionType} [type] - Optional type of builder function to build
177
+ * (default is triple)
178
+ * @returns {WOQLQuery} - A WOQLQuery which contains the partial Node pattern matching expression
179
+ */
180
+
181
+ WOQLQuery.prototype.node = function (node, type) {
182
+ type = type || false;
183
+ if (type === 'add_quad') type = 'AddTriple';
184
+ else if (type === 'delete_quad') type = 'DeleteTriple';
185
+ else if (type === 'add_triple') type = 'AddTriple';
186
+ else if (type === 'delete_triple') type = 'DeleteTriple';
187
+ else if (type === 'quad') type = 'Triple';
188
+ else if (type === 'triple') type = 'Triple';
189
+ if (type && type.indexOf(':') === -1) type = type;
190
+ const ctxt = { subject: node };
191
+ if (type) ctxt.action = type;
192
+ this._set_context(ctxt);
193
+ return this;
194
+ };
195
+
196
+ // do not remove
197
+ /**
198
+ * Sets the graph resource ID that will be used for subsequent chained function calls
199
+ * @param {typedef.GraphRef} [graphRef] Resource String identifying the graph which will
200
+ * be used for subsequent chained schema calls
201
+ * @returns {WOQLQuery} A WOQLQuery which contains the partial Graph pattern matching expression
202
+ */
203
+ WOQLQuery.prototype.graph = function (graphRef) {
204
+ return this._set_context({
205
+ graph: graphRef,
206
+ });
207
+ };
208
+ // do not remove
209
+ WOQLQuery.prototype._set_context = function (ctxt) {
210
+ if (!this.triple_builder_context) this.triple_builder_context = {};
211
+
212
+ for (const k in ctxt) {
213
+ this.triple_builder_context[k] = ctxt[k];
214
+ }
215
+
216
+ return this;
217
+ };
218
+
219
+ /**
220
+ * @param {string|Var} id - IRI string or variable containing
221
+ * @param {string|Var} type - IRI string or variable containing the IRI of the
222
+ * @param {typedef.GraphRef} [refGraph] - Optional Graph resource identifier
223
+ * @returns {WOQLQuery} A WOQLQuery which contains the insert expression
224
+ */
225
+
226
+ WOQLQuery.prototype.insert = function (id, type, refGraph) {
227
+ refGraph = refGraph || (this.triple_builder_context ? this.triple_builder_context.graph : false);
228
+ if (refGraph) {
229
+ return this.add_quad(id, 'rdf:type', `@schema:${type}`, refGraph);
230
+ }
231
+ return this.add_triple(id, 'rdf:type', `@schema:${type}`);
232
+ };
233
+
234
+ module.exports = WOQLQuery;