@secrez/fs 1.0.3 → 1.0.4

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.
package/src/Tree.js CHANGED
@@ -1,300 +1,319 @@
1
- const fs = require('fs-extra')
2
- const path = require('path')
3
- const Node = require('./Node')
4
- const {config, Entry, ConfigUtils} = require('@secrez/core')
5
- const Crypto = require('@secrez/crypto')
1
+ const fs = require("fs-extra");
2
+ const path = require("path");
3
+ const Node = require("./Node");
4
+ const { config, Entry, ConfigUtils } = require("@secrez/core");
5
+ const Crypto = require("@secrez/crypto");
6
6
 
7
7
  class Tree {
8
-
9
8
  constructor(secrez, datasetIndex = 0) {
10
-
11
- this.alerts = []
12
- if (secrez.constructor.name === 'Secrez') {
13
- let dataPath = secrez.config.dataPath
9
+ this.alerts = [];
10
+ if (secrez.constructor.name === "Secrez") {
11
+ let dataPath = secrez.config.dataPath;
14
12
  if (datasetIndex) {
15
- dataPath = ConfigUtils.setAndGetDataset(secrez.config, datasetIndex)
13
+ dataPath = ConfigUtils.setAndGetDataset(secrez.config, datasetIndex);
16
14
  }
17
- this.datasetIndex = datasetIndex
18
- this.secrez = secrez
19
- Node.setCache(secrez.cache)
20
- this.config = secrez.config
21
- this.dataPath = dataPath
22
- this.status = Tree.statutes.UNLOADED
23
- this.errors = []
24
- this.toBeDeleted = []
15
+ this.datasetIndex = datasetIndex;
16
+ this.secrez = secrez;
17
+ Node.setCache(secrez.cache);
18
+ this.config = secrez.config;
19
+ this.dataPath = dataPath;
20
+ this.status = Tree.statutes.UNLOADED;
21
+ this.errors = [];
22
+ this.toBeDeleted = [];
25
23
  } else {
26
- throw new Error('Tree requires a Secrez instance during construction')
24
+ throw new Error("Tree requires a Secrez instance during construction");
27
25
  }
28
26
  }
29
27
 
30
28
  async getAllFiles() {
31
- return (await fs.readdir(this.dataPath)).filter(file => !/^\./.test(file))
29
+ return (await fs.readdir(this.dataPath)).filter(
30
+ (file) => !/^\./.test(file)
31
+ );
32
32
  }
33
33
 
34
34
  async decryptSecret(file) {
35
35
  let entry = new Entry({
36
36
  encryptedName: file,
37
- preserveContent: true
38
- })
39
- if (file[file.length - 1] === '$') {
37
+ preserveContent: true,
38
+ });
39
+ if (file[file.length - 1] === "$") {
40
40
  // there is an extraName
41
- let content = await fs.readFile(path.join(this.dataPath, file), 'utf8')
42
- content = content.split('$')
41
+ let content = await fs.readFile(path.join(this.dataPath, file), "utf8");
42
+ content = content.split("$");
43
43
  entry.set({
44
- encryptedName: file.substring(0, 254) + content[1]
45
- })
44
+ encryptedName: file.substring(0, 254) + content[1],
45
+ });
46
46
  }
47
- return [entry, this.secrez.decryptEntry(entry)]
47
+ return [entry, this.secrez.decryptEntry(entry)];
48
48
  }
49
49
 
50
50
  async load() {
51
-
52
51
  if (this.status === Tree.statutes.LOADED) {
53
- return
52
+ return;
54
53
  }
55
54
 
56
- let files = await this.getAllFiles()
57
- let allIndexes = []
58
- let allSecrets = []
59
- let allNames = []
60
- let allTags = []
55
+ let files = await this.getAllFiles();
56
+ let allIndexes = [];
57
+ let allSecrets = [];
58
+ let allNames = [];
59
+ let allTags = [];
61
60
 
62
61
  for (let file of files) {
63
- let [entry, decryptedEntry] = await this.decryptSecret(file)
62
+ let [entry, decryptedEntry] = await this.decryptSecret(file);
64
63
  if (decryptedEntry.type === config.types.ROOT) {
65
- let content = await fs.readFile(path.join(this.dataPath, file), 'utf8')
64
+ let content = await fs.readFile(path.join(this.dataPath, file), "utf8");
66
65
  entry.set({
67
- encryptedContent: content.split('$')[0]
68
- })
69
- decryptedEntry = this.secrez.decryptEntry(entry)
70
- allIndexes.push(decryptedEntry)
66
+ encryptedContent: content.split("$")[0],
67
+ });
68
+ decryptedEntry = this.secrez.decryptEntry(entry);
69
+ allIndexes.push(decryptedEntry);
71
70
  } else if (decryptedEntry.type === config.types.TAGS) {
72
- allTags.push(decryptedEntry)
71
+ allTags.push(decryptedEntry);
73
72
  } else if (decryptedEntry.type === config.types.NAME) {
74
- allNames.push(decryptedEntry)
73
+ allNames.push(decryptedEntry);
75
74
  } else {
76
- allSecrets.push(decryptedEntry)
75
+ allSecrets.push(decryptedEntry);
77
76
  }
78
77
  }
79
78
 
80
79
  if (this.datasetIndex === 0) {
81
- this.name = 'main'
80
+ this.name = "main";
82
81
  } else if (this.datasetIndex === 1) {
83
- this.name = 'trash'
82
+ this.name = "trash";
84
83
  } else if (allNames.length) {
85
- allNames.sort(Node.sortEntry)
86
- this.name = allNames[0].name
84
+ allNames.sort(Node.sortEntry);
85
+ this.name = allNames[0].name;
87
86
  }
88
87
 
89
88
  if (allSecrets.length) {
90
- allSecrets.sort(Node.sortEntry)
89
+ allSecrets.sort(Node.sortEntry);
91
90
  if (!allIndexes.length) {
92
- this.root = Node.initGenericRoot()
93
- this.root.datasetIndex = this.datasetIndex
94
- this.workingNode = this.root
95
- this.alerts = ['A valid tree is missing.\nThe following entries have been recovered and put in the folder "/recovered":']
96
- .concat(await this.recoverUnlisted(allSecrets))
97
- await this.loadTags(allTags)
98
- await this.save()
91
+ this.root = Node.initGenericRoot();
92
+ this.root.datasetIndex = this.datasetIndex;
93
+ this.workingNode = this.root;
94
+ this.alerts = [
95
+ 'A valid tree is missing.\nThe following entries have been recovered and put in the folder "/recovered":',
96
+ ].concat(await this.recoverUnlisted(allSecrets));
97
+ await this.loadTags(allTags);
98
+ await this.save();
99
99
  } else {
100
+ allIndexes.sort(Node.sortEntry);
101
+ let allSecretsFiles = allSecrets.map((e) => e.encryptedName);
102
+ let json = JSON.parse(allIndexes[0].content);
103
+ this.root = Node.fromJSON(json, this.secrez, allSecretsFiles);
100
104
 
101
- allIndexes.sort(Node.sortEntry)
102
- let allSecretsFiles = allSecrets.map(e => e.encryptedName)
103
- let json = JSON.parse(allIndexes[0].content)
104
- this.root = Node.fromJSON(json, this.secrez, allSecretsFiles)
105
-
106
- this.root.datasetIndex = this.datasetIndex
107
- this.workingNode = this.root
105
+ this.root.datasetIndex = this.datasetIndex;
106
+ this.workingNode = this.root;
108
107
 
109
108
  // verify the tree
110
- let allFilesOnTree = Tree.getAllFilesOnTree(this.root).sort()
111
- const filesNotOnTree = []
109
+ let allFilesOnTree = Tree.getAllFilesOnTree(this.root).sort();
110
+ const filesNotOnTree = [];
112
111
  for (let i = 0; i < allSecretsFiles.length; i++) {
113
- let file = allSecretsFiles[i]
112
+ let file = allSecretsFiles[i];
114
113
  if (!allFilesOnTree.includes(file)) {
115
- filesNotOnTree.push(allSecrets[i])
114
+ filesNotOnTree.push(allSecrets[i]);
116
115
  }
117
116
  }
118
117
  if (filesNotOnTree.length) {
119
- let toBeRecovered = {}
120
- let recoveredEntries = []
118
+ let toBeRecovered = {};
119
+ let recoveredEntries = [];
121
120
  FOR: for (let i = 1; i < allIndexes.length; i++) {
122
- json = JSON.parse(allIndexes[i].content)
123
- let root = Node.fromJSON(json, this.secrez, allSecretsFiles)
124
- allFilesOnTree = Tree.getAllFilesOnTree(root).sort()
121
+ json = JSON.parse(allIndexes[i].content);
122
+ let root = Node.fromJSON(json, this.secrez, allSecretsFiles);
123
+ allFilesOnTree = Tree.getAllFilesOnTree(root).sort();
125
124
  for (let j = 0; j < filesNotOnTree.length; j++) {
126
- let f = filesNotOnTree[j]
125
+ let f = filesNotOnTree[j];
127
126
  if (allFilesOnTree.includes(f.encryptedName)) {
128
- let node = root.findChildById(f.id)
127
+ let node = root.findChildById(f.id);
129
128
  if (node) {
130
- let k = allSecretsFiles.indexOf(f.encryptedName)
131
- toBeRecovered[node.getPath()] = allSecrets[k]
132
- filesNotOnTree.splice(j, 1)
133
- j--
129
+ let k = allSecretsFiles.indexOf(f.encryptedName);
130
+ toBeRecovered[node.getPath()] = allSecrets[k];
131
+ filesNotOnTree.splice(j, 1);
132
+ j--;
134
133
  }
135
134
  }
136
135
  if (!files.length) {
137
- break FOR
136
+ break FOR;
138
137
  }
139
138
  }
140
139
  }
141
- let paths = Object.keys(toBeRecovered).sort()
140
+ let paths = Object.keys(toBeRecovered).sort();
142
141
  for (let p of paths) {
143
- let entry = toBeRecovered[p]
142
+ let entry = toBeRecovered[p];
144
143
  // it can generate duplicate names
145
- let parentPath = p.replace(/\/[^\\/]+$/, '')
144
+ let parentPath = p.replace(/\/[^\\/]+$/, "");
146
145
  if (parentPath) {
147
146
  // check if exists on with the same name
148
147
  // if so, the recovered one is trashed
149
148
  try {
150
- let parent = this.root.getChildFromPath(parentPath)
149
+ let parent = this.root.getChildFromPath(parentPath);
151
150
  if (parent) {
152
- entry.parent = parent
151
+ entry.parent = parent;
153
152
  if (await this.addAsChildOrVersion(parent, entry)) {
154
- recoveredEntries.push(p)
153
+ recoveredEntries.push(p);
155
154
  }
156
- continue
155
+ continue;
157
156
  }
158
- } catch (e) {
159
- }
157
+ } catch (e) {}
160
158
  }
161
- entry.parent = this.root
159
+ entry.parent = this.root;
162
160
  if (await this.addAsChildOrVersion(this.root, entry)) {
163
- recoveredEntries.push(p)
161
+ recoveredEntries.push(p);
164
162
  }
165
163
  }
166
164
  if (filesNotOnTree.length || recoveredEntries.length) {
167
- this.alerts = ['Some files/versions have been recovered:']
165
+ this.alerts = ["Some files/versions have been recovered:"];
168
166
  if (recoveredEntries.length) {
169
-
170
- for (let i=0;i<recoveredEntries.length;i++) {
167
+ for (let i = 0; i < recoveredEntries.length; i++) {
171
168
  if (!i) {
172
- continue
169
+ continue;
173
170
  }
174
- if (recoveredEntries[i-1].substring(0, recoveredEntries[i].length) === recoveredEntries[i]) {
175
- recoveredEntries.splice(i--,1)
171
+ if (
172
+ recoveredEntries[i - 1].substring(
173
+ 0,
174
+ recoveredEntries[i].length
175
+ ) === recoveredEntries[i]
176
+ ) {
177
+ recoveredEntries.splice(i--, 1);
176
178
  }
177
179
  }
178
180
 
179
- this.alerts = this.alerts.concat(this.optimizeResults(recoveredEntries))
181
+ this.alerts = this.alerts.concat(
182
+ this.optimizeResults(recoveredEntries)
183
+ );
180
184
  }
181
185
  if (filesNotOnTree.length) {
182
- this.alerts = this.alerts.concat(this.optimizeResults(await this.recoverUnlisted(filesNotOnTree)))
186
+ this.alerts = this.alerts.concat(
187
+ this.optimizeResults(await this.recoverUnlisted(filesNotOnTree))
188
+ );
183
189
  }
184
- await this.save()
190
+ await this.save();
185
191
  }
186
192
  }
187
193
 
188
194
  for (let i = 2; i < allIndexes.length; i++) {
189
- await fs.unlink(path.join(this.dataPath, allIndexes[i].encryptedName))
195
+ await fs.unlink(
196
+ path.join(this.dataPath, allIndexes[i].encryptedName)
197
+ );
190
198
  }
191
-
192
199
  }
193
- await this.loadTags(allTags)
200
+ await this.loadTags(allTags);
194
201
  } else {
195
- this.root = Node.initGenericRoot()
196
- this.root.datasetIndex = this.datasetIndex
197
- this.workingNode = this.root
198
- await this.loadTags()
202
+ this.root = Node.initGenericRoot();
203
+ this.root.datasetIndex = this.datasetIndex;
204
+ this.workingNode = this.root;
205
+ await this.loadTags();
199
206
  }
200
- this.status = Tree.statutes.LOADED
207
+ this.status = Tree.statutes.LOADED;
201
208
  }
202
209
 
203
210
  optimizeResults(entries) {
204
- entries.reverse()
205
- for (let i=0;i<entries.length;i++) {
211
+ entries.reverse();
212
+ for (let i = 0; i < entries.length; i++) {
206
213
  if (!i) {
207
- continue
214
+ continue;
208
215
  }
209
- if (entries[i-1].substring(0, entries[i].length) === entries[i]) {
210
- entries.splice(i--,1)
216
+ if (entries[i - 1].substring(0, entries[i].length) === entries[i]) {
217
+ entries.splice(i--, 1);
211
218
  }
212
219
  }
213
- return entries.reverse()
220
+ return entries.reverse();
214
221
  }
215
222
 
216
223
  datedName(prefix) {
217
- return prefix + '_' + (new Date()).toISOString().substring(0, 19).replace(/(T|:|-)/g, '')
224
+ return (
225
+ prefix +
226
+ "_" +
227
+ new Date()
228
+ .toISOString()
229
+ .substring(0, 19)
230
+ .replace(/(T|:|-)/g, "")
231
+ );
218
232
  }
219
233
 
220
234
  async recoverUnlisted(allSecrets) {
221
- let recName = this.datedName(this.config.specialName.RECOVERED)
222
- this.root.datasetIndex = this.datasetIndex
223
- this.workingNode = this.root
224
- let recoveredEntries = []
225
- let recovered
235
+ let recName = this.datedName(this.config.specialName.RECOVERED);
236
+ this.root.datasetIndex = this.datasetIndex;
237
+ this.workingNode = this.root;
238
+ let recoveredEntries = [];
239
+ let recovered;
226
240
  for (let entry of allSecrets) {
227
241
  if (!recovered) {
228
242
  try {
229
- recovered = await this.add(this.root, new Entry({
230
- name: recName,
231
- type: this.config.types.DIR
232
- }))
233
- } catch (e) {
234
- }
243
+ recovered = await this.add(
244
+ this.root,
245
+ new Entry({
246
+ name: recName,
247
+ type: this.config.types.DIR,
248
+ })
249
+ );
250
+ } catch (e) {}
235
251
  }
236
252
  if (entry.type === this.config.types.DIR && entry.name === recName) {
237
- await fs.unlink(path.join(this.dataPath, entry.encryptedName))
253
+ await fs.unlink(path.join(this.dataPath, entry.encryptedName));
238
254
  } else {
239
- entry.parent = recovered
255
+ entry.parent = recovered;
240
256
  try {
241
- recovered.getChildFromPath(entry.name)
242
- entry.name = await this.getVersionedBasename(`/${recName}/${entry.name}`)
243
- } catch (e) {
244
- }
245
- recovered.add(new Node(entry))
246
- recoveredEntries.push(`/${recName}/${entry.name}`)
257
+ recovered.getChildFromPath(entry.name);
258
+ entry.name = await this.getVersionedBasename(
259
+ `/${recName}/${entry.name}`
260
+ );
261
+ } catch (e) {}
262
+ recovered.add(new Node(entry));
263
+ recoveredEntries.push(`/${recName}/${entry.name}`);
247
264
  }
248
265
  }
249
- await this.save()
250
- return recoveredEntries
266
+ await this.save();
267
+ return recoveredEntries;
251
268
  }
252
269
 
253
270
  async addAsChildOrVersion(parent, entry) {
254
271
  // console.log(parent.getPath(), entry.name)
255
- let done = false
256
- let name = entry.name
257
- let existentChild = parent.findDirectChildByName(name, entry.id)
272
+ let done = false;
273
+ let name = entry.name;
274
+ let existentChild = parent.findDirectChildByName(name, entry.id);
258
275
  if (existentChild) {
259
276
  if (existentChild.type === entry.type) {
260
-
261
- let temporaryNode = new Node(entry)
277
+ let temporaryNode = new Node(entry);
262
278
  // if it is a dir, it has the same name, we don't need it. But
263
279
  if (Node.isFile(entry)) {
264
- let details = await this.getEntryDetails(existentChild)
265
- let tempDetails = await this.getEntryDetails(temporaryNode)
280
+ let details = await this.getEntryDetails(existentChild);
281
+ let tempDetails = await this.getEntryDetails(temporaryNode);
266
282
  if (details.content !== tempDetails.content) {
267
- entry.content = tempDetails.content
268
- existentChild.move(entry)
269
- done = true
283
+ entry.content = tempDetails.content;
284
+ existentChild.move(entry);
285
+ done = true;
270
286
  }
271
287
  }
272
- this.toBeDeleted.push(temporaryNode)
288
+ this.toBeDeleted.push(temporaryNode);
273
289
  } else {
274
- entry.name = await this.getVersionedBasename(existentChild.getPath())
275
- parent.add(new Node(entry))
276
- done = true
290
+ entry.name = await this.getVersionedBasename(existentChild.getPath());
291
+ parent.add(new Node(entry));
292
+ done = true;
277
293
  }
278
294
  } else {
279
- parent.add(new Node(entry))
280
- done = true
295
+ parent.add(new Node(entry));
296
+ done = true;
281
297
  }
282
- return done
298
+ return done;
283
299
  }
284
300
 
285
301
  async getEntryDetails(node, ts) {
286
- let content
302
+ let content;
287
303
  if (Node.isFile(node)) {
288
- content = node.getContent(ts)
289
- if (typeof content === 'undefined') {
304
+ content = node.getContent(ts);
305
+ if (typeof content === "undefined") {
290
306
  // must be read from disk
291
- let entry = node.getEntry(ts)
292
- let fullPath = this.getFullPath(entry)
293
- let [encryptedContent, extraName] = (await fs.readFile(fullPath, 'utf8')).split('$')
294
- entry.encryptedContent = encryptedContent
295
- entry.extraName = extraName
296
- let decryptedEntry = this.secrez.decryptEntry(entry)
297
- content = node.versions[ts ? ts : node.lastTs].content = decryptedEntry.content
307
+ let entry = node.getEntry(ts);
308
+ let fullPath = this.getFullPath(entry);
309
+ let [encryptedContent, extraName] = (
310
+ await fs.readFile(fullPath, "utf8")
311
+ ).split("$");
312
+ entry.encryptedContent = encryptedContent;
313
+ entry.extraName = extraName;
314
+ let decryptedEntry = this.secrez.decryptEntry(entry);
315
+ content = node.versions[ts ? ts : node.lastTs].content =
316
+ decryptedEntry.content;
298
317
  }
299
318
  }
300
319
  return {
@@ -302,359 +321,362 @@ class Tree {
302
321
  id: node.id,
303
322
  name: node.getName(ts),
304
323
  content,
305
- ts: ts || node.lastTs
306
- }
324
+ ts: ts || node.lastTs,
325
+ };
307
326
  }
308
327
 
309
328
  static getAllFilesOnTree(node) {
310
329
  // get all the version currently in the tree to check for anomalies
311
- let results = []
330
+ let results = [];
312
331
  if (node.versions) {
313
332
  for (let ts in node.versions) {
314
- let version = node.versions[ts]
333
+ let version = node.versions[ts];
315
334
  if (version.file) {
316
- results.push(version.file)
335
+ results.push(version.file);
317
336
  }
318
337
  }
319
338
  }
320
339
  if (node.children) {
321
340
  for (let id in node.children) {
322
- results = results.concat(Tree.getAllFilesOnTree(node.children[id]))
341
+ results = results.concat(Tree.getAllFilesOnTree(node.children[id]));
323
342
  }
324
343
  }
325
- return results
344
+ return results;
326
345
  }
327
346
 
328
- getNormalizedPath(p = '/') {
329
- p = p.replace(/^~+/, '~').replace(/^~\/+/, '/').replace(/~+/g, '')
347
+ getNormalizedPath(p = "/") {
348
+ p = p.replace(/^~+/, "~").replace(/^~\/+/, "/").replace(/~+/g, "");
330
349
  if (!p) {
331
- p = '/'
350
+ p = "/";
332
351
  }
333
- let resolvedDir = path.resolve(this.workingNode.getPath(), p)
334
- let normalized = path.normalize(resolvedDir)
335
- return normalized
352
+ let resolvedDir = path.resolve(this.workingNode.getPath(), p);
353
+ let normalized = path.normalize(resolvedDir);
354
+ return normalized;
336
355
  }
337
356
 
338
357
  async getVersionedBasename(p, node = this.root) {
339
- p = this.getNormalizedPath(p)
340
- let dir = path.dirname(p)
341
- let fn = path.basename(p)
342
- let ext = path.extname(p)
343
- let num = ''
358
+ p = this.getNormalizedPath(p);
359
+ let dir = path.dirname(p);
360
+ let fn = path.basename(p);
361
+ let ext = path.extname(p);
362
+ let num = "";
344
363
  if (ext) {
345
- fn = fn.replace(RegExp(ext.replace(/\./, '\\.') + '$'), '')
364
+ fn = fn.replace(RegExp(ext.replace(/\./, "\\.") + "$"), "");
346
365
  }
347
366
  if (/^\.\d+$/.test(ext)) {
348
- num = parseInt(ext.substring(1))
349
- ext = ''
367
+ num = parseInt(ext.substring(1));
368
+ ext = "";
350
369
  } else if (/\.\d+$/.test(fn)) {
351
- fn = fn.split('.')
352
- num = parseInt(fn[1])
353
- fn = fn[0]
354
- }
355
- fn = fn.split(/\.\d+$/)
356
- let name = fn + (num ? '.' + num : '') + ext
357
- let v = num || 2
358
- for (; ;) {
370
+ fn = fn.split(".");
371
+ num = parseInt(fn[1]);
372
+ fn = fn[0];
373
+ }
374
+ fn = fn.split(/\.\d+$/);
375
+ let name = fn + (num ? "." + num : "") + ext;
376
+ let v = num || 2;
377
+ for (;;) {
359
378
  try {
360
- node.getChildFromPath(path.join(dir, name))
361
- name = fn + '.' + (v++) + ext
379
+ node.getChildFromPath(path.join(dir, name));
380
+ name = fn + "." + v++ + ext;
362
381
  } catch (e) {
363
- return name
382
+ return name;
364
383
  }
365
384
  }
366
385
  }
367
386
 
368
-
369
387
  getFullPath(entry) {
370
- return path.join(this.dataPath, entry.encryptedName)
388
+ return path.join(this.dataPath, entry.encryptedName);
371
389
  }
372
390
 
373
391
  async unsaveEntry(entry) {
374
- let fullPath = this.getFullPath(entry)
392
+ let fullPath = this.getFullPath(entry);
375
393
  if (await fs.pathExists(fullPath)) {
376
- await fs.unlink(fullPath)
394
+ await fs.unlink(fullPath);
377
395
  }
378
396
  }
379
397
 
380
398
  async add(parent, entry, force) {
381
399
  /* istanbul ignore if */
382
400
  if (entry.id && !force) {
383
- throw new Error('A new entry cannot have a pre-existent id')
401
+ throw new Error("A new entry cannot have a pre-existent id");
384
402
  }
385
403
  if (!entry.id) {
386
- entry.set({id: Crypto.getRandomId(Node.getCache().list('id'))})
404
+ entry.set({ id: Crypto.getRandomId(Node.getCache().list("id")) });
387
405
  }
388
- entry.preserveContent = true
389
- entry = this.secrez.encryptEntry(entry)
406
+ entry.preserveContent = true;
407
+ entry = this.secrez.encryptEntry(entry);
390
408
  try {
391
- await this.saveEntry(entry)
392
- let node = new Node(entry, force)
393
- parent.add(node)
394
- await this.save()
395
- return node
409
+ await this.saveEntry(entry);
410
+ let node = new Node(entry, force);
411
+ parent.add(node);
412
+ await this.save();
413
+ return node;
396
414
  } catch (e) {
397
415
  /* istanbul ignore if */
398
416
  // eslint-disable-next-line no-constant-condition
399
417
  if (true) {
400
- await this.unsaveEntry(entry)
401
- throw e
418
+ await this.unsaveEntry(entry);
419
+ throw e;
402
420
  }
403
421
  }
404
422
  }
405
423
 
406
424
  async update(node, entry) {
407
-
408
425
  /* istanbul ignore if */
409
426
  if (!node || !entry) {
410
- throw new Error('A Node and an Entry are required')
427
+ throw new Error("A Node and an Entry are required");
411
428
  }
412
- entry.preserveContent = true
413
- entry = this.secrez.encryptEntry(entry)
429
+ entry.preserveContent = true;
430
+ entry = this.secrez.encryptEntry(entry);
414
431
  try {
415
- await this.saveEntry(entry)
416
- node.move(entry)
417
- await this.save()
418
- return node
432
+ await this.saveEntry(entry);
433
+ node.move(entry);
434
+ await this.save();
435
+ return node;
419
436
  } catch (e) {
420
437
  /* istanbul ignore if */
421
438
  // eslint-disable-next-line no-constant-condition
422
439
  if (true) {
423
- await this.unsaveEntry(entry)
424
- throw e
440
+ await this.unsaveEntry(entry);
441
+ throw e;
425
442
  }
426
443
  }
427
444
  }
428
445
 
429
446
  async saveEntry(entry) {
430
- let fullPath = this.getFullPath(entry)
447
+ let fullPath = this.getFullPath(entry);
431
448
  /* istanbul ignore if */
432
449
  if (await fs.pathExists(fullPath)) {
433
- throw new Error('File already exists')
450
+ throw new Error("File already exists");
434
451
  }
435
452
  let encryptedContent =
436
- entry.encryptedContent || entry.extraName
437
- ? (entry.encryptedContent || '') +
438
- (
439
- entry.extraName
440
- ? '$' + entry.extraName
441
- : ''
442
- )
443
- : ''
444
- await fs.writeFile(fullPath, encryptedContent)
445
- return entry
453
+ entry.encryptedContent || entry.extraName
454
+ ? (entry.encryptedContent || "") +
455
+ (entry.extraName ? "$" + entry.extraName : "")
456
+ : "";
457
+ await fs.writeFile(fullPath, encryptedContent);
458
+ return entry;
446
459
  }
447
460
 
448
461
  disableSave() {
449
- this.doNotSave = true
462
+ this.doNotSave = true;
450
463
  }
451
464
 
452
465
  isSaveEnabled() {
453
- return this.doNotSave ? false : true
466
+ return this.doNotSave ? false : true;
454
467
  }
455
468
 
456
469
  enableSave() {
457
- delete this.doNotSave
470
+ delete this.doNotSave;
458
471
  }
459
472
 
460
473
  async save() {
461
474
  if (this.doNotSave) {
462
475
  // used during imports with many entries, to optimize the performances
463
- return
476
+ return;
464
477
  }
465
- let rootEntry = this.root.getEntry()
478
+ let rootEntry = this.root.getEntry();
466
479
  if (this.previousRootEntry) {
467
- await this.unsaveEntry(this.previousRootEntry)
480
+ await this.unsaveEntry(this.previousRootEntry);
468
481
  }
469
482
  rootEntry.set({
470
483
  name: Crypto.getRandomBase58String(4),
471
- content: JSON.stringify(this.root.toCompressedJSON(null, null, await this.getAllFiles())),
472
- preserveContent: true
473
- })
474
- rootEntry = this.secrez.encryptEntry(rootEntry)
475
- await this.saveEntry(rootEntry)
476
- this.previousRootEntry = rootEntry
484
+ content: JSON.stringify(
485
+ this.root.toCompressedJSON(null, null, await this.getAllFiles())
486
+ ),
487
+ preserveContent: true,
488
+ });
489
+ rootEntry = this.secrez.encryptEntry(rootEntry);
490
+ await this.saveEntry(rootEntry);
491
+ this.previousRootEntry = rootEntry;
477
492
  }
478
493
 
479
494
  async loadTags(allTags = []) {
480
495
  if (allTags.length) {
481
- allTags = allTags.sort(Node.sortEntry)[0]
482
- let content = await fs.readFile(path.join(this.dataPath, allTags.encryptedName), 'utf8')
496
+ allTags = allTags.sort(Node.sortEntry)[0];
497
+ let content = await fs.readFile(
498
+ path.join(this.dataPath, allTags.encryptedName),
499
+ "utf8"
500
+ );
483
501
  allTags.set({
484
- encryptedContent: content.split('$')[0]
485
- })
486
- allTags = this.secrez.decryptEntry(allTags)
487
- allTags.content = JSON.parse(allTags.content)
488
- this.tags = allTags
502
+ encryptedContent: content.split("$")[0],
503
+ });
504
+ allTags = this.secrez.decryptEntry(allTags);
505
+ allTags.content = JSON.parse(allTags.content);
506
+ this.tags = allTags;
489
507
  } else {
490
508
  this.tags = new Entry({
491
509
  type: config.types.TAGS,
492
- content: {}
493
- })
510
+ content: {},
511
+ });
494
512
  }
495
513
  }
496
514
 
497
515
  async addTag(node, tags) {
498
- let content = this.tags.content
516
+ let content = this.tags.content;
499
517
  for (let tag of tags) {
500
518
  if (!content[tag]) {
501
- content[tag] = []
519
+ content[tag] = [];
502
520
  }
503
521
  if (!content[tag].includes(node.id)) {
504
- content[tag].push(node.id)
522
+ content[tag].push(node.id);
505
523
  }
506
- this.tagsChanged = true
524
+ this.tagsChanged = true;
507
525
  }
508
- await this.saveTags()
526
+ await this.saveTags();
509
527
  }
510
528
 
511
529
  getTags(node) {
512
- return this.reverseTags()[node.id] || []
530
+ return this.reverseTags()[node.id] || [];
513
531
  }
514
532
 
515
533
  async removeTag(node, tags) {
516
- let content = this.tags.content
534
+ let content = this.tags.content;
517
535
  for (let tag of tags) {
518
536
  if (content[tag].includes(node.id)) {
519
- content[tag] = content[tag].filter(e => e !== node.id)
520
- this.tagsChanged = true
537
+ content[tag] = content[tag].filter((e) => e !== node.id);
538
+ this.tagsChanged = true;
521
539
  }
522
540
  }
523
- await this.saveTags()
541
+ await this.saveTags();
524
542
  }
525
543
 
526
544
  listTags() {
527
- let result = []
528
- let tags = this.tags.content
545
+ let result = [];
546
+ let tags = this.tags.content;
529
547
  for (let t of Object.keys(tags).sort()) {
530
- result.push(`${t} (${tags[t].length})`)
548
+ result.push(`${t} (${tags[t].length})`);
531
549
  }
532
- return result.sort()
550
+ return result.sort();
533
551
  }
534
552
 
535
553
  getNodesByTag(list) {
536
- let result = []
537
- let tags = this.tags.content
538
- let tag = []
554
+ let result = [];
555
+ let tags = this.tags.content;
556
+ let tag = [];
539
557
  if (list.length === 1) {
540
- tag = tags[list[0]] || []
558
+ tag = tags[list[0]] || [];
541
559
  } else {
542
- let ttag = {}
560
+ let ttag = {};
543
561
  for (let l of list) {
544
- let tmp = this.tags.content[l] || []
562
+ let tmp = this.tags.content[l] || [];
545
563
  for (let id of tmp) {
546
- ttag[id] = true
564
+ ttag[id] = true;
547
565
  }
548
566
  }
549
- ttag = Object.keys(ttag)
567
+ ttag = Object.keys(ttag);
550
568
  FOR: for (let id of ttag) {
551
569
  for (let s of list) {
552
570
  if (!tags[s].includes(id)) {
553
- continue FOR
571
+ continue FOR;
554
572
  }
555
573
  }
556
- tag.push(id)
574
+ tag.push(id);
557
575
  }
558
576
  }
559
- let rev
577
+ let rev;
560
578
  for (let id of tag) {
561
579
  if (!rev) {
562
- rev = this.reverseTags()
580
+ rev = this.reverseTags();
563
581
  }
564
- let node = this.root.findChildById(id)
565
- result.push([node.getPath(), rev[id].sort().join(' ')])
582
+ let node = this.root.findChildById(id);
583
+ result.push([node.getPath(), rev[id].sort().join(" ")]);
566
584
  }
567
- return result
585
+ return result;
568
586
  }
569
587
 
570
588
  reverseTags() {
571
- let reverse = {}
589
+ let reverse = {};
572
590
  for (let t in this.tags.content) {
573
591
  for (let id of this.tags.content[t]) {
574
592
  if (!reverse[id]) {
575
- reverse[id] = []
593
+ reverse[id] = [];
576
594
  }
577
- reverse[id].push(t)
595
+ reverse[id].push(t);
578
596
  }
579
597
  }
580
- return reverse
598
+ return reverse;
581
599
  }
582
600
 
583
601
  async saveTags() {
584
602
  if (this.doNotSave || !this.tagsChanged) {
585
- return
603
+ return;
586
604
  }
587
- delete this.tagsChanged
588
- let tags = new Entry(this.tags)
605
+ delete this.tagsChanged;
606
+ let tags = new Entry(this.tags);
589
607
  if (this.previousTags) {
590
- await this.unsaveEntry(this.previousTags)
608
+ await this.unsaveEntry(this.previousTags);
591
609
  }
592
610
  tags.set({
593
611
  name: Crypto.getRandomBase58String(4),
594
612
  content: JSON.stringify(tags.content),
595
- preserveContent: true
596
- })
597
- tags = this.secrez.encryptEntry(tags)
598
- await this.saveEntry(tags, true)
599
- this.previousTags = tags
613
+ preserveContent: true,
614
+ });
615
+ tags = this.secrez.encryptEntry(tags);
616
+ await this.saveEntry(tags, true);
617
+ this.previousTags = tags;
600
618
  }
601
619
 
602
620
  validateDatasetName(name) {
603
621
  if (!/^[a-zA-Z]{1}\w{1,15}$/.test(name)) {
604
- throw new Error('Dataset name must be alphanumeric, start with a letter, and at most 16 characters long')
622
+ throw new Error(
623
+ "Dataset name must be alphanumeric, start with a letter, and at most 16 characters long"
624
+ );
605
625
  }
606
626
  }
607
627
 
608
628
  async nameDataset(name) {
609
629
  if ([0, 1].includes(this.datasetIndex)) {
610
- throw new Error('Main and trash dataset cannot be renamed')
630
+ throw new Error("Main and trash dataset cannot be renamed");
611
631
  }
612
- this.validateDatasetName(name)
632
+ this.validateDatasetName(name);
613
633
  if (name !== this.name) {
614
634
  let entry = new Entry({
615
635
  name,
616
636
  id: config.specialId.NAME,
617
- type: config.types.NAME
618
- })
619
- let encryptedEntry = this.secrez.encryptEntry(entry)
620
- await fs.writeFile(path.join(this.dataPath, encryptedEntry.encryptedName), '')
621
- this.name = name
637
+ type: config.types.NAME,
638
+ });
639
+ let encryptedEntry = this.secrez.encryptEntry(entry);
640
+ await fs.writeFile(
641
+ path.join(this.dataPath, encryptedEntry.encryptedName),
642
+ ""
643
+ );
644
+ this.name = name;
622
645
  }
623
646
  }
624
647
 
625
648
  async getAllDataFiles(node, files = []) {
626
649
  for (let ts in node.versions) {
627
- files.push(node.getFile(ts))
650
+ files.push(node.getFile(ts));
628
651
  }
629
652
  if (node.children) {
630
653
  for (let id in node.children) {
631
- await this.getAllDataFiles(node.children[id], files)
654
+ await this.getAllDataFiles(node.children[id], files);
632
655
  }
633
656
  }
634
- return files
657
+ return files;
635
658
  }
636
659
 
637
660
  async getName() {
638
- let files = (await fs.readdir(this.dataPath)).filter(file => RegExp(`^${this.config.types.NAME}`).test(file))
639
- let allNames = []
661
+ let files = (await fs.readdir(this.dataPath)).filter((file) =>
662
+ RegExp(`^${this.config.types.NAME}`).test(file)
663
+ );
664
+ let allNames = [];
640
665
  for (let file of files) {
641
666
  // eslint-disable-next-line no-unused-vars
642
- let [entry, decryptedEntry] = await this.decryptSecret(file)
643
- allNames.push(decryptedEntry)
667
+ let [entry, decryptedEntry] = await this.decryptSecret(file);
668
+ allNames.push(decryptedEntry);
644
669
  }
645
670
  // console.log(allNames)
646
- allNames.sort(Node.sortEntry)
647
- return allNames[0].name
671
+ allNames.sort(Node.sortEntry);
672
+ return allNames[0].name;
648
673
  }
649
-
650
674
  }
651
675
 
652
-
653
676
  Tree.statutes = {
654
677
  UNLOADED: 0,
655
678
  LOADED: 1,
656
- BROKEN: 2
657
- }
658
-
679
+ BROKEN: 2,
680
+ };
659
681
 
660
- module.exports = Tree
682
+ module.exports = Tree;