-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-pointer-selectors.js
282 lines (250 loc) · 9.07 KB
/
json-pointer-selectors.js
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
'use strict';
const { JsonPointer } = require('json-ptr');
//
// Some json pointer additions (path with object selectors)
//
const toValue = (v, escaped) => {
if (escaped) {
return v.replace(/\\(\\|")/g, '$1');
} else {
if (v === 'true') {
return true;
}
if (v === 'false') {
return false;
}
if (v === 'null') {
return null;
}
if (v === '') {
return undefined;
}
if (v.match(/^-?[0-9]+$/)) {
return parseInt(v, 10);
}
if (v.match(/^-?[0-9]+\.[0-9]*$/)) {
return parseFloat(v);
}
return v;
}
};
const toName = (n, escaped) => {
if (escaped) {
return n.replace(/\\(\\|")/g, '$1');
} else {
if (n === '') {
return null;
} else {
return n;
}
}
};
// path: "/aaaaaaaa/[bb=bb]/ccc"
// ^ ^ ^
// path = prefix + infix + suffix
const parseJsonPointer = (path) => {
let pos = path.indexOf('[');
let parse;
do {
if (pos === -1) {
return {
prefix: path,
infix: '',
suffix: ''
};
} else {
if (pos === 0) {
parse = true;
} else {
if (path.charAt(pos - 1) === '/') {
parse = true;
} else {
pos = path.indexOf('[', pos + 1);
}
}
}
const parseStart = pos;
while (parse) {
const selector = [];
do {
let tail = path.substr(pos);
let name = tail.match(/^\[([^"\/]*?)=/);
let escaped;
escaped = false;
if (name == null) {
name = tail.match(/^\["((?:[^\\"]|\\"|\\\\)*?)"=/);
escaped = true;
}
if (name != null) {
pos += name[0].length;
name = toName(name[1], escaped);
} else {
pos = path.indexOf('[', pos + 1);
parse = false;
break;
}
tail = path.substr(pos);
escaped = false;
let value = tail.match(/^([^"]*?)\]/);
if (value == null) {
value = tail.match(/^"((?:[^\\"]|\\"|\\\\)*?)"\]/);
escaped = true;
}
if (value != null) {
pos += value[0].length;
value = toValue(value[1], escaped);
} else {
pos = path.indexOf('[', pos);
parse = false;
break;
}
selector.push({key: name, value: value});
const eos = pos >= path.length;
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: true }]*/
if (eos || path.charAt(pos) === '/') {
if (eos) {
if (parseStart === 0) { // [infix]
return {
prefix: '', // ''
infix: path.substr(0, pos), // [infix]
suffix: '', // ''
selector: selector
};
} else { // prefix/[infix]
return {
prefix: path.substr(0, parseStart - 1), // prefix
infix: path.substr(parseStart - 1), // /[infix]
suffix: '', // ''
selector: selector
};
}
} else {
if (parseStart === 0) { // [infix]/suffix
return {
prefix: '', // ''
infix: path.substr(0, pos), // [infix]
suffix: path.substr(pos), // /suffix
selector: selector
};
} else { // prefix/[infix]/suffix
return {
prefix: path.substr(0, parseStart - 1), // prefix
infix: path.substring(parseStart - 1, pos), // /[infix]
suffix: path.substr(pos), // /suffix
selector: selector
};
}
}
}
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: false }]*/
} while (true);
}
} while (true);
};
const buildSelectorString = (selector) => {
let path = '';
for (let i = 0; i < selector.length; i++) {
let key = selector[i].key;
if (key != null) {
key = '"' + key.replace(/(\\|")/g, '\\$1') + '"';
} else {
key = '';
}
let value = selector[i].value;
if (value != null) {
if (typeof value == 'string') {
value = '"' + value.replace(/(\\|")/g, '\\$1') + '"';
}
} else {
if (value === null) {
value = 'null';
} else {
value = '';
}
}
path += `[${key}=${value}]`;
}
return path;
};
const objectMatchesSelector = (obj, selector) => {
let c;
for (let i = 0; i < selector.length; i++) {
c = selector[i];
if (c.key != null && c.value != null && obj[c.key] !== c.value ||
c.key != null && c.value == null && obj[c.key] == undefined ||
c.key == null && c.value != null && obj !== c.value
) {
return false;
}
}
return true;
};
const compileOperation = (source, op) => {
const re = parseJsonPointer(op.path);
if (re.selector) {
const arr = JsonPointer.get(source, re.prefix);
// if object is not array check deeper
if (!Array.isArray(arr)) {
// if there is something to check deeper
if (arr[re.infix] != undefined && re.suffix != '') {
// relative pathes
op = compileOperation(arr[re.infix], Object.assign({}, op, {path: re.suffix}));
// relative pathes back to absolute
op.path = re.prefix + re.infix + op.path;
}
return op;
}
// if found array check conditions
let found;
for (let j = 0; j < arr.length; j++) {
if (objectMatchesSelector(arr[j], re.selector)) {
if (found) {
//console.error(re.selector)
//console.error('first match:', found)
//console.error('new match:', j, arr[j])
throw new Error(`path ${op.path} compiles to selector that has multiple matches, it is forbidden`);
}
const tmp = Object.assign({}, op, {path: re.suffix});
if (compileOperation(arr[j], tmp)) {
// changing path to JSON-Pointer with number
found = Object.assign({}, op, {path: re.prefix + '/' + j + re.suffix});
}
}
}
if (found) {
// checking new pathes deeper
return compileOperation(source, found);
}
//return null;
throw new Error(`op ${JSON.stringify(op)} compiles to selector that has no matches`);
}
// all path exists or "op" is adding a new leaf
if (JsonPointer.get(source, op.path)
|| (op.op == 'add' || op.op == 'move')
&& JsonPointer.get(source, op.path.match(/(^.*)\/[^\/]*/)[1])
) {
return op;
}
//return null;
throw new Error(`op ${JSON.stringify(op)} compiles to selector that has no matches`);
};
/**
@param {object} source - object to which patch will be applied
@param {Array} patchOperations
@return {Array} - JSON Patch
*/
const compileJsonPatch = (source, patchOperations) => {
const res = [];
for (let i = 0; i < patchOperations.length; i++) {
const op = patchOperations[i];
if (!op.path) {
continue;
}
const compiled = compileOperation(source, op);
if (compiled) {
res.push(compiled);
}
}
return res;
};
module.exports = { buildSelectorString, parseJsonPointer, objectMatchesSelector, compileJsonPatch };