-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
222 lines (205 loc) · 7.65 KB
/
index.js
File metadata and controls
222 lines (205 loc) · 7.65 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
'use strict';
const fs = require('fs');
const jsonPatch = require('rfc6902');
const RefParser = require('./patched-json-schema-ref-parser');
const jps = require('./json-pointer-selectors');
const { JsonPointer } = require('json-ptr');
const clone = require('./clone');
/**
@param {object} doc
@param {object} options
@param {boolean|string} options.inherit - code word or boolean, if TRUE then code word wil be "$inherit"
@param {function} options.compileJsonPatch - custom compiler
@return {object} doc - modified source
*/
const applyInherit = function (doc, options, rootDoc, inWith) {
if (typeof doc != 'object' || doc == null) return doc;
rootDoc = rootDoc || doc;
options = options || {};
if (options.inherit == null) {
return doc;
}
if (options.inherit === true) {
options.inherit = '$inherit';
}
const $inherit = options.inherit;
const _inherit = encodeURIComponent($inherit);
const re_inherit = new RegExp(`\/${_inherit}\/source`, 'g');
const _source = `${_inherit}\/source`;
const re_source = new RegExp(`^(.*\/)${_source}\/?(.*)`);
const _with = `${_inherit}\/with`;
const re_with = new RegExp(`^(.*\/)${_with}\/?(.*)`);
if (Array.isArray(doc)) {
for (let i = 0; i < doc.length; i++) {
doc[i] = applyInherit(doc[i], options, rootDoc, inWith);
}
} else {
for (const key in doc) {
if (key == '$ref') {
if (!doc.$ref.match(/^#/)) {
throw new Error('inherit: all outer references \'$ref\' must be resolved!');
} else {
// if internal references are like '/$inherit/source*' we just bring the document
// because after applying json-patch these references will be invalid
const re = doc.$ref.match(re_source);
if (re) {
//console.error('found source ref', doc)
// pointer to whole document under key 'source'
if (inWith || !re[2]) {
//console.error('cloning document', doc.$ref, re, re_source)
return clone(JsonPointer.get(rootDoc, doc.$ref));
} else {
//console.error('replacing $ref', doc.$ref, re, re_source)
doc.$ref = doc.$ref.replace(re_inherit, '');
}
} else {
// if internal references are like '/$inherit/with*' we just bring the document
// because after applying json-patch these references will be invalid
const re = doc.$ref.match(re_with);
if (re) {
//console.error('found with ref', doc)
// pointer to whole document under key 'source'
//console.error('cloning document', doc.$ref, re, re_with)
return clone(JsonPointer.get(rootDoc, doc.$ref));
}
}
}
}
if (key in doc) {
doc[key] = applyInherit(doc[key], options, rootDoc, key == 'with' || inWith);
}
}
if (doc[$inherit]) {
const inh = doc[$inherit];
if (inh.source == null) {
throw new Error(`inherit: ${$inherit}.source is null!`);
}
if (!(inh.with == null || Array.isArray(inh.with) && inh.with.length == 0)) {
//console.log(options.compileJsonPatch, 'SOURCE:', inh.source, 'WITH:', inh.with)
inh.with.forEach(op => {
const patch = (options.compileJsonPatch || jps.compileJsonPatch)(inh.source, [op])
//console.log('PATCH', patch)
jsonPatch.applyPatch(
inh.source,
patch
);
});
}
doc = inh.source;
}
}
return doc;
};
/**
@param {string} filepath
@param {object} options
@param {boolean|string} options.inherit - code word or boolean, if TRUE code word will be "$inherit" if FALSE no inheritance will be resolved
@param {function} options.compileJsonPatch - custom compiler
@return {Promise.<object>}
*/
const bundle = function (filepath, options) {
//console.error('Bundle()')
if (!fs.existsSync(filepath)) {
return new Promise((res, rej) => rej(new Error(`invalid argument: file "${filepath}" not exists`)));
}
options = options || {};
const parser = new RefParser();
if (typeof options.inherit == 'string') {
parser.setJybidInheritWord(options.inherit);
}
return parser.bundle(filepath)
.then((doc) => {
try {
doc = applyInherit(doc, options);
} catch (e) {
console.error('inherit', 'doc:', JSON.stringify(doc, null, ' '), 'error:', e);
throw e;
}
return doc;
})
.catch((e) => {
console.error('bundle', 'filepath:', filepath, 'error:', e);
throw e;
});
};
/**
@param {string|object} doc - filepath or bundled document
@param {object} options
@param {boolean|string} options.inherit - code word or boolean, if TRUE code word will be "$inherit" if FALSE no inheritance will be resolved
@param {function} options.compileJsonPatch - custom compiler
@return {Promise.<object>}
*/
const dereference = function (doc, options) {
//console.error('Dereference()')
if (typeof doc == 'string') {
return bundle(doc, options)
.then((doc) => {
return dereference(doc);
});
}
try {
doc = applyInherit(doc, options);
} catch (e) {
console.error('inherit', 'doc:', doc, 'error:', e);
return new Promise(function(resolve, reject) {
reject(e);
});
}
return RefParser.dereference(doc)
.catch((e) => {
console.error('dereference', 'doc:', doc, 'error:', e);
throw e;
});
};
module.exports = { bundle, dereference };
if (process.argv[1] == module.filename) {
let cmd;
switch (process.argv[2]) {
case 'bundle':
case 'dereference': {
cmd = process.argv[2];
break;
}
default: {
console.log(
`Usage: node index.js COMMAND --file FILENAME [--inherit CODEWORD]
Commands:
bundle resolve external references
dereference resolve all references
Options:
--inherit CODEWORD if 'false' is passed, no inheritance will be compiled
if any word is passed it will be used instead of default '$inherit'
if option is not used default '$inherit' is used and inheritance is compiled
Examples:
node index.js bundle --file filename1.json
node index.js bundle --file filename2.json --inherit false
node index.js dereference --file filename3.json --inherit patch`);
process.exit(0);
break;
}
}
if (process.argv[3] != '--file') {
console.error('invalid option, run with --help');
process.exit(1);
}
const fs = require('fs');
const path = require('path');
const fname = path.resolve(__dirname, process.argv[4]);
if (!fs.existsSync(fname)) {
console.error(`file ${fname} not found`);
process.exit(1);
}
let inherit = true;
if (process.argv[5] == '--inherit') {
inherit = process.argv[6] == 'false' ? false :
process.argv[6] == 'true' ? true : process.argv[6];
}
module.exports[cmd](fname, { inherit })
.then((res) => {
console.log(JSON.stringify(res, null, ' '));
})
.catch((e) => {
console.error(e.stack);
process.exit(1);
});
}