This repository has been archived by the owner on Apr 12, 2024. It is now read-only.
forked from APIDevTools/json-schema-ref-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ref-parser.js
16829 lines (14208 loc) · 470 KB
/
ref-parser.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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.$RefParser = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/** !
* JSON Schema $Ref Parser v3.1.2
*
* @link https://github.com/BigstickCarpet/json-schema-ref-parser
* @license MIT
*/
'use strict';
var $Ref = require('./ref'),
Pointer = require('./pointer'),
debug = require('./util/debug'),
url = require('./util/url');
module.exports = bundle;
/**
* Bundles all external JSON references into the main JSON schema, thus resulting in a schema that
* only has *internal* references, not any *external* references.
* This method mutates the JSON schema object, adding new references and re-mapping existing ones.
*
* @param {$RefParser} parser
* @param {$RefParserOptions} options
*/
function bundle(parser, options) {
debug('Bundling $ref pointers in %s', parser.$refs._root$Ref.path);
// Build an inventory of all $ref pointers in the JSON Schema
var inventory = [];
crawl(parser, 'schema', parser.$refs._root$Ref.path + '#', '#', inventory, parser.$refs, options);
// Remap all $ref pointers
remap(inventory);
}
/**
* Recursively crawls the given value, and inventories all JSON references.
*
* @param {object} parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored.
* @param {string} key - The property key of `parent` to be crawled
* @param {string} path - The full path of the property being crawled, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of the property being crawled, from the schema root
* @param {object[]} inventory - An array of already-inventoried $ref pointers
* @param {$Refs} $refs
* @param {$RefParserOptions} options
*/
function crawl(parent, key, path, pathFromRoot, inventory, $refs, options) {
var obj = key === null ? parent : parent[key];
if (obj && typeof obj === 'object') {
if ($Ref.is$Ref(obj)) {
inventory$Ref(parent, key, path, pathFromRoot, inventory, $refs, options);
}
else {
var keys = Object.keys(obj);
// Most people will expect references to be bundled into the the "definitions" property,
// so we always crawl that property first, if it exists.
var defs = keys.indexOf('definitions');
if (defs > 0) {
keys.splice(0, 0, keys.splice(defs, 1)[0]);
}
keys.forEach(function(key) {
var keyPath = Pointer.join(path, key);
var keyPathFromRoot = Pointer.join(pathFromRoot, key);
var value = obj[key];
if ($Ref.is$Ref(value)) {
inventory$Ref(obj, key, path, keyPathFromRoot, inventory, $refs, options);
}
else {
crawl(obj, key, keyPath, keyPathFromRoot, inventory, $refs, options);
}
});
}
}
}
/**
* Inventories the given JSON Reference (i.e. records detailed information about it so we can
* optimize all $refs in the schema), and then crawls the resolved value.
*
* @param {object} $refParent - The object that contains a JSON Reference as one of its keys
* @param {string} $refKey - The key in `$refParent` that is a JSON Reference
* @param {string} path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root
* @param {object[]} inventory - An array of already-inventoried $ref pointers
* @param {$Refs} $refs
* @param {$RefParserOptions} options
*/
function inventory$Ref($refParent, $refKey, path, pathFromRoot, inventory, $refs, options) {
if (inventory.some(function(i) { return i.parent === $refParent && i.key === $refKey; })) {
// This $Ref has already been inventoried, so we don't need to process it again
return;
}
var $ref = $refKey === null ? $refParent : $refParent[$refKey];
var $refPath = url.resolve(path, $ref.$ref);
var pointer = $refs._resolve($refPath, options);
var depth = Pointer.parse(pathFromRoot).length;
var file = url.stripHash(pointer.path);
var hash = url.getHash(pointer.path);
var external = file !== $refs._root$Ref.path;
var extended = $Ref.isExtended$Ref($ref);
inventory.push({
$ref: $ref, // The JSON Reference (e.g. {$ref: string})
parent: $refParent, // The object that contains this $ref pointer
key: $refKey, // The key in `parent` that is the $ref pointer
pathFromRoot: pathFromRoot, // The path to the $ref pointer, from the JSON Schema root
depth: depth, // How far from the JSON Schema root is this $ref pointer?
file: file, // The file that the $ref pointer resolves to
hash: hash, // The hash within `file` that the $ref pointer resolves to
value: pointer.value, // The resolved value of the $ref pointer
circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself)
extended: extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref")
external: external // Does this $ref pointer point to a file other than the main JSON Schema file?
});
// Recursively crawl the resolved value
crawl(pointer.value, null, pointer.path, pathFromRoot, inventory, $refs, options);
}
/**
* Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema.
* Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same
* value are re-mapped to point to the first reference.
*
* @example:
* {
* first: { $ref: somefile.json#/some/part },
* second: { $ref: somefile.json#/another/part },
* third: { $ref: somefile.json },
* fourth: { $ref: somefile.json#/some/part/sub/part }
* }
*
* In this example, there are four references to the same file, but since the third reference points
* to the ENTIRE file, that's the only one we need to dereference. The other three can just be
* remapped to point inside the third one.
*
* On the other hand, if the third reference DIDN'T exist, then the first and second would both need
* to be dereferenced, since they point to different parts of the file. The fourth reference does NOT
* need to be dereferenced, because it can be remapped to point inside the first one.
*
* @param {object[]} inventory
*/
function remap(inventory) {
// Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them
inventory.sort(function(a, b) {
if (a.file !== b.file) {
return a.file < b.file ? -1 : +1; // Group all the $refs that point to the same file
}
else if (a.hash !== b.hash) {
return a.hash < b.hash ? -1 : +1; // Group all the $refs that point to the same part of the file
}
else if (a.circular !== b.circular) {
return a.circular ? -1 : +1; // If the $ref points to itself, then sort it higher than other $refs that point to this $ref
}
else if (a.extended !== b.extended) {
return a.extended ? +1 : -1; // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value
}
else if (a.depth !== b.depth) {
return a.depth - b.depth; // Sort $refs by how close they are to the JSON Schema root
}
else {
// If all else is equal, use the $ref that's in the "definitions" property
return b.pathFromRoot.lastIndexOf('/definitions') - a.pathFromRoot.lastIndexOf('/definitions');
}
});
var file, hash, pathFromRoot;
inventory.forEach(function(i) {
debug('Re-mapping $ref pointer "%s" at %s', i.$ref.$ref, i.pathFromRoot);
if (!i.external) {
// This $ref already resolves to the main JSON Schema file
i.$ref.$ref = i.hash;
}
else if (i.file === file && i.hash === hash) {
// This $ref points to the same value as the prevous $ref, so remap it to the same path
i.$ref.$ref = pathFromRoot;
}
else if (i.file === file && i.hash.indexOf(hash + '/') === 0) {
// This $ref points to the a sub-value as the prevous $ref, so remap it beneath that path
i.$ref.$ref = Pointer.join(pathFromRoot, Pointer.parse(i.hash));
}
else {
// We've moved to a new file or new hash
file = i.file;
hash = i.hash;
pathFromRoot = i.pathFromRoot;
// This is the first $ref to point to this value, so dereference the value.
// Any other $refs that point to the same value will point to this $ref instead
i.$ref = i.parent[i.key] = $Ref.dereference(i.$ref, i.value);
if (i.circular) {
// This $ref points to itself
i.$ref.$ref = i.pathFromRoot;
}
}
debug(' new value: %s', (i.$ref && i.$ref.$ref) ? i.$ref.$ref : '[object Object]');
});
}
},{"./pointer":10,"./ref":11,"./util/debug":16,"./util/url":19}],2:[function(require,module,exports){
'use strict';
var $Ref = require('./ref'),
Pointer = require('./pointer'),
ono = require('ono'),
debug = require('./util/debug'),
url = require('./util/url');
module.exports = dereference;
/**
* Crawls the JSON schema, finds all JSON references, and dereferences them.
* This method mutates the JSON schema object, replacing JSON references with their resolved value.
*
* @param {$RefParser} parser
* @param {$RefParserOptions} options
*/
function dereference(parser, options) {
debug('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);
var dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, '#', [], parser.$refs, options);
parser.$refs.circular = dereferenced.circular;
parser.schema = dereferenced.value;
}
/**
* Recursively crawls the given value, and dereferences any JSON references.
*
* @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored.
* @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of `obj` from the schema root
* @param {object[]} parents - An array of the parent objects that have already been dereferenced
* @param {$Refs} $refs
* @param {$RefParserOptions} options
* @returns {{value: object, circular: boolean}}
*/
function crawl(obj, path, pathFromRoot, parents, $refs, options) {
var dereferenced;
var result = {
value: obj,
circular: false
};
if (obj && typeof obj === 'object') {
parents.push(obj);
if ($Ref.isAllowed$Ref(obj, options)) {
dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, $refs, options);
result.circular = dereferenced.circular;
result.value = dereferenced.value;
}
else {
Object.keys(obj).forEach(function(key) {
var keyPath = Pointer.join(path, key);
var keyPathFromRoot = Pointer.join(pathFromRoot, key);
var value = obj[key];
var circular = false;
if ($Ref.isAllowed$Ref(value, options)) {
dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, $refs, options);
circular = dereferenced.circular;
obj[key] = dereferenced.value;
}
else {
if (parents.indexOf(value) === -1) {
dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, $refs, options);
circular = dereferenced.circular;
obj[key] = dereferenced.value;
}
else {
circular = foundCircularReference(keyPath, $refs, options);
}
}
// Set the "isCircular" flag if this or any other property is circular
result.circular = result.circular || circular;
});
}
parents.pop();
}
return result;
}
/**
* Dereferences the given JSON Reference, and then crawls the resulting value.
*
* @param {{$ref: string}} $ref - The JSON Reference to resolve
* @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of `$ref` from the schema root
* @param {object[]} parents - An array of the parent objects that have already been dereferenced
* @param {$Refs} $refs
* @param {$RefParserOptions} options
* @returns {{value: object, circular: boolean}}
*/
function dereference$Ref($ref, path, pathFromRoot, parents, $refs, options) {
debug('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path);
var $refPath = url.resolve(path, $ref.$ref);
var pointer = $refs._resolve($refPath, options);
// Check for circular references
var directCircular = pointer.circular;
var circular = directCircular || parents.indexOf(pointer.value) !== -1;
circular && foundCircularReference(path, $refs, options);
// Dereference the JSON reference
var dereferencedValue = $Ref.dereference($ref, pointer.value);
if (!pointer.unresolved)
{
// Crawl the dereferenced value (unless it's circular)
if (!circular)
{
// Determine if the dereferenced value is circular
var dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, $refs, options);
circular = dereferenced.circular;
dereferencedValue = dereferenced.value;
}
if (circular && !directCircular && options.dereference.circular === 'ignore')
{
// The user has chosen to "ignore" circular references, so don't change the value
dereferencedValue = $ref;
}
if (directCircular)
{
// The pointer is a DIRECT circular reference (i.e. it references itself).
// So replace the $ref path with the absolute path from the JSON Schema root
dereferencedValue.$ref = pathFromRoot;
}
}
return {
circular: circular,
value: dereferencedValue
};
}
/**
* Called when a circular reference is found.
* It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false.
*
* @param {string} keyPath - The JSON Reference path of the circular reference
* @param {$Refs} $refs
* @param {$RefParserOptions} options
* @returns {boolean} - always returns true, to indicate that a circular reference was found
*/
function foundCircularReference(keyPath, $refs, options) {
$refs.circular = true;
if (!options.dereference.circular) {
throw ono.reference('Circular $ref pointer found at %s', keyPath);
}
return true;
}
},{"./pointer":10,"./ref":11,"./util/debug":16,"./util/url":19,"ono":68}],3:[function(require,module,exports){
(function (Buffer){
'use strict';
var Promise = require('./util/promise'),
Options = require('./options'),
$Refs = require('./refs'),
parse = require('./parse'),
resolveExternal = require('./resolve-external'),
bundle = require('./bundle'),
dereference = require('./dereference'),
url = require('./util/url'),
maybe = require('call-me-maybe'),
ono = require('ono');
module.exports = $RefParser;
module.exports.YAML = require('./util/yaml');
/**
* This class parses a JSON schema, builds a map of its JSON references and their resolved values,
* and provides methods for traversing, manipulating, and dereferencing those references.
*
* @constructor
*/
function $RefParser() {
/**
* The parsed (and possibly dereferenced) JSON schema object
*
* @type {object}
* @readonly
*/
this.schema = null;
/**
* The resolved JSON references
*
* @type {$Refs}
* @readonly
*/
this.$refs = new $Refs();
}
/**
* Parses the given JSON schema.
* This method does not resolve any JSON references.
* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed
* @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object.
* @returns {Promise} - The returned promise resolves with the parsed JSON schema object.
*/
$RefParser.parse = function(schema, options, callback) {
var Class = this; // eslint-disable-line consistent-this
var instance = new Class();
return instance.parse.apply(instance, arguments);
};
/**
* Parses the given JSON schema.
* This method does not resolve any JSON references.
* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed
* @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object.
* @returns {Promise} - The returned promise resolves with the parsed JSON schema object.
*/
$RefParser.prototype.parse = function(schema, options, callback) {
var args = normalizeArgs(arguments);
var promise;
if (!args.path && !args.schema) {
var err = ono('Expected a file path, URL, or object. Got %s', args.path || args.schema);
return maybe(args.callback, Promise.reject(err));
}
// Reset everything
this.schema = null;
this.$refs = new $Refs();
// If the path is a filesystem path, then convert it to a URL.
// NOTE: According to the JSON Reference spec, these should already be URLs,
// but, in practice, many people use local filesystem paths instead.
// So we're being generous here and doing the conversion automatically.
// This is not intended to be a 100% bulletproof solution.
// If it doesn't work for your use-case, then use a URL instead.
if (url.isFileSystemPath(args.path)) {
args.path = url.fromFileSystemPath(args.path);
}
// Resolve the absolute path of the schema
args.path = url.resolve(url.cwd(), args.path);
if (args.schema && typeof args.schema === 'object') {
// A schema object was passed-in.
// So immediately add a new $Ref with the schema object as its value
this.$refs._add(args.path, args.schema);
promise = Promise.resolve(args.schema);
}
else {
// Parse the schema file/url
promise = parse(args.path, this.$refs, args.options);
}
var me = this;
return promise
.then(function(result) {
if (!result || typeof result !== 'object' || Buffer.isBuffer(result)) {
throw ono.syntax('"%s" is not a valid JSON Schema', me.$refs._root$Ref.path || result);
}
else {
me.schema = result;
return maybe(args.callback, Promise.resolve(me.schema));
}
})
.catch(function(e) {
return maybe(args.callback, Promise.reject(e));
});
};
/**
* Parses the given JSON schema and resolves any JSON references, including references in
* externally-referenced files.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved
* @param {function} [callback]
* - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references
*
* @returns {Promise}
* The returned promise resolves with a {@link $Refs} object containing the resolved JSON references
*/
$RefParser.resolve = function(schema, options, callback) {
var Class = this; // eslint-disable-line consistent-this
var instance = new Class();
return instance.resolve.apply(instance, arguments);
};
/**
* Parses the given JSON schema and resolves any JSON references, including references in
* externally-referenced files.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved
* @param {function} [callback]
* - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references
*
* @returns {Promise}
* The returned promise resolves with a {@link $Refs} object containing the resolved JSON references
*/
$RefParser.prototype.resolve = function(schema, options, callback) {
var me = this;
var args = normalizeArgs(arguments);
return this.parse(args.path, args.schema, args.options)
.then(function() {
return resolveExternal(me, args.options);
})
.then(function() {
return maybe(args.callback, Promise.resolve(me.$refs));
})
.catch(function(err) {
return maybe(args.callback, Promise.reject(err));
});
};
/**
* Parses the given JSON schema, resolves any JSON references, and bundles all external references
* into the main JSON schema. This produces a JSON schema that only has *internal* references,
* not any *external* references.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object
* @returns {Promise} - The returned promise resolves with the bundled JSON schema object.
*/
$RefParser.bundle = function(schema, options, callback) {
var Class = this; // eslint-disable-line consistent-this
var instance = new Class();
return instance.bundle.apply(instance, arguments);
};
/**
* Parses the given JSON schema, resolves any JSON references, and bundles all external references
* into the main JSON schema. This produces a JSON schema that only has *internal* references,
* not any *external* references.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object
* @returns {Promise} - The returned promise resolves with the bundled JSON schema object.
*/
$RefParser.prototype.bundle = function(schema, options, callback) {
var me = this;
var args = normalizeArgs(arguments);
return this.resolve(args.path, args.schema, args.options)
.then(function() {
bundle(me, args.options);
return maybe(args.callback, Promise.resolve(me.schema));
})
.catch(function(err) {
return maybe(args.callback, Promise.reject(err));
});
};
/**
* Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema.
* That is, all JSON references are replaced with their resolved values.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object
* @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object.
*/
$RefParser.dereference = function(schema, options, callback) {
var Class = this; // eslint-disable-line consistent-this
var instance = new Class();
return instance.dereference.apply(instance, arguments);
};
/**
* Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema.
* That is, all JSON references are replaced with their resolved values.
*
* @param {string|object} schema - The file path or URL of the JSON schema. Or a JSON schema object.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object
* @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object.
*/
$RefParser.prototype.dereference = function(schema, options, callback) {
var me = this;
var args = normalizeArgs(arguments);
return this.resolve(args.path, args.schema, args.options)
.then(function() {
dereference(me, args.options);
return maybe(args.callback, Promise.resolve(me.schema));
})
.catch(function(err) {
return maybe(args.callback, Promise.reject(err));
});
};
/**
* Normalizes the given arguments, accounting for optional args.
*
* @param {Arguments} args
* @returns {object}
*/
function normalizeArgs(args) {
var path, schema, options, callback;
args = Array.prototype.slice.call(args);
if (typeof args[args.length - 1] === 'function') {
// The last parameter is a callback function
callback = args.pop();
}
if (typeof args[0] === 'string') {
// The first parameter is the path
path = args[0];
if (typeof args[2] === 'object') {
// The second parameter is the schema, and the third parameter is the options
schema = args[1];
options = args[2];
}
else {
// The second parameter is the options
schema = undefined;
options = args[1];
}
}
else {
// The first parameter is the schema
path = '';
schema = args[0];
options = args[1];
}
if (!(options instanceof Options)) {
options = new Options(options);
}
return {
path: path,
schema: schema,
options: options,
callback: callback
};
}
}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")})
},{"../node_modules/is-buffer/index.js":35,"./bundle":1,"./dereference":2,"./options":4,"./parse":5,"./refs":12,"./resolve-external":13,"./util/promise":18,"./util/url":19,"./util/yaml":20,"call-me-maybe":26,"ono":68}],4:[function(require,module,exports){
/* eslint lines-around-comment: [2, {beforeBlockComment: false}] */
'use strict';
var jsonParser = require('./parsers/json'),
yamlParser = require('./parsers/yaml'),
textParser = require('./parsers/text'),
binaryParser = require('./parsers/binary'),
fileResolver = require('./resolvers/file'),
httpResolver = require('./resolvers/http'),
zschemaValidator = require('./validators/z-schema');
module.exports = $RefParserOptions;
/**
* Options that determine how JSON schemas are parsed, resolved, dereferenced, and validated.
*
* @param {object|$RefParserOptions} [options] - Overridden options
* @constructor
*/
function $RefParserOptions(options) {
merge(this, $RefParserOptions.defaults);
merge(this, options);
}
$RefParserOptions.defaults = {
/**
* Determines how different types of files will be parsed.
*
* You can add additional parsers of your own, replace an existing one with
* your own implemenation, or disable any parser by setting it to false.
*/
parse: {
json: jsonParser,
yaml: yamlParser,
text: textParser,
binary: binaryParser,
},
/**
* Determines how JSON References will be resolved.
*
* You can add additional resolvers of your own, replace an existing one with
* your own implemenation, or disable any resolver by setting it to false.
*/
resolve: {
file: fileResolver,
http: httpResolver,
/**
* Determines whether external $ref pointers will be resolved.
* If this option is disabled, then none of above resolvers will be called.
* Instead, external $ref pointers will simply be ignored.
*
* @type {boolean}
*/
external: true,
},
/**
* Determines the types of JSON references that are allowed.
*/
dereference: {
/**
* Dereference circular (recursive) JSON references?
* If false, then a {@link ReferenceError} will be thrown if a circular reference is found.
* If "ignore", then circular references will not be dereferenced.
*
* @type {boolean|string}
*/
circular: true,
/**
* The default behavior is to throw an error if a reference is not found.
* If false, then leave the $ref: value object in the json schema
*
* @type {boolean}
*/
onErrorThrow: true
},
/**
* Validator plug-ins that can be used to validate the schema.
*/
validate: {
zschema: zschemaValidator
}
};
/**
* Merges the properties of the source object into the target object.
*
* @param {object} target - The object that we're populating
* @param {?object} source - The options that are being merged
* @returns {object}
*/
function merge(target, source) {
if (isMergeable(source)) {
var keys = Object.keys(source);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var sourceSetting = source[key];
var targetSetting = target[key];
if (isMergeable(sourceSetting)) {
// It's a nested object, so merge it recursively
target[key] = merge(targetSetting || {}, sourceSetting);
}
else if (sourceSetting !== undefined) {
// It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.
target[key] = sourceSetting;
}
}
}
return target;
}
/**
* Determines whether the given value can be merged,
* or if it is a scalar value that should just override the target value.
*
* @param {*} val
* @returns {Boolean}
*/
function isMergeable(val) {
return val &&
(typeof val === 'object') &&
!Array.isArray(val) &&
!(val instanceof RegExp) &&
!(val instanceof Date);
}
},{"./parsers/binary":6,"./parsers/json":7,"./parsers/text":8,"./parsers/yaml":9,"./resolvers/file":14,"./resolvers/http":15,"./validators/z-schema":21}],5:[function(require,module,exports){
(function (Buffer){
'use strict';
var ono = require('ono'),
debug = require('./util/debug'),
url = require('./util/url'),
plugins = require('./util/plugins'),
Promise = require('./util/promise');
module.exports = parse;
/**
* Reads and parses the specified file path or URL.
*
* @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context
* @param {$Refs} $refs
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves with the parsed file contents, NOT the raw (Buffer) contents.
*/
function parse(path, $refs, options) {
try {
// Remove the URL fragment, if any
path = url.stripHash(path);
// Add a new $Ref for this file, even though we don't have the value yet.
// This ensures that we don't simultaneously read & parse the same file multiple times
var $ref = $refs._add(path);
// This "file object" will be passed to all resolvers and parsers.
var file = {
url: path,
extension: url.getExtension(path),
};
// Read the file and then parse the data
return readFile(file, options)
.then(function(resolver) {
$ref.pathType = resolver.plugin.name;
file.data = resolver.result;
return parseFile(file, options);
})
.then(function(parser) {
$ref.value = parser.result;
return parser.result;
})
.catch(function(err) {
if (options.dereference.onErrorThrow) {
throw err;
}
else {
$ref.unresolved = true;
$ref.value = {'$ref': file.url};
return $ref.value;
}
});
}
catch (e) {
return Promise.reject(e);
}
}
/**
* Reads the given file, using the configured resolver plugins
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves with the raw file contents and the resolver that was used.
*/
function readFile(file, options) {
return new Promise(function(resolve, reject) {
debug('Reading %s', file.url);
// Find the resolvers that can read this file
var resolvers = plugins.all(options.resolve);
resolvers = plugins.filter(resolvers, 'canRead', file);
// Run the resolvers, in order, until one of them succeeds
plugins.sort(resolvers);
plugins.run(resolvers, 'read', file)
.then(resolve, onError);
function onError(err) {
// Throw the original error, if it's one of our own (user-friendly) errors.
// Otherwise, throw a generic, friendly error.
if (err && !(err instanceof SyntaxError)) {
reject(err);
}
else {
reject(ono.syntax('Unable to resolve $ref pointer "%s"', file.url));
}
}
});
}
/**
* Parses the given file's contents, using the configured parser plugins.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves with the parsed file contents and the parser that was used.
*/
function parseFile(file, options) {
return new Promise(function(resolve, reject) {
debug('Parsing %s', file.url);
// Find the parsers that can read this file type.
// If none of the parsers are an exact match for this file, then we'll try ALL of them.
// This handles situations where the file IS a supported type, just with an unknown extension.
var allParsers = plugins.all(options.parse);
var filteredParsers = plugins.filter(allParsers, 'canParse', file);
var parsers = filteredParsers.length > 0 ? filteredParsers : allParsers;
// Run the parsers, in order, until one of them succeeds
plugins.sort(parsers);
plugins.run(parsers, 'parse', file)
.then(onParsed, onError);
function onParsed(parser) {
if (!parser.plugin.allowEmpty && isEmpty(parser.result)) {
reject(ono.syntax('Error parsing "%s" as %s. \nParsed value is empty', file.url, parser.plugin.name));
}
else {
resolve(parser);
}
}
function onError(err) {
if (err) {
err = err instanceof Error ? err : new Error(err);
reject(ono.syntax(err, 'Error parsing %s', file.url));
}
else {
reject(ono.syntax('Unable to parse %s', file.url));
}
}
});
}
/**
* Determines whether the parsed value is "empty".
*
* @param {*} value
* @returns {boolean}
*/
function isEmpty(value) {
return value === undefined ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0) ||
(Buffer.isBuffer(value) && value.length === 0);
}
}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")})
},{"../node_modules/is-buffer/index.js":35,"./util/debug":16,"./util/plugins":17,"./util/promise":18,"./util/url":19,"ono":68}],6:[function(require,module,exports){
(function (Buffer){
'use strict';
var BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i;
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 400,
/**
* Whether to allow "empty" files (zero bytes).
*
* @type {boolean}
*/
allowEmpty: true,
/**
* Determines whether this parser can parse a given file reference.
* Parsers that return true will be tried, in order, until one successfully parses the file.
* Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
* every parser will be tried.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {boolean}
*/
canParse: function isBinary(file) {
// Use this parser if the file is a Buffer, and has a known binary extension
return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url);
},
/**
* Parses the given data as a Buffer (byte array).
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)