acebase-server 1.19.0 → 1.19.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 (57) hide show
  1. package/.eslintrc.json +49 -49
  2. package/.github/workflows/publish.yml +125 -0
  3. package/Dockerfile +26 -26
  4. package/LICENSE +21 -21
  5. package/bin/acebase-server.js +8 -8
  6. package/create-package-files.sh +25 -0
  7. package/dist/cjs/routes/data-exists.js +2 -2
  8. package/dist/cjs/routes/data-export.js +2 -2
  9. package/dist/cjs/routes/data-get.js +2 -2
  10. package/dist/cjs/routes/data-reflect.js +2 -2
  11. package/dist/cjs/routes/docs.js +1 -1
  12. package/dist/cjs/routes/meta-info.js +1 -1
  13. package/dist/esm/routes/data-exists.js +1 -2
  14. package/dist/esm/routes/data-export.js +1 -2
  15. package/dist/esm/routes/data-get.js +1 -1
  16. package/dist/esm/routes/data-reflect.js +1 -2
  17. package/dist/esm/routes/docs.js +1 -1
  18. package/dist/esm/routes/meta-info.js +1 -1
  19. package/package.json +6 -7
  20. package/release_notes.md +2 -0
  21. package/src/routes/auth-change-password.yaml +73 -73
  22. package/src/routes/auth-delete.yaml +77 -77
  23. package/src/routes/auth-forgot-password.yaml +49 -49
  24. package/src/routes/auth-reset-password.yaml +53 -53
  25. package/src/routes/auth-signin.yaml +129 -129
  26. package/src/routes/auth-signout.yaml +46 -46
  27. package/src/routes/auth-signup.yaml +135 -135
  28. package/src/routes/auth-state.yaml +28 -28
  29. package/src/routes/auth-update.yaml +151 -151
  30. package/src/routes/auth-verify-email.yaml +52 -52
  31. package/src/routes/data-exists.yaml +44 -44
  32. package/src/routes/data-export.yaml +63 -63
  33. package/src/routes/data-import.yaml +74 -74
  34. package/src/routes/data-index-create.yaml +105 -105
  35. package/src/routes/data-index-delete.yaml +51 -51
  36. package/src/routes/data-index-list.yaml +84 -84
  37. package/src/routes/data-query.yaml +165 -165
  38. package/src/routes/data-reflect.yaml +124 -124
  39. package/src/routes/data-schema-get.yaml +53 -53
  40. package/src/routes/data-schema-set.yaml +64 -64
  41. package/src/routes/data-schema-test.yaml +66 -66
  42. package/src/routes/data-schemas-list.yaml +41 -41
  43. package/src/routes/data-set.yaml +77 -77
  44. package/src/routes/data-sync-changes.yaml +66 -66
  45. package/src/routes/data-sync-mutations.yaml +66 -66
  46. package/src/routes/data-transaction-finish.yaml +82 -82
  47. package/src/routes/data-transaction-start.yaml +58 -58
  48. package/src/routes/data-update.yaml +77 -77
  49. package/src/routes/meta-info.yaml +40 -40
  50. package/src/routes/meta-ping.yaml +22 -22
  51. package/src/routes/meta-stats.yaml +40 -40
  52. package/src/routes/oauth2-init.yaml +62 -62
  53. package/src/routes/oauth2-refresh.yaml +64 -64
  54. package/src/routes/oauth2-signin.yaml +65 -65
  55. package/webmanager/acebase-client-browser.min.js +12 -12
  56. package/webmanager/index.html +271 -271
  57. package/webmanager/index.js +437 -437
@@ -1,437 +1,437 @@
1
- var connection = {
2
- dbname: 'none',
3
- username: 'anonymous',
4
- db: null,
5
- user: null,
6
- auth_token: '',
7
- };
8
-
9
- async function connect(dbname, username, password) {
10
- connection.db?.disconnect();
11
- const host = location.hostname, port = location.port, https = location.protocol === 'https:', rootPath = location.pathname.match(/^\/?(.*?)\/webmanager/)[1];
12
- connection.db = new AceBaseClient({ dbname, host, port, https, autoConnect: false, rootPath });
13
- await connection.db.connect(false);
14
- await connection.db.ready();
15
- connection.dbname = dbname;
16
- if (username) {
17
- // Only sign in when credentials are passed
18
- const signInDetails = await connection.db.auth.signIn(username, password);
19
- connection.user = signInDetails.user;
20
- connection.auth_token = signInDetails.accessToken;
21
- connection.username = (signInDetails && signInDetails.user.displayName) || username;
22
- }
23
- }
24
-
25
- function getChildPath (path, childKey) {
26
- const isIndex = typeof childKey === 'number';
27
- const trailPath = isIndex ? '[' + childKey + ']' : '/' + childKey;
28
- const childPath = path ? path + trailPath : childKey;
29
- return childPath;
30
- }
31
-
32
- function getPathKeys(path) {
33
- if (typeof path === 'undefined' || path.length === 0) { return []; }
34
- let keys = path.replace(/\[/g, '/[').split('/');
35
- keys.forEach((key, index) => {
36
- if (key.startsWith('[')) {
37
- keys[index] = parseInt(key.substr(1, key.length - 2));
38
- }
39
- });
40
- return keys;
41
- }
42
-
43
- /**
44
- *
45
- * @param {string} path
46
- * @param {(event: 'changed'|'removed'|'added', childRef) => any} callback
47
- */
48
- function subscribeToChildEvents(path, callback) {
49
- // Create 3 subscriptions, combine them into 1
50
- path = path || '';
51
- const ref = connection.db.ref(path);
52
-
53
- // Subscribe to events
54
- const changes = ref.on('notify_child_changed').subscribe(ref => callback('changed', ref));
55
- const adds = ref.on('notify_child_added').subscribe(ref => callback('added', ref));
56
- const removes = ref.on('notify_child_removed').subscribe(ref => callback('removed', ref));
57
-
58
- function stop() {
59
- // Unsubscribe
60
- changes.stop();
61
- adds.stop();
62
- removes.stop();
63
- }
64
-
65
- return { stop };
66
- }
67
-
68
- let currentPath = null;
69
- let currentPathSubscription = null;
70
- let currentPathIsArray = false;
71
- let lastMoreClickListener;
72
- function updateBrowsePath(path = '') {
73
-
74
- if (currentPath !== path) {
75
- if (currentPathSubscription) {
76
- // unsubscribe from previous subscription
77
- currentPathSubscription.stop();
78
- }
79
- currentPathSubscription = subscribeToChildEvents(path, (event, ref) => {
80
- // M.toast({ html: `Child "${ref.key}" ${event}` });
81
- clearErrors();
82
- if (event === 'removed') {
83
- removeNode({ key: ref.key });
84
- }
85
- else {
86
- ref.reflect('info', { child_limit: 0, child_skip: 0, impersonate: impersonatedUid })
87
- .then(event === 'changed' ? updateNode : addNode);
88
- }
89
- });
90
- }
91
- currentPath = path;
92
- const impersonatedUid = document.getElementById('impersonate_uid').value;
93
-
94
- const container = document.getElementById('browse_container');
95
- while (container.firstChild) {
96
- container.removeChild(container.firstChild);
97
- }
98
- const breadcrumbContainer = document.getElementById('browse_breadcrumb_container');
99
- while (breadcrumbContainer.firstChild) {
100
- breadcrumbContainer.removeChild(breadcrumbContainer.firstChild);
101
- }
102
-
103
- const pathKeys = getPathKeys(path);
104
- let parentPath = '';
105
- pathKeys.forEach(key => {
106
- const breadcrumbNode = document.createElement('a');
107
- breadcrumbNode.className = 'browse_breadcrumb_node';
108
- breadcrumbNode.textContent = key;
109
- let childPath = getChildPath(parentPath, key);
110
- breadcrumbNode.addEventListener('click', updateBrowsePath.bind(this, childPath));
111
- breadcrumbContainer.appendChild(breadcrumbNode);
112
- parentPath = childPath;
113
- });
114
-
115
- function createNode(nodeInfo) {
116
- const childElem = document.createElement('div');
117
- childElem.id = 'child_' + nodeInfo.key;
118
- childElem.classList.add('db_node');
119
- const isObjectOrArray = ['object', 'array'].includes(nodeInfo.type);
120
- const hasInlineValue = typeof nodeInfo.value !== 'undefined';
121
- if (isObjectOrArray && !hasInlineValue) {
122
- childElem.classList.add('db_node_expand');
123
- // add_box
124
- // indeterminate_check_box?
125
- const childPath = getChildPath(path, nodeInfo.key);
126
- childElem.addEventListener('click', updateBrowsePath.bind(this, childPath));
127
- }
128
-
129
- const nodeNameElem = document.createElement('span');
130
- nodeNameElem.className = 'db_node_name';
131
- nodeNameElem.textContent = nodeInfo.key;
132
- if (typeof nodeInfo.access === 'object') {
133
- nodeNameElem.classList.add('access_mode');
134
- nodeNameElem.classList.add(nodeInfo.access.read ? 'allow_read' : 'deny_read');
135
- nodeNameElem.classList.add(nodeInfo.access.write ? 'allow_write' : 'deny_write');
136
- }
137
- childElem.appendChild(nodeNameElem);
138
-
139
- if (hasInlineValue) {
140
- const nodeValueElem = document.createElement('span');
141
- nodeValueElem.className = 'db_node_inlinevalue';
142
- let displayValue = nodeInfo.value;
143
- if (nodeInfo.type === 'string') {
144
- displayValue = `"${displayValue}"`;
145
- }
146
- else if (nodeInfo.type === 'reference') {
147
- displayValue = `(ref to:) "${displayValue.path}"`;
148
- }
149
- else if (nodeInfo.type === 'date') {
150
- displayValue = new Date(displayValue).toString();
151
- }
152
- else if (nodeInfo.type === 'object') {
153
- displayValue = '{}';
154
- }
155
- else if (nodeInfo.type === 'array') {
156
- displayValue = '[]';
157
- }
158
- else if (nodeInfo.type === 'binary') {
159
- nodeValueElem.className = 'db_node_type';
160
- displayValue = nodeInfo.type; //'(binary value)';
161
- }
162
- nodeValueElem.textContent = displayValue;
163
- childElem.appendChild(nodeValueElem);
164
- }
165
- else if (!isObjectOrArray) {
166
- const canLoadValue = ['string','reference'].includes(nodeInfo.type);
167
- const nodeTypeElem = document.createElement(canLoadValue ? 'a' : 'span');
168
- nodeTypeElem.className = 'db_node_type';
169
- if (canLoadValue) { nodeTypeElem.classList.add('clickable'); }
170
- nodeTypeElem.textContent = nodeInfo.type;
171
- canLoadValue && nodeTypeElem.addEventListener('click', () => {
172
- // load and display value
173
- const childPath = getChildPath(path, nodeInfo.key);
174
- connection.db.ref(childPath).get(snap => {
175
- let val = snap.val();
176
- if (val === null) { val = 'null'; }
177
- else if (nodeInfo.type === 'string') { val = `"${val}"`; }
178
- else if (nodeInfo.type === 'reference') { val = `${val.path}`; }
179
-
180
- const nodeValueElem = document.createElement('span');
181
- nodeValueElem.className = 'db_node_inlinevalue';
182
- nodeValueElem.textContent = val;
183
-
184
- // replace node
185
- nodeTypeElem.parentElement.replaceChild(nodeValueElem, nodeTypeElem);
186
- });
187
- });
188
- childElem.appendChild(nodeTypeElem);
189
- }
190
-
191
- return childElem;
192
- }
193
-
194
- function addNode(nodeInfo, noFlash = false) {
195
- console.log(`Adding node ${nodeInfo.key}:`, nodeInfo);
196
- const childElem = createNode(nodeInfo);
197
- if (!noFlash) { childElem.classList.add('flash'); }
198
- container.appendChild(childElem);
199
- }
200
- function updateNode(nodeInfo) {
201
- const id = 'child_' + nodeInfo.key;
202
- const currentElem = document.getElementById(id);
203
- if (currentElem) { currentElem.id = 'prev_' + id; }
204
- const newElem = createNode(nodeInfo);
205
- newElem.classList.add('flash');
206
- if (currentElem) {
207
- container.replaceChild(newElem, currentElem);
208
- }
209
- else {
210
- container.appendChild(newElem);
211
- }
212
- }
213
- function removeNode(nodeInfo) {
214
- const id = 'child_' + nodeInfo.key;
215
- const currentElem = document.getElementById(id);
216
- currentElem && currentElem.remove();
217
- if (container.children.length === 0) {
218
- // Node is either gone or has no more children. Refresh info
219
- updateBrowsePath(path);
220
- }
221
- }
222
-
223
- function showError(message) {
224
- const errorElem = document.createElement('div');
225
- errorElem.className = 'error';
226
- errorElem.textContent = message;
227
- container.appendChild(errorElem);
228
- document.getElementById('browse_impersonate_access').className = '';
229
- document.getElementById('more_children').className = '';
230
- }
231
- function clearErrors() {
232
- container.querySelectorAll('div.error').forEach(elem => elem.remove());
233
- }
234
-
235
- let ref = path ? connection.db.ref(path) : connection.db.root;
236
- const limit = 100;
237
- async function getChildren(skip = 0) {
238
- try {
239
- // Load path children with reflect API
240
- const info = await ref.reflect('info', { child_limit: limit, child_skip: skip, impersonate: impersonatedUid });
241
-
242
- currentPathIsArray = info.type === 'array';
243
-
244
- if (info.impersonation) {
245
- const elem = document.getElementById('browse_impersonate_access');
246
- if (info.impersonation.read.allow && info.impersonation.write.allow) {
247
- elem.className = 'access_allow_read_write';
248
- }
249
- else if (info.impersonation.read.allow) {
250
- elem.className = 'access_allow_read';
251
- }
252
- else if (info.impersonation.write.allow) {
253
- elem.className = 'access_allow_write';
254
- }
255
- else {
256
- elem.className = 'access_deny';
257
- }
258
- }
259
- else {
260
- document.getElementById('browse_impersonate_access').className = '';
261
- }
262
-
263
- if (!info.exists) {
264
- return showError('node does not exist');
265
- }
266
- else if (info.children.list.length === 0) {
267
- showError('node has no children');
268
- }
269
-
270
- if (skip === 0 && !info.children.more) {
271
- // we've got all children, sort the list
272
- info.children.list.sort((a,b) => a.key < b.key ? -1 : 1);
273
- }
274
-
275
- // Add children
276
- info.children.list.forEach(childInfo => {
277
- addNode(childInfo, true);
278
- });
279
-
280
- // Is there more data?
281
- const moreElem = document.getElementById('more_children');
282
- moreElem.className = info.children.more ? 'visible' : '';
283
- const loadMoreElem = document.getElementById('load_more_children');
284
- lastMoreClickListener && loadMoreElem.removeEventListener('click', lastMoreClickListener);
285
- lastMoreClickListener = () => {
286
- getChildren(skip + limit);
287
- };
288
- loadMoreElem.addEventListener('click', lastMoreClickListener);
289
-
290
- // Enable export?
291
- const exportAvailable = ['object','array'].includes(info.type);
292
- const exportNode = document.getElementById('export_node');
293
- if (exportAvailable) { exportNode.classList.remove('hide'); }
294
- else { exportNode.classList.add('hide'); }
295
- }
296
- catch (err) {
297
- // Server error?
298
- showError('Error: ' + err.message);
299
- }
300
- }
301
- getChildren(0);
302
- }
303
-
304
- function setSpans(className, value) {
305
- const elems = document.getElementsByClassName(className);
306
- for (let i = 0; i < elems.length; i++) {
307
- elems.item(i).textContent = value;
308
- }
309
- }
310
-
311
- function connectionChanged(success) {
312
- if (!success) {
313
- return;
314
- }
315
- setSpans('connected_user', connection.username);
316
- setSpans('connected_db', connection.dbname);
317
-
318
- let tabs = M.Tabs.getInstance(document.getElementById('main_tabs'));
319
- tabs.select('browse');
320
-
321
- updateBrowsePath();
322
- }
323
-
324
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
325
- function impersonateUser() {
326
- // Called from index.html
327
- const impersonateElem = document.getElementById('impersonate_uid');
328
- let uid = window.prompt('Enter the user id (uid) to impersonate:', impersonateElem.value);
329
- let impersonating = false;
330
- if (uid === '') { uid = 'anonymous'; }
331
- if (uid) {
332
- impersonating = true;
333
- }
334
- impersonateElem.value = uid || '';
335
- document.getElementById('impersonate_disabled').style.display = impersonating ? 'none' : 'inline';
336
- document.getElementById('impersonate_enabled').style.display = impersonating ? 'inline' : 'none';
337
- setSpans('impersonate_uid_label', impersonateElem.value);
338
- updateBrowsePath(currentPath);
339
- }
340
-
341
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
342
- function specifyChildKey() {
343
- // Called from index.html
344
- let key = window.prompt('Enter the child key to browse to:', '');
345
- if (typeof key !== 'string') { return; }
346
- if (currentPathIsArray && /^[0-9]+$/.test(key)) {
347
- // index
348
- key = parseInt(key);
349
- }
350
- const targetPath = getChildPath(currentPath, key);
351
- updateBrowsePath(targetPath);
352
- }
353
-
354
- const connectButton = document.getElementById('connect_button');
355
- connectButton.addEventListener('click', async () => {
356
- const connectingLabel = document.getElementById('connecting');
357
- const successLabel = document.getElementById('connect_success');
358
- const failLabel = document.getElementById('connect_fail');
359
- const failReasonLabel = document.getElementById('fail_reason');
360
- successLabel.classList.add('hide');
361
- failLabel.classList.add('hide');
362
-
363
- const dbname = document.getElementById('dbname').value;
364
- const username = document.getElementById('username').value; //'admin'
365
- const password = document.getElementById('password').value;
366
-
367
- if (username !== 'admin') {
368
- M.toast({html: 'Sorry! Only the admin user can currently use this interface'});
369
- return;
370
- }
371
-
372
- try {
373
- connectButton.classList.add('disabled');
374
- connectingLabel.classList.remove('hide');
375
- await connect(dbname, username, password);
376
- successLabel.classList.remove('hide');
377
- connectionChanged(true);
378
- }
379
- catch (err) {
380
- failLabel.classList.remove('hide');
381
- failReasonLabel.textContent = err.message;
382
- connectionChanged(false);
383
- }
384
- finally {
385
- connectButton.classList.remove('disabled');
386
- connectingLabel.classList.add('hide');
387
- }
388
- });
389
-
390
- document.getElementById('browse_breadcrumb_root').addEventListener('click', () => {
391
- updateBrowsePath('');
392
- });
393
-
394
- document.getElementById('export_json').addEventListener('click', () => {
395
- // Will initiate a download:
396
- const url = `/export/${connection.dbname}/${currentPath}?format=json&auth_token=${connection.auth_token}`;
397
- window.location.href = url;
398
- });
399
-
400
- document.getElementById('edit_node').addEventListener('click', () => {
401
- document.getElementById('edit_form').classList.remove('hide');
402
- });
403
-
404
- document.getElementById('update_button').addEventListener('click', async () => {
405
- const textarea = document.getElementById('update_json');
406
- let json = textarea.value;
407
-
408
- try {
409
- // Check update value
410
- if (!json.startsWith('{') || !json.endsWith('}')) { throw new Error('Value must be json'); }
411
-
412
- // Parse object
413
- let updates = JSON.parse(json);
414
-
415
- // Allow passed data to be serialized by Transport.serialize2:
416
- // this allows dates etc to be used: { "created": { ".type": "date", ".val": "2022-05-31T16:52:51Z" } }
417
- updates = acebaseclient.Transport.deserialize2(updates);
418
-
419
- console.log(updates);
420
- if (typeof updates !== 'object') { throw new Error('value must be an object'); }
421
-
422
- // Update
423
- await connection.db.ref(currentPath).update(updates);
424
- }
425
- catch (err) {
426
- M.toast({ html: `Error: ${err.message}` });
427
- }
428
- });
429
-
430
- // TODO: create a stand-alone PWA (Ionic?) that has more functionality, such as:
431
- // - connecting to multiple servers
432
- // - edit data
433
- // - create (and store) queries on data
434
- // - monitoring
435
- // - editing rules
436
- // - managing users
437
- // - etc!
1
+ var connection = {
2
+ dbname: 'none',
3
+ username: 'anonymous',
4
+ db: null,
5
+ user: null,
6
+ auth_token: '',
7
+ };
8
+
9
+ async function connect(dbname, username, password) {
10
+ connection.db?.disconnect();
11
+ const host = location.hostname, port = location.port, https = location.protocol === 'https:', rootPath = location.pathname.match(/^\/?(.*?)\/webmanager/)[1];
12
+ connection.db = new AceBaseClient({ dbname, host, port, https, autoConnect: false, rootPath });
13
+ await connection.db.connect(false);
14
+ await connection.db.ready();
15
+ connection.dbname = dbname;
16
+ if (username) {
17
+ // Only sign in when credentials are passed
18
+ const signInDetails = await connection.db.auth.signIn(username, password);
19
+ connection.user = signInDetails.user;
20
+ connection.auth_token = signInDetails.accessToken;
21
+ connection.username = (signInDetails && signInDetails.user.displayName) || username;
22
+ }
23
+ }
24
+
25
+ function getChildPath (path, childKey) {
26
+ const isIndex = typeof childKey === 'number';
27
+ const trailPath = isIndex ? '[' + childKey + ']' : '/' + childKey;
28
+ const childPath = path ? path + trailPath : childKey;
29
+ return childPath;
30
+ }
31
+
32
+ function getPathKeys(path) {
33
+ if (typeof path === 'undefined' || path.length === 0) { return []; }
34
+ let keys = path.replace(/\[/g, '/[').split('/');
35
+ keys.forEach((key, index) => {
36
+ if (key.startsWith('[')) {
37
+ keys[index] = parseInt(key.substr(1, key.length - 2));
38
+ }
39
+ });
40
+ return keys;
41
+ }
42
+
43
+ /**
44
+ *
45
+ * @param {string} path
46
+ * @param {(event: 'changed'|'removed'|'added', childRef) => any} callback
47
+ */
48
+ function subscribeToChildEvents(path, callback) {
49
+ // Create 3 subscriptions, combine them into 1
50
+ path = path || '';
51
+ const ref = connection.db.ref(path);
52
+
53
+ // Subscribe to events
54
+ const changes = ref.on('notify_child_changed').subscribe(ref => callback('changed', ref));
55
+ const adds = ref.on('notify_child_added').subscribe(ref => callback('added', ref));
56
+ const removes = ref.on('notify_child_removed').subscribe(ref => callback('removed', ref));
57
+
58
+ function stop() {
59
+ // Unsubscribe
60
+ changes.stop();
61
+ adds.stop();
62
+ removes.stop();
63
+ }
64
+
65
+ return { stop };
66
+ }
67
+
68
+ let currentPath = null;
69
+ let currentPathSubscription = null;
70
+ let currentPathIsArray = false;
71
+ let lastMoreClickListener;
72
+ function updateBrowsePath(path = '') {
73
+
74
+ if (currentPath !== path) {
75
+ if (currentPathSubscription) {
76
+ // unsubscribe from previous subscription
77
+ currentPathSubscription.stop();
78
+ }
79
+ currentPathSubscription = subscribeToChildEvents(path, (event, ref) => {
80
+ // M.toast({ html: `Child "${ref.key}" ${event}` });
81
+ clearErrors();
82
+ if (event === 'removed') {
83
+ removeNode({ key: ref.key });
84
+ }
85
+ else {
86
+ ref.reflect('info', { child_limit: 0, child_skip: 0, impersonate: impersonatedUid })
87
+ .then(event === 'changed' ? updateNode : addNode);
88
+ }
89
+ });
90
+ }
91
+ currentPath = path;
92
+ const impersonatedUid = document.getElementById('impersonate_uid').value;
93
+
94
+ const container = document.getElementById('browse_container');
95
+ while (container.firstChild) {
96
+ container.removeChild(container.firstChild);
97
+ }
98
+ const breadcrumbContainer = document.getElementById('browse_breadcrumb_container');
99
+ while (breadcrumbContainer.firstChild) {
100
+ breadcrumbContainer.removeChild(breadcrumbContainer.firstChild);
101
+ }
102
+
103
+ const pathKeys = getPathKeys(path);
104
+ let parentPath = '';
105
+ pathKeys.forEach(key => {
106
+ const breadcrumbNode = document.createElement('a');
107
+ breadcrumbNode.className = 'browse_breadcrumb_node';
108
+ breadcrumbNode.textContent = key;
109
+ let childPath = getChildPath(parentPath, key);
110
+ breadcrumbNode.addEventListener('click', updateBrowsePath.bind(this, childPath));
111
+ breadcrumbContainer.appendChild(breadcrumbNode);
112
+ parentPath = childPath;
113
+ });
114
+
115
+ function createNode(nodeInfo) {
116
+ const childElem = document.createElement('div');
117
+ childElem.id = 'child_' + nodeInfo.key;
118
+ childElem.classList.add('db_node');
119
+ const isObjectOrArray = ['object', 'array'].includes(nodeInfo.type);
120
+ const hasInlineValue = typeof nodeInfo.value !== 'undefined';
121
+ if (isObjectOrArray && !hasInlineValue) {
122
+ childElem.classList.add('db_node_expand');
123
+ // add_box
124
+ // indeterminate_check_box?
125
+ const childPath = getChildPath(path, nodeInfo.key);
126
+ childElem.addEventListener('click', updateBrowsePath.bind(this, childPath));
127
+ }
128
+
129
+ const nodeNameElem = document.createElement('span');
130
+ nodeNameElem.className = 'db_node_name';
131
+ nodeNameElem.textContent = nodeInfo.key;
132
+ if (typeof nodeInfo.access === 'object') {
133
+ nodeNameElem.classList.add('access_mode');
134
+ nodeNameElem.classList.add(nodeInfo.access.read ? 'allow_read' : 'deny_read');
135
+ nodeNameElem.classList.add(nodeInfo.access.write ? 'allow_write' : 'deny_write');
136
+ }
137
+ childElem.appendChild(nodeNameElem);
138
+
139
+ if (hasInlineValue) {
140
+ const nodeValueElem = document.createElement('span');
141
+ nodeValueElem.className = 'db_node_inlinevalue';
142
+ let displayValue = nodeInfo.value;
143
+ if (nodeInfo.type === 'string') {
144
+ displayValue = `"${displayValue}"`;
145
+ }
146
+ else if (nodeInfo.type === 'reference') {
147
+ displayValue = `(ref to:) "${displayValue.path}"`;
148
+ }
149
+ else if (nodeInfo.type === 'date') {
150
+ displayValue = new Date(displayValue).toString();
151
+ }
152
+ else if (nodeInfo.type === 'object') {
153
+ displayValue = '{}';
154
+ }
155
+ else if (nodeInfo.type === 'array') {
156
+ displayValue = '[]';
157
+ }
158
+ else if (nodeInfo.type === 'binary') {
159
+ nodeValueElem.className = 'db_node_type';
160
+ displayValue = nodeInfo.type; //'(binary value)';
161
+ }
162
+ nodeValueElem.textContent = displayValue;
163
+ childElem.appendChild(nodeValueElem);
164
+ }
165
+ else if (!isObjectOrArray) {
166
+ const canLoadValue = ['string','reference'].includes(nodeInfo.type);
167
+ const nodeTypeElem = document.createElement(canLoadValue ? 'a' : 'span');
168
+ nodeTypeElem.className = 'db_node_type';
169
+ if (canLoadValue) { nodeTypeElem.classList.add('clickable'); }
170
+ nodeTypeElem.textContent = nodeInfo.type;
171
+ canLoadValue && nodeTypeElem.addEventListener('click', () => {
172
+ // load and display value
173
+ const childPath = getChildPath(path, nodeInfo.key);
174
+ connection.db.ref(childPath).get(snap => {
175
+ let val = snap.val();
176
+ if (val === null) { val = 'null'; }
177
+ else if (nodeInfo.type === 'string') { val = `"${val}"`; }
178
+ else if (nodeInfo.type === 'reference') { val = `${val.path}`; }
179
+
180
+ const nodeValueElem = document.createElement('span');
181
+ nodeValueElem.className = 'db_node_inlinevalue';
182
+ nodeValueElem.textContent = val;
183
+
184
+ // replace node
185
+ nodeTypeElem.parentElement.replaceChild(nodeValueElem, nodeTypeElem);
186
+ });
187
+ });
188
+ childElem.appendChild(nodeTypeElem);
189
+ }
190
+
191
+ return childElem;
192
+ }
193
+
194
+ function addNode(nodeInfo, noFlash = false) {
195
+ console.log(`Adding node ${nodeInfo.key}:`, nodeInfo);
196
+ const childElem = createNode(nodeInfo);
197
+ if (!noFlash) { childElem.classList.add('flash'); }
198
+ container.appendChild(childElem);
199
+ }
200
+ function updateNode(nodeInfo) {
201
+ const id = 'child_' + nodeInfo.key;
202
+ const currentElem = document.getElementById(id);
203
+ if (currentElem) { currentElem.id = 'prev_' + id; }
204
+ const newElem = createNode(nodeInfo);
205
+ newElem.classList.add('flash');
206
+ if (currentElem) {
207
+ container.replaceChild(newElem, currentElem);
208
+ }
209
+ else {
210
+ container.appendChild(newElem);
211
+ }
212
+ }
213
+ function removeNode(nodeInfo) {
214
+ const id = 'child_' + nodeInfo.key;
215
+ const currentElem = document.getElementById(id);
216
+ currentElem && currentElem.remove();
217
+ if (container.children.length === 0) {
218
+ // Node is either gone or has no more children. Refresh info
219
+ updateBrowsePath(path);
220
+ }
221
+ }
222
+
223
+ function showError(message) {
224
+ const errorElem = document.createElement('div');
225
+ errorElem.className = 'error';
226
+ errorElem.textContent = message;
227
+ container.appendChild(errorElem);
228
+ document.getElementById('browse_impersonate_access').className = '';
229
+ document.getElementById('more_children').className = '';
230
+ }
231
+ function clearErrors() {
232
+ container.querySelectorAll('div.error').forEach(elem => elem.remove());
233
+ }
234
+
235
+ let ref = path ? connection.db.ref(path) : connection.db.root;
236
+ const limit = 100;
237
+ async function getChildren(skip = 0) {
238
+ try {
239
+ // Load path children with reflect API
240
+ const info = await ref.reflect('info', { child_limit: limit, child_skip: skip, impersonate: impersonatedUid });
241
+
242
+ currentPathIsArray = info.type === 'array';
243
+
244
+ if (info.impersonation) {
245
+ const elem = document.getElementById('browse_impersonate_access');
246
+ if (info.impersonation.read.allow && info.impersonation.write.allow) {
247
+ elem.className = 'access_allow_read_write';
248
+ }
249
+ else if (info.impersonation.read.allow) {
250
+ elem.className = 'access_allow_read';
251
+ }
252
+ else if (info.impersonation.write.allow) {
253
+ elem.className = 'access_allow_write';
254
+ }
255
+ else {
256
+ elem.className = 'access_deny';
257
+ }
258
+ }
259
+ else {
260
+ document.getElementById('browse_impersonate_access').className = '';
261
+ }
262
+
263
+ if (!info.exists) {
264
+ return showError('node does not exist');
265
+ }
266
+ else if (info.children.list.length === 0) {
267
+ showError('node has no children');
268
+ }
269
+
270
+ if (skip === 0 && !info.children.more) {
271
+ // we've got all children, sort the list
272
+ info.children.list.sort((a,b) => a.key < b.key ? -1 : 1);
273
+ }
274
+
275
+ // Add children
276
+ info.children.list.forEach(childInfo => {
277
+ addNode(childInfo, true);
278
+ });
279
+
280
+ // Is there more data?
281
+ const moreElem = document.getElementById('more_children');
282
+ moreElem.className = info.children.more ? 'visible' : '';
283
+ const loadMoreElem = document.getElementById('load_more_children');
284
+ lastMoreClickListener && loadMoreElem.removeEventListener('click', lastMoreClickListener);
285
+ lastMoreClickListener = () => {
286
+ getChildren(skip + limit);
287
+ };
288
+ loadMoreElem.addEventListener('click', lastMoreClickListener);
289
+
290
+ // Enable export?
291
+ const exportAvailable = ['object','array'].includes(info.type);
292
+ const exportNode = document.getElementById('export_node');
293
+ if (exportAvailable) { exportNode.classList.remove('hide'); }
294
+ else { exportNode.classList.add('hide'); }
295
+ }
296
+ catch (err) {
297
+ // Server error?
298
+ showError('Error: ' + err.message);
299
+ }
300
+ }
301
+ getChildren(0);
302
+ }
303
+
304
+ function setSpans(className, value) {
305
+ const elems = document.getElementsByClassName(className);
306
+ for (let i = 0; i < elems.length; i++) {
307
+ elems.item(i).textContent = value;
308
+ }
309
+ }
310
+
311
+ function connectionChanged(success) {
312
+ if (!success) {
313
+ return;
314
+ }
315
+ setSpans('connected_user', connection.username);
316
+ setSpans('connected_db', connection.dbname);
317
+
318
+ let tabs = M.Tabs.getInstance(document.getElementById('main_tabs'));
319
+ tabs.select('browse');
320
+
321
+ updateBrowsePath();
322
+ }
323
+
324
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
325
+ function impersonateUser() {
326
+ // Called from index.html
327
+ const impersonateElem = document.getElementById('impersonate_uid');
328
+ let uid = window.prompt('Enter the user id (uid) to impersonate:', impersonateElem.value);
329
+ let impersonating = false;
330
+ if (uid === '') { uid = 'anonymous'; }
331
+ if (uid) {
332
+ impersonating = true;
333
+ }
334
+ impersonateElem.value = uid || '';
335
+ document.getElementById('impersonate_disabled').style.display = impersonating ? 'none' : 'inline';
336
+ document.getElementById('impersonate_enabled').style.display = impersonating ? 'inline' : 'none';
337
+ setSpans('impersonate_uid_label', impersonateElem.value);
338
+ updateBrowsePath(currentPath);
339
+ }
340
+
341
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
342
+ function specifyChildKey() {
343
+ // Called from index.html
344
+ let key = window.prompt('Enter the child key to browse to:', '');
345
+ if (typeof key !== 'string') { return; }
346
+ if (currentPathIsArray && /^[0-9]+$/.test(key)) {
347
+ // index
348
+ key = parseInt(key);
349
+ }
350
+ const targetPath = getChildPath(currentPath, key);
351
+ updateBrowsePath(targetPath);
352
+ }
353
+
354
+ const connectButton = document.getElementById('connect_button');
355
+ connectButton.addEventListener('click', async () => {
356
+ const connectingLabel = document.getElementById('connecting');
357
+ const successLabel = document.getElementById('connect_success');
358
+ const failLabel = document.getElementById('connect_fail');
359
+ const failReasonLabel = document.getElementById('fail_reason');
360
+ successLabel.classList.add('hide');
361
+ failLabel.classList.add('hide');
362
+
363
+ const dbname = document.getElementById('dbname').value;
364
+ const username = document.getElementById('username').value; //'admin'
365
+ const password = document.getElementById('password').value;
366
+
367
+ if (username !== 'admin') {
368
+ M.toast({html: 'Sorry! Only the admin user can currently use this interface'});
369
+ return;
370
+ }
371
+
372
+ try {
373
+ connectButton.classList.add('disabled');
374
+ connectingLabel.classList.remove('hide');
375
+ await connect(dbname, username, password);
376
+ successLabel.classList.remove('hide');
377
+ connectionChanged(true);
378
+ }
379
+ catch (err) {
380
+ failLabel.classList.remove('hide');
381
+ failReasonLabel.textContent = err.message;
382
+ connectionChanged(false);
383
+ }
384
+ finally {
385
+ connectButton.classList.remove('disabled');
386
+ connectingLabel.classList.add('hide');
387
+ }
388
+ });
389
+
390
+ document.getElementById('browse_breadcrumb_root').addEventListener('click', () => {
391
+ updateBrowsePath('');
392
+ });
393
+
394
+ document.getElementById('export_json').addEventListener('click', () => {
395
+ // Will initiate a download:
396
+ const url = `/export/${connection.dbname}/${currentPath}?format=json&auth_token=${connection.auth_token}`;
397
+ window.location.href = url;
398
+ });
399
+
400
+ document.getElementById('edit_node').addEventListener('click', () => {
401
+ document.getElementById('edit_form').classList.remove('hide');
402
+ });
403
+
404
+ document.getElementById('update_button').addEventListener('click', async () => {
405
+ const textarea = document.getElementById('update_json');
406
+ let json = textarea.value;
407
+
408
+ try {
409
+ // Check update value
410
+ if (!json.startsWith('{') || !json.endsWith('}')) { throw new Error('Value must be json'); }
411
+
412
+ // Parse object
413
+ let updates = JSON.parse(json);
414
+
415
+ // Allow passed data to be serialized by Transport.serialize2:
416
+ // this allows dates etc to be used: { "created": { ".type": "date", ".val": "2022-05-31T16:52:51Z" } }
417
+ updates = acebaseclient.Transport.deserialize2(updates);
418
+
419
+ console.log(updates);
420
+ if (typeof updates !== 'object') { throw new Error('value must be an object'); }
421
+
422
+ // Update
423
+ await connection.db.ref(currentPath).update(updates);
424
+ }
425
+ catch (err) {
426
+ M.toast({ html: `Error: ${err.message}` });
427
+ }
428
+ });
429
+
430
+ // TODO: create a stand-alone PWA (Ionic?) that has more functionality, such as:
431
+ // - connecting to multiple servers
432
+ // - edit data
433
+ // - create (and store) queries on data
434
+ // - monitoring
435
+ // - editing rules
436
+ // - managing users
437
+ // - etc!