-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
498 lines (408 loc) · 14.7 KB
/
index.js
File metadata and controls
498 lines (408 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
'use strict';
var Joi = require('joi');
var fs = require('fs-extra');
var _ = require('lodash');
var S = require('string');
var validator = require('is-my-json-valid');
var confSchema = Joi.object().keys({
schema: [Joi.string().min(2).description('json-schema file path'), Joi.object().description('json-schema content')],
tableFriendly: Joi.boolean().description('Output for help command is a list of records when true')
});
var isSchemaFile = function(value) {
return _.isString(value);
};
var isSchemaContent = function(value) {
return _.isPlainObject(value);
};
var recordAsString = function(value) {
return [value.name, value.description].join(': ');
};
var loadSchema = function(value) {
if (isSchemaContent(value)) {
return value;
} else
if (isSchemaFile(value)) {
return fs.readJsonSync(value);
} else {
throw new Error("Unknown schema " + value);
}
};
var hasProperties = function(obj) {
return (!_.isEmpty(obj.properties)) && ("object" === obj.type);
};
var hasItems = function(obj) {
return (!_.isEmpty(obj.items)) && ("array" === obj.type);
};
var addPath = function(parent, child) {
var childPath = _.clone(parent);
childPath.push(child);
return childPath;
};
var isStringProvided = function(value) {
if (!_.isString(value)) {
return false;
}
return (value.length > 0);
};
var asPropertyKey = function(pathArray) {
return pathArray.join(".").replace(".[]", "[]");
};
var copyProps = function(obj, name, pathArray) {
var props = {
name: name,
type: obj.type,
path: pathArray
};
if (isStringProvided(obj.title)) {
props.title = obj.title;
}
if (isStringProvided(obj.description)) {
props.description = obj.description;
}
return props;
};
var walkPaths = function(obj, pathsFound, parentPath) {
if (hasProperties(obj)) {
_.forIn(obj.properties, function(v, k) {
var propPath = addPath(parentPath, k);
pathsFound[asPropertyKey(propPath)] = copyProps(v, k, propPath);
walkPaths(v, pathsFound, propPath);
});
} else
if (hasItems(obj)) {
var arrayPath = addPath(parentPath, "[]");
pathsFound[asPropertyKey(arrayPath)] = copyProps(obj.items, "[]", arrayPath);
if (hasProperties(obj.items)) {
_.forIn(obj.items.properties, function(v, k) {
var propPath = addPath(arrayPath, k);
pathsFound[asPropertyKey(propPath)] = copyProps(v, k, propPath);
walkPaths(v, pathsFound, propPath);
});
}
} else {
//console.log("already processed?"+JSON.stringify(obj));
}
};
var simplifyPath = function(value) {
return value.replace(/\[\d+\]/g, "[]");
};
var getParentPath = function(path) {
var p = S(path);
var hasParent = p.contains('.') || p.contains('[');
if (!hasParent) {
return null;
}
if (p.endsWith(']')) {
return path.replace(/\[\d+\]$/, '');
}
return path.replace(/(\.[^.]+$)/, '');
};
var modelRowToHelpLineRecord = function(value) {
var noTitle = S(value.title).isEmpty();
var noDesc = S(value.description).isEmpty();
var name = asPropertyKey(value.path) + " (" + value.type + ")";
if (noTitle && noDesc) {
return {
name: name,
description: ""
};
}
var title = noTitle ? "" : S(value.title).capitalize().trim().ensureRight('.').s;
var desc = noDesc ? "" : S(value.description).capitalize().trim().ensureRight('.').s;
var description = S([title, desc].join(' ')).trim().s;
return {
name: name,
description: description
};
};
var modelRowToHelpLine = function(value) {
var row = modelRowToHelpLineRecord(value);
return S(row.description).isEmpty() ? row.name : [row.name, row.description].join(': ');
};
module.exports = function(config) {
Joi.assert(config, confSchema);
var schema = loadSchema(config.schema);
var pathsFound = {};
walkPaths(schema, pathsFound, []);
var modelHelp = function() {
return config.tableFriendly ? _.sortBy(_.map(_.values(pathsFound), modelRowToHelpLineRecord), 'name') :
_.map(_.values(pathsFound), modelRowToHelpLine).sort();
};
var idPathValid = function(path) {
var isSyntaxCorrect = (!isStringProvided(path)) || (path.indexOf('[]') >= 0);
if (isSyntaxCorrect) {
return false;
}
var search = simplifyPath(path);
return _.has(pathsFound, search);
};
var getTypeForPath = function(path) {
return pathsFound[simplifyPath(path)].type;
};
var isValueValid = function(path, value) {
var valueType = getTypeForPath(path);
var invalid = {
valid: false,
expected: valueType
};
if (_.isNull(value) || _.isUndefined(value)) {
return invalid;
}
if ((valueType === "string") && (!_.isString(value))) {
return invalid;
}
if ((valueType === "object") && (!_.isObject(value))) {
return invalid;
}
if ((valueType === "array") && (!_.isArray(value))) {
return invalid;
}
var s = S(value);
if (valueType === "boolean") {
if (isStringProvided(value)) {
var valueLower = value.toLowerCase();
var isBoolean = valueLower === 'true' || valueLower === 'false' || valueLower === 'yes' || valueLower === 'no' || valueLower === 'on' || valueLower === 'off';
if (!isBoolean) {
return invalid;
}
} else if (!_.isBoolean(value)) {
return invalid;
}
}
if (valueType === "number") {
if (isStringProvided(value)) {
if (!_.isFinite(s.toFloat())) {
return invalid;
}
} else if (!_.isNumber(value)) {
return invalid;
}
}
if (valueType === "integer") {
if (isStringProvided(value)) {
if (!_.isFinite(s.toInt())) {
return invalid;
}
} else if (!_.isNumber(value)) {
return invalid;
}
}
return {
valid: true,
expected: valueType
};
};
var getValue = function(jsonData, path) {
var isValid = idPathValid(path);
if (!isValid) {
return new Error('Given path is not valid:' + path);
}
return _.get(jsonData, path);
};
var setValueForType = function(jsonData, path, value) {
var childType = getTypeForPath(path);
switch (childType) {
case 'integer':
_.set(jsonData, path, S(value).toInt());
break;
case 'number':
_.set(jsonData, path, S(value).toFloat());
break;
case 'boolean':
_.set(jsonData, path, S(value).toBoolean());
break;
default:
_.set(jsonData, path, value);
}
};
var createEmpty = function(valueType) {
var value = "";
switch (valueType) {
case 'integer':
value = 0;
break;
case 'number':
value = 0;
break;
case 'string':
value = "";
break;
case 'object':
value = {};
break;
default:
throw new Error(valueType + 'not supported!');
}
return value;
};
var setValue = function(jsonData, path, value) {
var isValid = idPathValid(path);
if (!isValid) {
return new Error('Given path is not valid');
}
var isValueNotValid = !isValueValid(path, value);
if (isValueNotValid) {
return new Error('Value is not valid for path');
}
var parent = getParentPath(path);
if (_.isNull(parent)) {
setValueForType(jsonData, path, value);
} else {
var parentType = getTypeForPath(parent);
var isParentContainer = (parentType === 'object') || (parentType === 'array');
if (!isParentContainer) {
throw new Error('The parent should be a an object or an array');
}
var parentData = _.get(jsonData, path);
var isUndefinedAndArray = _.isUndefined(parentData) && (parent.indexOf('[') >= 0);
if (isUndefinedAndArray) {
return new Error('The parent object should be defined');
}
setValueForType(jsonData, path, value);
return jsonData;
}
};
var insertRow = function(jsonData, path, position) {
var isValid = idPathValid(path);
if (!isValid) {
return new Error('Given path is not valid');
}
var valueType = getTypeForPath(path);
if (valueType !== 'array') {
return new Error('This path is not array but ' + valueType);
}
var previousVal = _.get(jsonData, path);
if (_.isEmpty(previousVal)) {
previousVal = [];
}
var max = _.size(previousVal);
var min = -max - 1;
var pos = S(position).toInt();
var inrange = pos >= min && pos <= max;
if (!inrange) {
return new Error('Position should be between ' + min + ' and ' + max);
}
var childType = getTypeForPath(path + "[]");
if (pos === -1) {
previousVal.push(createEmpty(childType));
} else if (pos >= 0) {
previousVal.splice(pos, 0, createEmpty(childType));
} else if (pos < -1) {
previousVal.splice(pos + 1, 0, createEmpty(childType));
}
_.set(jsonData, path, previousVal);
return jsonData;
};
var copyValue = function(jsonData, pathSrc, pathDest) {
var src = getValue(jsonData, pathSrc);
if (_.isError(src)) {
return src;
}
var typeSrc = getTypeForPath(pathSrc);
var typeDest = getTypeForPath(pathDest);
if (typeSrc !== typeDest) {
return new Error('Source type is different from destination type: ' + typeSrc + ' and ' + typeDest);
}
return setValue(jsonData, pathDest, src);
};
var deleteValue = function(jsonData, path) {
var isValid = idPathValid(path);
if (!isValid) {
return new Error('Given path is not valid:' + path);
}
var parentPath = getParentPath(path);
if (_.isNull(parentPath)) {
delete jsonData[path];
} else {
var parentType = getTypeForPath(parentPath);
var parentVal = _.get(jsonData, parentPath);
if (parentType === 'object') {
var childPath = S(path).chompLeft(parentPath + ".");
delete parentVal[childPath];
} else if (parentType === 'array') {
var idx = S(path).chompLeft(parentPath).between('[', ']').toInt();
_.pullAt(parentVal, idx);
}
}
return jsonData;
};
var validate = validator(schema);
var check = function(jsonData) {
var validation = validate(jsonData);
return validation ? "valid" : "invalid";
};
var validActions = ['get', 'set', 'copy', 'insert', 'del', 'all', 'schema', 'check', 'help'];
var actionValidators = {
'get': Joi.array(Joi.string()).length(2),
'set': Joi.array(Joi.string()).length(3),
'copy': Joi.array(Joi.string()).length(3),
'insert': Joi.array(Joi.string()).length(3),
'del': Joi.array(Joi.string()).length(2),
'all': Joi.array(Joi.string()).length(1),
'check': Joi.array(Joi.string()).length(1),
'schema': Joi.array(Joi.string()).length(1),
'help': Joi.array(Joi.string()).length(1)
};
var helpCommandRecords = [
{name: "all", description: "get the whole configuration"},
{name: "check", description: "validate the configuration"},
{name: "copy", description: "copy a value between two paths. Eg: copy " + _.keys(pathsFound)[0] + " " + _.keys(pathsFound)[1]},
{name: "del", description: "delete the value at the given path. Eg: del " + _.keys(pathsFound)[0]},
{name: "get", description: "get the value at the given path. Eg: get " + _.keys(pathsFound)[0]},
{name: "help", description: "display the help you are reading now"},
{name: "insert", description: "insert a blank row"},
{name: "schema", description: "display the schema with all the possible paths"},
{name: "set", description: "set the value at the given path. Eg: set " + _.keys(pathsFound)[1] + " value"}
];
var helpCommands = _.map(helpCommandRecords, recordAsString);
var evaluate = function(jsonData, args) {
Joi.assert(jsonData, Joi.object());
Joi.assert(args, Joi.array(Joi.string()).min(1));
var action = args[0];
var actionCheck = Joi.validate(action, Joi.string().valid(validActions));
if (!_.isNull(actionCheck.error)) {
return new Error('Available actions are ' + validActions);
}
var incorrectLength = Joi.validate(args, actionValidators[action]).error;
if (!_.isNull(incorrectLength)) {
return incorrectLength;
}
if (action === 'get') {
return getValue(jsonData, args[1]);
} else if (action === 'set') {
return setValue(jsonData, args[1], args[2]);
} else if (action === 'copy') {
return copyValue(jsonData, args[1], args[2]);
} else if (action === 'insert') {
return insertRow(jsonData, args[1], args[2]);
} else if (action === 'del') {
return deleteValue(jsonData, args[1]);
} else if (action === 'schema') {
return modelHelp();
} else if (action === 'help') {
return config.tableFriendly ? helpCommandRecords: helpCommands;
} else if (action === 'all') {
return jsonData;
} else if (action === 'check') {
return check(jsonData);
}
};
var commander = {
schema: schema,
model: function() {
return _.clone(pathsFound);
},
modelHelp: modelHelp,
isPathValid: idPathValid,
isValueValid: isValueValid,
getParentPath: getParentPath,
getValue: getValue,
setValue: setValue,
insertRow: insertRow,
copyValue: copyValue,
deleteValue: deleteValue,
check: check,
evaluate: evaluate
};
return commander;
};