· 6 years ago · Jun 27, 2019, 04:18 PM
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define(['exports'], factory) :
4 (global = global || self, factory(global.YmlHelper = {}));
5}(this, function (exports) { 'use strict';
6
7 function _classCallCheck(instance, Constructor) {
8 if (!(instance instanceof Constructor)) {
9 throw new TypeError("Cannot call a class as a function");
10 }
11 }
12
13 function _defineProperties(target, props) {
14 for (var i = 0; i < props.length; i++) {
15 var descriptor = props[i];
16 descriptor.enumerable = descriptor.enumerable || false;
17 descriptor.configurable = true;
18 if ("value" in descriptor) descriptor.writable = true;
19 Object.defineProperty(target, descriptor.key, descriptor);
20 }
21 }
22
23 function _createClass(Constructor, protoProps, staticProps) {
24 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
25 if (staticProps) _defineProperties(Constructor, staticProps);
26 return Constructor;
27 }
28
29 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
30
31 function commonjsRequire () {
32 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
33 }
34
35 function createCommonjsModule(fn, module) {
36 return module = { exports: {} }, fn(module, module.exports), module.exports;
37 }
38
39 var underscore = createCommonjsModule(function (module, exports) {
40 // Underscore.js 1.9.1
41 // http://underscorejs.org
42 // (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
43 // Underscore may be freely distributed under the MIT license.
44
45 (function() {
46
47 // Baseline setup
48 // --------------
49
50 // Establish the root object, `window` (`self`) in the browser, `global`
51 // on the server, or `this` in some virtual machines. We use `self`
52 // instead of `window` for `WebWorker` support.
53 var root = typeof self == 'object' && self.self === self && self ||
54 typeof commonjsGlobal == 'object' && commonjsGlobal.global === commonjsGlobal && commonjsGlobal ||
55 this ||
56 {};
57
58 // Save the previous value of the `_` variable.
59 var previousUnderscore = root._;
60
61 // Save bytes in the minified (but not gzipped) version:
62 var ArrayProto = Array.prototype, ObjProto = Object.prototype;
63 var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
64
65 // Create quick reference variables for speed access to core prototypes.
66 var push = ArrayProto.push,
67 slice = ArrayProto.slice,
68 toString = ObjProto.toString,
69 hasOwnProperty = ObjProto.hasOwnProperty;
70
71 // All **ECMAScript 5** native function implementations that we hope to use
72 // are declared here.
73 var nativeIsArray = Array.isArray,
74 nativeKeys = Object.keys,
75 nativeCreate = Object.create;
76
77 // Naked function reference for surrogate-prototype-swapping.
78 var Ctor = function(){};
79
80 // Create a safe reference to the Underscore object for use below.
81 var _ = function(obj) {
82 if (obj instanceof _) return obj;
83 if (!(this instanceof _)) return new _(obj);
84 this._wrapped = obj;
85 };
86
87 // Export the Underscore object for **Node.js**, with
88 // backwards-compatibility for their old module API. If we're in
89 // the browser, add `_` as a global object.
90 // (`nodeType` is checked to ensure that `module`
91 // and `exports` are not HTML elements.)
92 if (!exports.nodeType) {
93 if (!module.nodeType && module.exports) {
94 exports = module.exports = _;
95 }
96 exports._ = _;
97 } else {
98 root._ = _;
99 }
100
101 // Current version.
102 _.VERSION = '1.9.1';
103
104 // Internal function that returns an efficient (for current engines) version
105 // of the passed-in callback, to be repeatedly applied in other Underscore
106 // functions.
107 var optimizeCb = function(func, context, argCount) {
108 if (context === void 0) return func;
109 switch (argCount == null ? 3 : argCount) {
110 case 1: return function(value) {
111 return func.call(context, value);
112 };
113 // The 2-argument case is omitted because we’re not using it.
114 case 3: return function(value, index, collection) {
115 return func.call(context, value, index, collection);
116 };
117 case 4: return function(accumulator, value, index, collection) {
118 return func.call(context, accumulator, value, index, collection);
119 };
120 }
121 return function() {
122 return func.apply(context, arguments);
123 };
124 };
125
126 var builtinIteratee;
127
128 // An internal function to generate callbacks that can be applied to each
129 // element in a collection, returning the desired result — either `identity`,
130 // an arbitrary callback, a property matcher, or a property accessor.
131 var cb = function(value, context, argCount) {
132 if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
133 if (value == null) return _.identity;
134 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
135 if (_.isObject(value) && !_.isArray(value)) return _.matcher(value);
136 return _.property(value);
137 };
138
139 // External wrapper for our callback generator. Users may customize
140 // `_.iteratee` if they want additional predicate/iteratee shorthand styles.
141 // This abstraction hides the internal-only argCount argument.
142 _.iteratee = builtinIteratee = function(value, context) {
143 return cb(value, context, Infinity);
144 };
145
146 // Some functions take a variable number of arguments, or a few expected
147 // arguments at the beginning and then a variable number of values to operate
148 // on. This helper accumulates all remaining arguments past the function’s
149 // argument length (or an explicit `startIndex`), into an array that becomes
150 // the last argument. Similar to ES6’s "rest parameter".
151 var restArguments = function(func, startIndex) {
152 startIndex = startIndex == null ? func.length - 1 : +startIndex;
153 return function() {
154 var length = Math.max(arguments.length - startIndex, 0),
155 rest = Array(length),
156 index = 0;
157 for (; index < length; index++) {
158 rest[index] = arguments[index + startIndex];
159 }
160 switch (startIndex) {
161 case 0: return func.call(this, rest);
162 case 1: return func.call(this, arguments[0], rest);
163 case 2: return func.call(this, arguments[0], arguments[1], rest);
164 }
165 var args = Array(startIndex + 1);
166 for (index = 0; index < startIndex; index++) {
167 args[index] = arguments[index];
168 }
169 args[startIndex] = rest;
170 return func.apply(this, args);
171 };
172 };
173
174 // An internal function for creating a new object that inherits from another.
175 var baseCreate = function(prototype) {
176 if (!_.isObject(prototype)) return {};
177 if (nativeCreate) return nativeCreate(prototype);
178 Ctor.prototype = prototype;
179 var result = new Ctor;
180 Ctor.prototype = null;
181 return result;
182 };
183
184 var shallowProperty = function(key) {
185 return function(obj) {
186 return obj == null ? void 0 : obj[key];
187 };
188 };
189
190 var has = function(obj, path) {
191 return obj != null && hasOwnProperty.call(obj, path);
192 };
193
194 var deepGet = function(obj, path) {
195 var length = path.length;
196 for (var i = 0; i < length; i++) {
197 if (obj == null) return void 0;
198 obj = obj[path[i]];
199 }
200 return length ? obj : void 0;
201 };
202
203 // Helper for collection methods to determine whether a collection
204 // should be iterated as an array or as an object.
205 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
206 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
207 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
208 var getLength = shallowProperty('length');
209 var isArrayLike = function(collection) {
210 var length = getLength(collection);
211 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
212 };
213
214 // Collection Functions
215 // --------------------
216
217 // The cornerstone, an `each` implementation, aka `forEach`.
218 // Handles raw objects in addition to array-likes. Treats all
219 // sparse array-likes as if they were dense.
220 _.each = _.forEach = function(obj, iteratee, context) {
221 iteratee = optimizeCb(iteratee, context);
222 var i, length;
223 if (isArrayLike(obj)) {
224 for (i = 0, length = obj.length; i < length; i++) {
225 iteratee(obj[i], i, obj);
226 }
227 } else {
228 var keys = _.keys(obj);
229 for (i = 0, length = keys.length; i < length; i++) {
230 iteratee(obj[keys[i]], keys[i], obj);
231 }
232 }
233 return obj;
234 };
235
236 // Return the results of applying the iteratee to each element.
237 _.map = _.collect = function(obj, iteratee, context) {
238 iteratee = cb(iteratee, context);
239 var keys = !isArrayLike(obj) && _.keys(obj),
240 length = (keys || obj).length,
241 results = Array(length);
242 for (var index = 0; index < length; index++) {
243 var currentKey = keys ? keys[index] : index;
244 results[index] = iteratee(obj[currentKey], currentKey, obj);
245 }
246 return results;
247 };
248
249 // Create a reducing function iterating left or right.
250 var createReduce = function(dir) {
251 // Wrap code that reassigns argument variables in a separate function than
252 // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
253 var reducer = function(obj, iteratee, memo, initial) {
254 var keys = !isArrayLike(obj) && _.keys(obj),
255 length = (keys || obj).length,
256 index = dir > 0 ? 0 : length - 1;
257 if (!initial) {
258 memo = obj[keys ? keys[index] : index];
259 index += dir;
260 }
261 for (; index >= 0 && index < length; index += dir) {
262 var currentKey = keys ? keys[index] : index;
263 memo = iteratee(memo, obj[currentKey], currentKey, obj);
264 }
265 return memo;
266 };
267
268 return function(obj, iteratee, memo, context) {
269 var initial = arguments.length >= 3;
270 return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
271 };
272 };
273
274 // **Reduce** builds up a single result from a list of values, aka `inject`,
275 // or `foldl`.
276 _.reduce = _.foldl = _.inject = createReduce(1);
277
278 // The right-associative version of reduce, also known as `foldr`.
279 _.reduceRight = _.foldr = createReduce(-1);
280
281 // Return the first value which passes a truth test. Aliased as `detect`.
282 _.find = _.detect = function(obj, predicate, context) {
283 var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey;
284 var key = keyFinder(obj, predicate, context);
285 if (key !== void 0 && key !== -1) return obj[key];
286 };
287
288 // Return all the elements that pass a truth test.
289 // Aliased as `select`.
290 _.filter = _.select = function(obj, predicate, context) {
291 var results = [];
292 predicate = cb(predicate, context);
293 _.each(obj, function(value, index, list) {
294 if (predicate(value, index, list)) results.push(value);
295 });
296 return results;
297 };
298
299 // Return all the elements for which a truth test fails.
300 _.reject = function(obj, predicate, context) {
301 return _.filter(obj, _.negate(cb(predicate)), context);
302 };
303
304 // Determine whether all of the elements match a truth test.
305 // Aliased as `all`.
306 _.every = _.all = function(obj, predicate, context) {
307 predicate = cb(predicate, context);
308 var keys = !isArrayLike(obj) && _.keys(obj),
309 length = (keys || obj).length;
310 for (var index = 0; index < length; index++) {
311 var currentKey = keys ? keys[index] : index;
312 if (!predicate(obj[currentKey], currentKey, obj)) return false;
313 }
314 return true;
315 };
316
317 // Determine if at least one element in the object matches a truth test.
318 // Aliased as `any`.
319 _.some = _.any = function(obj, predicate, context) {
320 predicate = cb(predicate, context);
321 var keys = !isArrayLike(obj) && _.keys(obj),
322 length = (keys || obj).length;
323 for (var index = 0; index < length; index++) {
324 var currentKey = keys ? keys[index] : index;
325 if (predicate(obj[currentKey], currentKey, obj)) return true;
326 }
327 return false;
328 };
329
330 // Determine if the array or object contains a given item (using `===`).
331 // Aliased as `includes` and `include`.
332 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
333 if (!isArrayLike(obj)) obj = _.values(obj);
334 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
335 return _.indexOf(obj, item, fromIndex) >= 0;
336 };
337
338 // Invoke a method (with arguments) on every item in a collection.
339 _.invoke = restArguments(function(obj, path, args) {
340 var contextPath, func;
341 if (_.isFunction(path)) {
342 func = path;
343 } else if (_.isArray(path)) {
344 contextPath = path.slice(0, -1);
345 path = path[path.length - 1];
346 }
347 return _.map(obj, function(context) {
348 var method = func;
349 if (!method) {
350 if (contextPath && contextPath.length) {
351 context = deepGet(context, contextPath);
352 }
353 if (context == null) return void 0;
354 method = context[path];
355 }
356 return method == null ? method : method.apply(context, args);
357 });
358 });
359
360 // Convenience version of a common use case of `map`: fetching a property.
361 _.pluck = function(obj, key) {
362 return _.map(obj, _.property(key));
363 };
364
365 // Convenience version of a common use case of `filter`: selecting only objects
366 // containing specific `key:value` pairs.
367 _.where = function(obj, attrs) {
368 return _.filter(obj, _.matcher(attrs));
369 };
370
371 // Convenience version of a common use case of `find`: getting the first object
372 // containing specific `key:value` pairs.
373 _.findWhere = function(obj, attrs) {
374 return _.find(obj, _.matcher(attrs));
375 };
376
377 // Return the maximum element (or element-based computation).
378 _.max = function(obj, iteratee, context) {
379 var result = -Infinity, lastComputed = -Infinity,
380 value, computed;
381 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
382 obj = isArrayLike(obj) ? obj : _.values(obj);
383 for (var i = 0, length = obj.length; i < length; i++) {
384 value = obj[i];
385 if (value != null && value > result) {
386 result = value;
387 }
388 }
389 } else {
390 iteratee = cb(iteratee, context);
391 _.each(obj, function(v, index, list) {
392 computed = iteratee(v, index, list);
393 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
394 result = v;
395 lastComputed = computed;
396 }
397 });
398 }
399 return result;
400 };
401
402 // Return the minimum element (or element-based computation).
403 _.min = function(obj, iteratee, context) {
404 var result = Infinity, lastComputed = Infinity,
405 value, computed;
406 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
407 obj = isArrayLike(obj) ? obj : _.values(obj);
408 for (var i = 0, length = obj.length; i < length; i++) {
409 value = obj[i];
410 if (value != null && value < result) {
411 result = value;
412 }
413 }
414 } else {
415 iteratee = cb(iteratee, context);
416 _.each(obj, function(v, index, list) {
417 computed = iteratee(v, index, list);
418 if (computed < lastComputed || computed === Infinity && result === Infinity) {
419 result = v;
420 lastComputed = computed;
421 }
422 });
423 }
424 return result;
425 };
426
427 // Shuffle a collection.
428 _.shuffle = function(obj) {
429 return _.sample(obj, Infinity);
430 };
431
432 // Sample **n** random values from a collection using the modern version of the
433 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
434 // If **n** is not specified, returns a single random element.
435 // The internal `guard` argument allows it to work with `map`.
436 _.sample = function(obj, n, guard) {
437 if (n == null || guard) {
438 if (!isArrayLike(obj)) obj = _.values(obj);
439 return obj[_.random(obj.length - 1)];
440 }
441 var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj);
442 var length = getLength(sample);
443 n = Math.max(Math.min(n, length), 0);
444 var last = length - 1;
445 for (var index = 0; index < n; index++) {
446 var rand = _.random(index, last);
447 var temp = sample[index];
448 sample[index] = sample[rand];
449 sample[rand] = temp;
450 }
451 return sample.slice(0, n);
452 };
453
454 // Sort the object's values by a criterion produced by an iteratee.
455 _.sortBy = function(obj, iteratee, context) {
456 var index = 0;
457 iteratee = cb(iteratee, context);
458 return _.pluck(_.map(obj, function(value, key, list) {
459 return {
460 value: value,
461 index: index++,
462 criteria: iteratee(value, key, list)
463 };
464 }).sort(function(left, right) {
465 var a = left.criteria;
466 var b = right.criteria;
467 if (a !== b) {
468 if (a > b || a === void 0) return 1;
469 if (a < b || b === void 0) return -1;
470 }
471 return left.index - right.index;
472 }), 'value');
473 };
474
475 // An internal function used for aggregate "group by" operations.
476 var group = function(behavior, partition) {
477 return function(obj, iteratee, context) {
478 var result = partition ? [[], []] : {};
479 iteratee = cb(iteratee, context);
480 _.each(obj, function(value, index) {
481 var key = iteratee(value, index, obj);
482 behavior(result, value, key);
483 });
484 return result;
485 };
486 };
487
488 // Groups the object's values by a criterion. Pass either a string attribute
489 // to group by, or a function that returns the criterion.
490 _.groupBy = group(function(result, value, key) {
491 if (has(result, key)) result[key].push(value); else result[key] = [value];
492 });
493
494 // Indexes the object's values by a criterion, similar to `groupBy`, but for
495 // when you know that your index values will be unique.
496 _.indexBy = group(function(result, value, key) {
497 result[key] = value;
498 });
499
500 // Counts instances of an object that group by a certain criterion. Pass
501 // either a string attribute to count by, or a function that returns the
502 // criterion.
503 _.countBy = group(function(result, value, key) {
504 if (has(result, key)) result[key]++; else result[key] = 1;
505 });
506
507 var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
508 // Safely create a real, live array from anything iterable.
509 _.toArray = function(obj) {
510 if (!obj) return [];
511 if (_.isArray(obj)) return slice.call(obj);
512 if (_.isString(obj)) {
513 // Keep surrogate pair characters together
514 return obj.match(reStrSymbol);
515 }
516 if (isArrayLike(obj)) return _.map(obj, _.identity);
517 return _.values(obj);
518 };
519
520 // Return the number of elements in an object.
521 _.size = function(obj) {
522 if (obj == null) return 0;
523 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
524 };
525
526 // Split a collection into two arrays: one whose elements all satisfy the given
527 // predicate, and one whose elements all do not satisfy the predicate.
528 _.partition = group(function(result, value, pass) {
529 result[pass ? 0 : 1].push(value);
530 }, true);
531
532 // Array Functions
533 // ---------------
534
535 // Get the first element of an array. Passing **n** will return the first N
536 // values in the array. Aliased as `head` and `take`. The **guard** check
537 // allows it to work with `_.map`.
538 _.first = _.head = _.take = function(array, n, guard) {
539 if (array == null || array.length < 1) return n == null ? void 0 : [];
540 if (n == null || guard) return array[0];
541 return _.initial(array, array.length - n);
542 };
543
544 // Returns everything but the last entry of the array. Especially useful on
545 // the arguments object. Passing **n** will return all the values in
546 // the array, excluding the last N.
547 _.initial = function(array, n, guard) {
548 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
549 };
550
551 // Get the last element of an array. Passing **n** will return the last N
552 // values in the array.
553 _.last = function(array, n, guard) {
554 if (array == null || array.length < 1) return n == null ? void 0 : [];
555 if (n == null || guard) return array[array.length - 1];
556 return _.rest(array, Math.max(0, array.length - n));
557 };
558
559 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
560 // Especially useful on the arguments object. Passing an **n** will return
561 // the rest N values in the array.
562 _.rest = _.tail = _.drop = function(array, n, guard) {
563 return slice.call(array, n == null || guard ? 1 : n);
564 };
565
566 // Trim out all falsy values from an array.
567 _.compact = function(array) {
568 return _.filter(array, Boolean);
569 };
570
571 // Internal implementation of a recursive `flatten` function.
572 var flatten = function(input, shallow, strict, output) {
573 output = output || [];
574 var idx = output.length;
575 for (var i = 0, length = getLength(input); i < length; i++) {
576 var value = input[i];
577 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
578 // Flatten current level of array or arguments object.
579 if (shallow) {
580 var j = 0, len = value.length;
581 while (j < len) output[idx++] = value[j++];
582 } else {
583 flatten(value, shallow, strict, output);
584 idx = output.length;
585 }
586 } else if (!strict) {
587 output[idx++] = value;
588 }
589 }
590 return output;
591 };
592
593 // Flatten out an array, either recursively (by default), or just one level.
594 _.flatten = function(array, shallow) {
595 return flatten(array, shallow, false);
596 };
597
598 // Return a version of the array that does not contain the specified value(s).
599 _.without = restArguments(function(array, otherArrays) {
600 return _.difference(array, otherArrays);
601 });
602
603 // Produce a duplicate-free version of the array. If the array has already
604 // been sorted, you have the option of using a faster algorithm.
605 // The faster algorithm will not work with an iteratee if the iteratee
606 // is not a one-to-one function, so providing an iteratee will disable
607 // the faster algorithm.
608 // Aliased as `unique`.
609 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
610 if (!_.isBoolean(isSorted)) {
611 context = iteratee;
612 iteratee = isSorted;
613 isSorted = false;
614 }
615 if (iteratee != null) iteratee = cb(iteratee, context);
616 var result = [];
617 var seen = [];
618 for (var i = 0, length = getLength(array); i < length; i++) {
619 var value = array[i],
620 computed = iteratee ? iteratee(value, i, array) : value;
621 if (isSorted && !iteratee) {
622 if (!i || seen !== computed) result.push(value);
623 seen = computed;
624 } else if (iteratee) {
625 if (!_.contains(seen, computed)) {
626 seen.push(computed);
627 result.push(value);
628 }
629 } else if (!_.contains(result, value)) {
630 result.push(value);
631 }
632 }
633 return result;
634 };
635
636 // Produce an array that contains the union: each distinct element from all of
637 // the passed-in arrays.
638 _.union = restArguments(function(arrays) {
639 return _.uniq(flatten(arrays, true, true));
640 });
641
642 // Produce an array that contains every item shared between all the
643 // passed-in arrays.
644 _.intersection = function(array) {
645 var result = [];
646 var argsLength = arguments.length;
647 for (var i = 0, length = getLength(array); i < length; i++) {
648 var item = array[i];
649 if (_.contains(result, item)) continue;
650 var j;
651 for (j = 1; j < argsLength; j++) {
652 if (!_.contains(arguments[j], item)) break;
653 }
654 if (j === argsLength) result.push(item);
655 }
656 return result;
657 };
658
659 // Take the difference between one array and a number of other arrays.
660 // Only the elements present in just the first array will remain.
661 _.difference = restArguments(function(array, rest) {
662 rest = flatten(rest, true, true);
663 return _.filter(array, function(value){
664 return !_.contains(rest, value);
665 });
666 });
667
668 // Complement of _.zip. Unzip accepts an array of arrays and groups
669 // each array's elements on shared indices.
670 _.unzip = function(array) {
671 var length = array && _.max(array, getLength).length || 0;
672 var result = Array(length);
673
674 for (var index = 0; index < length; index++) {
675 result[index] = _.pluck(array, index);
676 }
677 return result;
678 };
679
680 // Zip together multiple lists into a single array -- elements that share
681 // an index go together.
682 _.zip = restArguments(_.unzip);
683
684 // Converts lists into objects. Pass either a single array of `[key, value]`
685 // pairs, or two parallel arrays of the same length -- one of keys, and one of
686 // the corresponding values. Passing by pairs is the reverse of _.pairs.
687 _.object = function(list, values) {
688 var result = {};
689 for (var i = 0, length = getLength(list); i < length; i++) {
690 if (values) {
691 result[list[i]] = values[i];
692 } else {
693 result[list[i][0]] = list[i][1];
694 }
695 }
696 return result;
697 };
698
699 // Generator function to create the findIndex and findLastIndex functions.
700 var createPredicateIndexFinder = function(dir) {
701 return function(array, predicate, context) {
702 predicate = cb(predicate, context);
703 var length = getLength(array);
704 var index = dir > 0 ? 0 : length - 1;
705 for (; index >= 0 && index < length; index += dir) {
706 if (predicate(array[index], index, array)) return index;
707 }
708 return -1;
709 };
710 };
711
712 // Returns the first index on an array-like that passes a predicate test.
713 _.findIndex = createPredicateIndexFinder(1);
714 _.findLastIndex = createPredicateIndexFinder(-1);
715
716 // Use a comparator function to figure out the smallest index at which
717 // an object should be inserted so as to maintain order. Uses binary search.
718 _.sortedIndex = function(array, obj, iteratee, context) {
719 iteratee = cb(iteratee, context, 1);
720 var value = iteratee(obj);
721 var low = 0, high = getLength(array);
722 while (low < high) {
723 var mid = Math.floor((low + high) / 2);
724 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
725 }
726 return low;
727 };
728
729 // Generator function to create the indexOf and lastIndexOf functions.
730 var createIndexFinder = function(dir, predicateFind, sortedIndex) {
731 return function(array, item, idx) {
732 var i = 0, length = getLength(array);
733 if (typeof idx == 'number') {
734 if (dir > 0) {
735 i = idx >= 0 ? idx : Math.max(idx + length, i);
736 } else {
737 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
738 }
739 } else if (sortedIndex && idx && length) {
740 idx = sortedIndex(array, item);
741 return array[idx] === item ? idx : -1;
742 }
743 if (item !== item) {
744 idx = predicateFind(slice.call(array, i, length), _.isNaN);
745 return idx >= 0 ? idx + i : -1;
746 }
747 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
748 if (array[idx] === item) return idx;
749 }
750 return -1;
751 };
752 };
753
754 // Return the position of the first occurrence of an item in an array,
755 // or -1 if the item is not included in the array.
756 // If the array is large and already in sort order, pass `true`
757 // for **isSorted** to use binary search.
758 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
759 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
760
761 // Generate an integer Array containing an arithmetic progression. A port of
762 // the native Python `range()` function. See
763 // [the Python documentation](http://docs.python.org/library/functions.html#range).
764 _.range = function(start, stop, step) {
765 if (stop == null) {
766 stop = start || 0;
767 start = 0;
768 }
769 if (!step) {
770 step = stop < start ? -1 : 1;
771 }
772
773 var length = Math.max(Math.ceil((stop - start) / step), 0);
774 var range = Array(length);
775
776 for (var idx = 0; idx < length; idx++, start += step) {
777 range[idx] = start;
778 }
779
780 return range;
781 };
782
783 // Chunk a single array into multiple arrays, each containing `count` or fewer
784 // items.
785 _.chunk = function(array, count) {
786 if (count == null || count < 1) return [];
787 var result = [];
788 var i = 0, length = array.length;
789 while (i < length) {
790 result.push(slice.call(array, i, i += count));
791 }
792 return result;
793 };
794
795 // Function (ahem) Functions
796 // ------------------
797
798 // Determines whether to execute a function as a constructor
799 // or a normal function with the provided arguments.
800 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
801 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
802 var self = baseCreate(sourceFunc.prototype);
803 var result = sourceFunc.apply(self, args);
804 if (_.isObject(result)) return result;
805 return self;
806 };
807
808 // Create a function bound to a given object (assigning `this`, and arguments,
809 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
810 // available.
811 _.bind = restArguments(function(func, context, args) {
812 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
813 var bound = restArguments(function(callArgs) {
814 return executeBound(func, bound, context, this, args.concat(callArgs));
815 });
816 return bound;
817 });
818
819 // Partially apply a function by creating a version that has had some of its
820 // arguments pre-filled, without changing its dynamic `this` context. _ acts
821 // as a placeholder by default, allowing any combination of arguments to be
822 // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
823 _.partial = restArguments(function(func, boundArgs) {
824 var placeholder = _.partial.placeholder;
825 var bound = function() {
826 var position = 0, length = boundArgs.length;
827 var args = Array(length);
828 for (var i = 0; i < length; i++) {
829 args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
830 }
831 while (position < arguments.length) args.push(arguments[position++]);
832 return executeBound(func, bound, this, this, args);
833 };
834 return bound;
835 });
836
837 _.partial.placeholder = _;
838
839 // Bind a number of an object's methods to that object. Remaining arguments
840 // are the method names to be bound. Useful for ensuring that all callbacks
841 // defined on an object belong to it.
842 _.bindAll = restArguments(function(obj, keys) {
843 keys = flatten(keys, false, false);
844 var index = keys.length;
845 if (index < 1) throw new Error('bindAll must be passed function names');
846 while (index--) {
847 var key = keys[index];
848 obj[key] = _.bind(obj[key], obj);
849 }
850 });
851
852 // Memoize an expensive function by storing its results.
853 _.memoize = function(func, hasher) {
854 var memoize = function(key) {
855 var cache = memoize.cache;
856 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
857 if (!has(cache, address)) cache[address] = func.apply(this, arguments);
858 return cache[address];
859 };
860 memoize.cache = {};
861 return memoize;
862 };
863
864 // Delays a function for the given number of milliseconds, and then calls
865 // it with the arguments supplied.
866 _.delay = restArguments(function(func, wait, args) {
867 return setTimeout(function() {
868 return func.apply(null, args);
869 }, wait);
870 });
871
872 // Defers a function, scheduling it to run after the current call stack has
873 // cleared.
874 _.defer = _.partial(_.delay, _, 1);
875
876 // Returns a function, that, when invoked, will only be triggered at most once
877 // during a given window of time. Normally, the throttled function will run
878 // as much as it can, without ever going more than once per `wait` duration;
879 // but if you'd like to disable the execution on the leading edge, pass
880 // `{leading: false}`. To disable execution on the trailing edge, ditto.
881 _.throttle = function(func, wait, options) {
882 var timeout, context, args, result;
883 var previous = 0;
884 if (!options) options = {};
885
886 var later = function() {
887 previous = options.leading === false ? 0 : _.now();
888 timeout = null;
889 result = func.apply(context, args);
890 if (!timeout) context = args = null;
891 };
892
893 var throttled = function() {
894 var now = _.now();
895 if (!previous && options.leading === false) previous = now;
896 var remaining = wait - (now - previous);
897 context = this;
898 args = arguments;
899 if (remaining <= 0 || remaining > wait) {
900 if (timeout) {
901 clearTimeout(timeout);
902 timeout = null;
903 }
904 previous = now;
905 result = func.apply(context, args);
906 if (!timeout) context = args = null;
907 } else if (!timeout && options.trailing !== false) {
908 timeout = setTimeout(later, remaining);
909 }
910 return result;
911 };
912
913 throttled.cancel = function() {
914 clearTimeout(timeout);
915 previous = 0;
916 timeout = context = args = null;
917 };
918
919 return throttled;
920 };
921
922 // Returns a function, that, as long as it continues to be invoked, will not
923 // be triggered. The function will be called after it stops being called for
924 // N milliseconds. If `immediate` is passed, trigger the function on the
925 // leading edge, instead of the trailing.
926 _.debounce = function(func, wait, immediate) {
927 var timeout, result;
928
929 var later = function(context, args) {
930 timeout = null;
931 if (args) result = func.apply(context, args);
932 };
933
934 var debounced = restArguments(function(args) {
935 if (timeout) clearTimeout(timeout);
936 if (immediate) {
937 var callNow = !timeout;
938 timeout = setTimeout(later, wait);
939 if (callNow) result = func.apply(this, args);
940 } else {
941 timeout = _.delay(later, wait, this, args);
942 }
943
944 return result;
945 });
946
947 debounced.cancel = function() {
948 clearTimeout(timeout);
949 timeout = null;
950 };
951
952 return debounced;
953 };
954
955 // Returns the first function passed as an argument to the second,
956 // allowing you to adjust arguments, run code before and after, and
957 // conditionally execute the original function.
958 _.wrap = function(func, wrapper) {
959 return _.partial(wrapper, func);
960 };
961
962 // Returns a negated version of the passed-in predicate.
963 _.negate = function(predicate) {
964 return function() {
965 return !predicate.apply(this, arguments);
966 };
967 };
968
969 // Returns a function that is the composition of a list of functions, each
970 // consuming the return value of the function that follows.
971 _.compose = function() {
972 var args = arguments;
973 var start = args.length - 1;
974 return function() {
975 var i = start;
976 var result = args[start].apply(this, arguments);
977 while (i--) result = args[i].call(this, result);
978 return result;
979 };
980 };
981
982 // Returns a function that will only be executed on and after the Nth call.
983 _.after = function(times, func) {
984 return function() {
985 if (--times < 1) {
986 return func.apply(this, arguments);
987 }
988 };
989 };
990
991 // Returns a function that will only be executed up to (but not including) the Nth call.
992 _.before = function(times, func) {
993 var memo;
994 return function() {
995 if (--times > 0) {
996 memo = func.apply(this, arguments);
997 }
998 if (times <= 1) func = null;
999 return memo;
1000 };
1001 };
1002
1003 // Returns a function that will be executed at most one time, no matter how
1004 // often you call it. Useful for lazy initialization.
1005 _.once = _.partial(_.before, 2);
1006
1007 _.restArguments = restArguments;
1008
1009 // Object Functions
1010 // ----------------
1011
1012 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
1013 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
1014 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
1015 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
1016
1017 var collectNonEnumProps = function(obj, keys) {
1018 var nonEnumIdx = nonEnumerableProps.length;
1019 var constructor = obj.constructor;
1020 var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;
1021
1022 // Constructor is a special case.
1023 var prop = 'constructor';
1024 if (has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
1025
1026 while (nonEnumIdx--) {
1027 prop = nonEnumerableProps[nonEnumIdx];
1028 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
1029 keys.push(prop);
1030 }
1031 }
1032 };
1033
1034 // Retrieve the names of an object's own properties.
1035 // Delegates to **ECMAScript 5**'s native `Object.keys`.
1036 _.keys = function(obj) {
1037 if (!_.isObject(obj)) return [];
1038 if (nativeKeys) return nativeKeys(obj);
1039 var keys = [];
1040 for (var key in obj) if (has(obj, key)) keys.push(key);
1041 // Ahem, IE < 9.
1042 if (hasEnumBug) collectNonEnumProps(obj, keys);
1043 return keys;
1044 };
1045
1046 // Retrieve all the property names of an object.
1047 _.allKeys = function(obj) {
1048 if (!_.isObject(obj)) return [];
1049 var keys = [];
1050 for (var key in obj) keys.push(key);
1051 // Ahem, IE < 9.
1052 if (hasEnumBug) collectNonEnumProps(obj, keys);
1053 return keys;
1054 };
1055
1056 // Retrieve the values of an object's properties.
1057 _.values = function(obj) {
1058 var keys = _.keys(obj);
1059 var length = keys.length;
1060 var values = Array(length);
1061 for (var i = 0; i < length; i++) {
1062 values[i] = obj[keys[i]];
1063 }
1064 return values;
1065 };
1066
1067 // Returns the results of applying the iteratee to each element of the object.
1068 // In contrast to _.map it returns an object.
1069 _.mapObject = function(obj, iteratee, context) {
1070 iteratee = cb(iteratee, context);
1071 var keys = _.keys(obj),
1072 length = keys.length,
1073 results = {};
1074 for (var index = 0; index < length; index++) {
1075 var currentKey = keys[index];
1076 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
1077 }
1078 return results;
1079 };
1080
1081 // Convert an object into a list of `[key, value]` pairs.
1082 // The opposite of _.object.
1083 _.pairs = function(obj) {
1084 var keys = _.keys(obj);
1085 var length = keys.length;
1086 var pairs = Array(length);
1087 for (var i = 0; i < length; i++) {
1088 pairs[i] = [keys[i], obj[keys[i]]];
1089 }
1090 return pairs;
1091 };
1092
1093 // Invert the keys and values of an object. The values must be serializable.
1094 _.invert = function(obj) {
1095 var result = {};
1096 var keys = _.keys(obj);
1097 for (var i = 0, length = keys.length; i < length; i++) {
1098 result[obj[keys[i]]] = keys[i];
1099 }
1100 return result;
1101 };
1102
1103 // Return a sorted list of the function names available on the object.
1104 // Aliased as `methods`.
1105 _.functions = _.methods = function(obj) {
1106 var names = [];
1107 for (var key in obj) {
1108 if (_.isFunction(obj[key])) names.push(key);
1109 }
1110 return names.sort();
1111 };
1112
1113 // An internal function for creating assigner functions.
1114 var createAssigner = function(keysFunc, defaults) {
1115 return function(obj) {
1116 var length = arguments.length;
1117 if (defaults) obj = Object(obj);
1118 if (length < 2 || obj == null) return obj;
1119 for (var index = 1; index < length; index++) {
1120 var source = arguments[index],
1121 keys = keysFunc(source),
1122 l = keys.length;
1123 for (var i = 0; i < l; i++) {
1124 var key = keys[i];
1125 if (!defaults || obj[key] === void 0) obj[key] = source[key];
1126 }
1127 }
1128 return obj;
1129 };
1130 };
1131
1132 // Extend a given object with all the properties in passed-in object(s).
1133 _.extend = createAssigner(_.allKeys);
1134
1135 // Assigns a given object with all the own properties in the passed-in object(s).
1136 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
1137 _.extendOwn = _.assign = createAssigner(_.keys);
1138
1139 // Returns the first key on an object that passes a predicate test.
1140 _.findKey = function(obj, predicate, context) {
1141 predicate = cb(predicate, context);
1142 var keys = _.keys(obj), key;
1143 for (var i = 0, length = keys.length; i < length; i++) {
1144 key = keys[i];
1145 if (predicate(obj[key], key, obj)) return key;
1146 }
1147 };
1148
1149 // Internal pick helper function to determine if `obj` has key `key`.
1150 var keyInObj = function(value, key, obj) {
1151 return key in obj;
1152 };
1153
1154 // Return a copy of the object only containing the whitelisted properties.
1155 _.pick = restArguments(function(obj, keys) {
1156 var result = {}, iteratee = keys[0];
1157 if (obj == null) return result;
1158 if (_.isFunction(iteratee)) {
1159 if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
1160 keys = _.allKeys(obj);
1161 } else {
1162 iteratee = keyInObj;
1163 keys = flatten(keys, false, false);
1164 obj = Object(obj);
1165 }
1166 for (var i = 0, length = keys.length; i < length; i++) {
1167 var key = keys[i];
1168 var value = obj[key];
1169 if (iteratee(value, key, obj)) result[key] = value;
1170 }
1171 return result;
1172 });
1173
1174 // Return a copy of the object without the blacklisted properties.
1175 _.omit = restArguments(function(obj, keys) {
1176 var iteratee = keys[0], context;
1177 if (_.isFunction(iteratee)) {
1178 iteratee = _.negate(iteratee);
1179 if (keys.length > 1) context = keys[1];
1180 } else {
1181 keys = _.map(flatten(keys, false, false), String);
1182 iteratee = function(value, key) {
1183 return !_.contains(keys, key);
1184 };
1185 }
1186 return _.pick(obj, iteratee, context);
1187 });
1188
1189 // Fill in a given object with default properties.
1190 _.defaults = createAssigner(_.allKeys, true);
1191
1192 // Creates an object that inherits from the given prototype object.
1193 // If additional properties are provided then they will be added to the
1194 // created object.
1195 _.create = function(prototype, props) {
1196 var result = baseCreate(prototype);
1197 if (props) _.extendOwn(result, props);
1198 return result;
1199 };
1200
1201 // Create a (shallow-cloned) duplicate of an object.
1202 _.clone = function(obj) {
1203 if (!_.isObject(obj)) return obj;
1204 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
1205 };
1206
1207 // Invokes interceptor with the obj, and then returns obj.
1208 // The primary purpose of this method is to "tap into" a method chain, in
1209 // order to perform operations on intermediate results within the chain.
1210 _.tap = function(obj, interceptor) {
1211 interceptor(obj);
1212 return obj;
1213 };
1214
1215 // Returns whether an object has a given set of `key:value` pairs.
1216 _.isMatch = function(object, attrs) {
1217 var keys = _.keys(attrs), length = keys.length;
1218 if (object == null) return !length;
1219 var obj = Object(object);
1220 for (var i = 0; i < length; i++) {
1221 var key = keys[i];
1222 if (attrs[key] !== obj[key] || !(key in obj)) return false;
1223 }
1224 return true;
1225 };
1226
1227
1228 // Internal recursive comparison function for `isEqual`.
1229 var eq, deepEq;
1230 eq = function(a, b, aStack, bStack) {
1231 // Identical objects are equal. `0 === -0`, but they aren't identical.
1232 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
1233 if (a === b) return a !== 0 || 1 / a === 1 / b;
1234 // `null` or `undefined` only equal to itself (strict comparison).
1235 if (a == null || b == null) return false;
1236 // `NaN`s are equivalent, but non-reflexive.
1237 if (a !== a) return b !== b;
1238 // Exhaust primitive checks
1239 var type = typeof a;
1240 if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
1241 return deepEq(a, b, aStack, bStack);
1242 };
1243
1244 // Internal recursive comparison function for `isEqual`.
1245 deepEq = function(a, b, aStack, bStack) {
1246 // Unwrap any wrapped objects.
1247 if (a instanceof _) a = a._wrapped;
1248 if (b instanceof _) b = b._wrapped;
1249 // Compare `[[Class]]` names.
1250 var className = toString.call(a);
1251 if (className !== toString.call(b)) return false;
1252 switch (className) {
1253 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
1254 case '[object RegExp]':
1255 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
1256 case '[object String]':
1257 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
1258 // equivalent to `new String("5")`.
1259 return '' + a === '' + b;
1260 case '[object Number]':
1261 // `NaN`s are equivalent, but non-reflexive.
1262 // Object(NaN) is equivalent to NaN.
1263 if (+a !== +a) return +b !== +b;
1264 // An `egal` comparison is performed for other numeric values.
1265 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
1266 case '[object Date]':
1267 case '[object Boolean]':
1268 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
1269 // millisecond representations. Note that invalid dates with millisecond representations
1270 // of `NaN` are not equivalent.
1271 return +a === +b;
1272 case '[object Symbol]':
1273 return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
1274 }
1275
1276 var areArrays = className === '[object Array]';
1277 if (!areArrays) {
1278 if (typeof a != 'object' || typeof b != 'object') return false;
1279
1280 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
1281 // from different frames are.
1282 var aCtor = a.constructor, bCtor = b.constructor;
1283 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
1284 _.isFunction(bCtor) && bCtor instanceof bCtor)
1285 && ('constructor' in a && 'constructor' in b)) {
1286 return false;
1287 }
1288 }
1289 // Assume equality for cyclic structures. The algorithm for detecting cyclic
1290 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
1291
1292 // Initializing stack of traversed objects.
1293 // It's done here since we only need them for objects and arrays comparison.
1294 aStack = aStack || [];
1295 bStack = bStack || [];
1296 var length = aStack.length;
1297 while (length--) {
1298 // Linear search. Performance is inversely proportional to the number of
1299 // unique nested structures.
1300 if (aStack[length] === a) return bStack[length] === b;
1301 }
1302
1303 // Add the first object to the stack of traversed objects.
1304 aStack.push(a);
1305 bStack.push(b);
1306
1307 // Recursively compare objects and arrays.
1308 if (areArrays) {
1309 // Compare array lengths to determine if a deep comparison is necessary.
1310 length = a.length;
1311 if (length !== b.length) return false;
1312 // Deep compare the contents, ignoring non-numeric properties.
1313 while (length--) {
1314 if (!eq(a[length], b[length], aStack, bStack)) return false;
1315 }
1316 } else {
1317 // Deep compare objects.
1318 var keys = _.keys(a), key;
1319 length = keys.length;
1320 // Ensure that both objects contain the same number of properties before comparing deep equality.
1321 if (_.keys(b).length !== length) return false;
1322 while (length--) {
1323 // Deep compare each member
1324 key = keys[length];
1325 if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
1326 }
1327 }
1328 // Remove the first object from the stack of traversed objects.
1329 aStack.pop();
1330 bStack.pop();
1331 return true;
1332 };
1333
1334 // Perform a deep comparison to check if two objects are equal.
1335 _.isEqual = function(a, b) {
1336 return eq(a, b);
1337 };
1338
1339 // Is a given array, string, or object empty?
1340 // An "empty" object has no enumerable own-properties.
1341 _.isEmpty = function(obj) {
1342 if (obj == null) return true;
1343 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
1344 return _.keys(obj).length === 0;
1345 };
1346
1347 // Is a given value a DOM element?
1348 _.isElement = function(obj) {
1349 return !!(obj && obj.nodeType === 1);
1350 };
1351
1352 // Is a given value an array?
1353 // Delegates to ECMA5's native Array.isArray
1354 _.isArray = nativeIsArray || function(obj) {
1355 return toString.call(obj) === '[object Array]';
1356 };
1357
1358 // Is a given variable an object?
1359 _.isObject = function(obj) {
1360 var type = typeof obj;
1361 return type === 'function' || type === 'object' && !!obj;
1362 };
1363
1364 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet.
1365 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) {
1366 _['is' + name] = function(obj) {
1367 return toString.call(obj) === '[object ' + name + ']';
1368 };
1369 });
1370
1371 // Define a fallback version of the method in browsers (ahem, IE < 9), where
1372 // there isn't any inspectable "Arguments" type.
1373 if (!_.isArguments(arguments)) {
1374 _.isArguments = function(obj) {
1375 return has(obj, 'callee');
1376 };
1377 }
1378
1379 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
1380 // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
1381 var nodelist = root.document && root.document.childNodes;
1382 if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
1383 _.isFunction = function(obj) {
1384 return typeof obj == 'function' || false;
1385 };
1386 }
1387
1388 // Is a given object a finite number?
1389 _.isFinite = function(obj) {
1390 return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj));
1391 };
1392
1393 // Is the given value `NaN`?
1394 _.isNaN = function(obj) {
1395 return _.isNumber(obj) && isNaN(obj);
1396 };
1397
1398 // Is a given value a boolean?
1399 _.isBoolean = function(obj) {
1400 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
1401 };
1402
1403 // Is a given value equal to null?
1404 _.isNull = function(obj) {
1405 return obj === null;
1406 };
1407
1408 // Is a given variable undefined?
1409 _.isUndefined = function(obj) {
1410 return obj === void 0;
1411 };
1412
1413 // Shortcut function for checking if an object has a given property directly
1414 // on itself (in other words, not on a prototype).
1415 _.has = function(obj, path) {
1416 if (!_.isArray(path)) {
1417 return has(obj, path);
1418 }
1419 var length = path.length;
1420 for (var i = 0; i < length; i++) {
1421 var key = path[i];
1422 if (obj == null || !hasOwnProperty.call(obj, key)) {
1423 return false;
1424 }
1425 obj = obj[key];
1426 }
1427 return !!length;
1428 };
1429
1430 // Utility Functions
1431 // -----------------
1432
1433 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
1434 // previous owner. Returns a reference to the Underscore object.
1435 _.noConflict = function() {
1436 root._ = previousUnderscore;
1437 return this;
1438 };
1439
1440 // Keep the identity function around for default iteratees.
1441 _.identity = function(value) {
1442 return value;
1443 };
1444
1445 // Predicate-generating functions. Often useful outside of Underscore.
1446 _.constant = function(value) {
1447 return function() {
1448 return value;
1449 };
1450 };
1451
1452 _.noop = function(){};
1453
1454 // Creates a function that, when passed an object, will traverse that object’s
1455 // properties down the given `path`, specified as an array of keys or indexes.
1456 _.property = function(path) {
1457 if (!_.isArray(path)) {
1458 return shallowProperty(path);
1459 }
1460 return function(obj) {
1461 return deepGet(obj, path);
1462 };
1463 };
1464
1465 // Generates a function for a given object that returns a given property.
1466 _.propertyOf = function(obj) {
1467 if (obj == null) {
1468 return function(){};
1469 }
1470 return function(path) {
1471 return !_.isArray(path) ? obj[path] : deepGet(obj, path);
1472 };
1473 };
1474
1475 // Returns a predicate for checking whether an object has a given set of
1476 // `key:value` pairs.
1477 _.matcher = _.matches = function(attrs) {
1478 attrs = _.extendOwn({}, attrs);
1479 return function(obj) {
1480 return _.isMatch(obj, attrs);
1481 };
1482 };
1483
1484 // Run a function **n** times.
1485 _.times = function(n, iteratee, context) {
1486 var accum = Array(Math.max(0, n));
1487 iteratee = optimizeCb(iteratee, context, 1);
1488 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
1489 return accum;
1490 };
1491
1492 // Return a random integer between min and max (inclusive).
1493 _.random = function(min, max) {
1494 if (max == null) {
1495 max = min;
1496 min = 0;
1497 }
1498 return min + Math.floor(Math.random() * (max - min + 1));
1499 };
1500
1501 // A (possibly faster) way to get the current timestamp as an integer.
1502 _.now = Date.now || function() {
1503 return new Date().getTime();
1504 };
1505
1506 // List of HTML entities for escaping.
1507 var escapeMap = {
1508 '&': '&',
1509 '<': '<',
1510 '>': '>',
1511 '"': '"',
1512 "'": ''',
1513 '`': '`'
1514 };
1515 var unescapeMap = _.invert(escapeMap);
1516
1517 // Functions for escaping and unescaping strings to/from HTML interpolation.
1518 var createEscaper = function(map) {
1519 var escaper = function(match) {
1520 return map[match];
1521 };
1522 // Regexes for identifying a key that needs to be escaped.
1523 var source = '(?:' + _.keys(map).join('|') + ')';
1524 var testRegexp = RegExp(source);
1525 var replaceRegexp = RegExp(source, 'g');
1526 return function(string) {
1527 string = string == null ? '' : '' + string;
1528 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
1529 };
1530 };
1531 _.escape = createEscaper(escapeMap);
1532 _.unescape = createEscaper(unescapeMap);
1533
1534 // Traverses the children of `obj` along `path`. If a child is a function, it
1535 // is invoked with its parent as context. Returns the value of the final
1536 // child, or `fallback` if any child is undefined.
1537 _.result = function(obj, path, fallback) {
1538 if (!_.isArray(path)) path = [path];
1539 var length = path.length;
1540 if (!length) {
1541 return _.isFunction(fallback) ? fallback.call(obj) : fallback;
1542 }
1543 for (var i = 0; i < length; i++) {
1544 var prop = obj == null ? void 0 : obj[path[i]];
1545 if (prop === void 0) {
1546 prop = fallback;
1547 i = length; // Ensure we don't continue iterating.
1548 }
1549 obj = _.isFunction(prop) ? prop.call(obj) : prop;
1550 }
1551 return obj;
1552 };
1553
1554 // Generate a unique integer id (unique within the entire client session).
1555 // Useful for temporary DOM ids.
1556 var idCounter = 0;
1557 _.uniqueId = function(prefix) {
1558 var id = ++idCounter + '';
1559 return prefix ? prefix + id : id;
1560 };
1561
1562 // By default, Underscore uses ERB-style template delimiters, change the
1563 // following template settings to use alternative delimiters.
1564 _.templateSettings = {
1565 evaluate: /<%([\s\S]+?)%>/g,
1566 interpolate: /<%=([\s\S]+?)%>/g,
1567 escape: /<%-([\s\S]+?)%>/g
1568 };
1569
1570 // When customizing `templateSettings`, if you don't want to define an
1571 // interpolation, evaluation or escaping regex, we need one that is
1572 // guaranteed not to match.
1573 var noMatch = /(.)^/;
1574
1575 // Certain characters need to be escaped so that they can be put into a
1576 // string literal.
1577 var escapes = {
1578 "'": "'",
1579 '\\': '\\',
1580 '\r': 'r',
1581 '\n': 'n',
1582 '\u2028': 'u2028',
1583 '\u2029': 'u2029'
1584 };
1585
1586 var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
1587
1588 var escapeChar = function(match) {
1589 return '\\' + escapes[match];
1590 };
1591
1592 // JavaScript micro-templating, similar to John Resig's implementation.
1593 // Underscore templating handles arbitrary delimiters, preserves whitespace,
1594 // and correctly escapes quotes within interpolated code.
1595 // NB: `oldSettings` only exists for backwards compatibility.
1596 _.template = function(text, settings, oldSettings) {
1597 if (!settings && oldSettings) settings = oldSettings;
1598 settings = _.defaults({}, settings, _.templateSettings);
1599
1600 // Combine delimiters into one regular expression via alternation.
1601 var matcher = RegExp([
1602 (settings.escape || noMatch).source,
1603 (settings.interpolate || noMatch).source,
1604 (settings.evaluate || noMatch).source
1605 ].join('|') + '|$', 'g');
1606
1607 // Compile the template source, escaping string literals appropriately.
1608 var index = 0;
1609 var source = "__p+='";
1610 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
1611 source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
1612 index = offset + match.length;
1613
1614 if (escape) {
1615 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
1616 } else if (interpolate) {
1617 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
1618 } else if (evaluate) {
1619 source += "';\n" + evaluate + "\n__p+='";
1620 }
1621
1622 // Adobe VMs need the match returned to produce the correct offset.
1623 return match;
1624 });
1625 source += "';\n";
1626
1627 // If a variable is not specified, place data values in local scope.
1628 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1629
1630 source = "var __t,__p='',__j=Array.prototype.join," +
1631 "print=function(){__p+=__j.call(arguments,'');};\n" +
1632 source + 'return __p;\n';
1633
1634 var render;
1635 try {
1636 render = new Function(settings.variable || 'obj', '_', source);
1637 } catch (e) {
1638 e.source = source;
1639 throw e;
1640 }
1641
1642 var template = function(data) {
1643 return render.call(this, data, _);
1644 };
1645
1646 // Provide the compiled source as a convenience for precompilation.
1647 var argument = settings.variable || 'obj';
1648 template.source = 'function(' + argument + '){\n' + source + '}';
1649
1650 return template;
1651 };
1652
1653 // Add a "chain" function. Start chaining a wrapped Underscore object.
1654 _.chain = function(obj) {
1655 var instance = _(obj);
1656 instance._chain = true;
1657 return instance;
1658 };
1659
1660 // OOP
1661 // ---------------
1662 // If Underscore is called as a function, it returns a wrapped object that
1663 // can be used OO-style. This wrapper holds altered versions of all the
1664 // underscore functions. Wrapped objects may be chained.
1665
1666 // Helper function to continue chaining intermediate results.
1667 var chainResult = function(instance, obj) {
1668 return instance._chain ? _(obj).chain() : obj;
1669 };
1670
1671 // Add your own custom functions to the Underscore object.
1672 _.mixin = function(obj) {
1673 _.each(_.functions(obj), function(name) {
1674 var func = _[name] = obj[name];
1675 _.prototype[name] = function() {
1676 var args = [this._wrapped];
1677 push.apply(args, arguments);
1678 return chainResult(this, func.apply(_, args));
1679 };
1680 });
1681 return _;
1682 };
1683
1684 // Add all of the Underscore functions to the wrapper object.
1685 _.mixin(_);
1686
1687 // Add all mutator Array functions to the wrapper.
1688 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1689 var method = ArrayProto[name];
1690 _.prototype[name] = function() {
1691 var obj = this._wrapped;
1692 method.apply(obj, arguments);
1693 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
1694 return chainResult(this, obj);
1695 };
1696 });
1697
1698 // Add all accessor Array functions to the wrapper.
1699 _.each(['concat', 'join', 'slice'], function(name) {
1700 var method = ArrayProto[name];
1701 _.prototype[name] = function() {
1702 return chainResult(this, method.apply(this._wrapped, arguments));
1703 };
1704 });
1705
1706 // Extracts the result from a wrapped and chained object.
1707 _.prototype.value = function() {
1708 return this._wrapped;
1709 };
1710
1711 // Provide unwrapping proxy for some methods used in engine operations
1712 // such as arithmetic and JSON stringification.
1713 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
1714
1715 _.prototype.toString = function() {
1716 return String(this._wrapped);
1717 };
1718 }());
1719 });
1720 var underscore_1 = underscore._;
1721
1722 function isNothing(subject) {
1723 return (typeof subject === 'undefined') || (subject === null);
1724 }
1725
1726
1727 function isObject(subject) {
1728 return (typeof subject === 'object') && (subject !== null);
1729 }
1730
1731
1732 function toArray(sequence) {
1733 if (Array.isArray(sequence)) return sequence;
1734 else if (isNothing(sequence)) return [];
1735
1736 return [ sequence ];
1737 }
1738
1739
1740 function extend(target, source) {
1741 var index, length, key, sourceKeys;
1742
1743 if (source) {
1744 sourceKeys = Object.keys(source);
1745
1746 for (index = 0, length = sourceKeys.length; index < length; index += 1) {
1747 key = sourceKeys[index];
1748 target[key] = source[key];
1749 }
1750 }
1751
1752 return target;
1753 }
1754
1755
1756 function repeat(string, count) {
1757 var result = '', cycle;
1758
1759 for (cycle = 0; cycle < count; cycle += 1) {
1760 result += string;
1761 }
1762
1763 return result;
1764 }
1765
1766
1767 function isNegativeZero(number) {
1768 return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
1769 }
1770
1771
1772 var isNothing_1 = isNothing;
1773 var isObject_1 = isObject;
1774 var toArray_1 = toArray;
1775 var repeat_1 = repeat;
1776 var isNegativeZero_1 = isNegativeZero;
1777 var extend_1 = extend;
1778
1779 var common = {
1780 isNothing: isNothing_1,
1781 isObject: isObject_1,
1782 toArray: toArray_1,
1783 repeat: repeat_1,
1784 isNegativeZero: isNegativeZero_1,
1785 extend: extend_1
1786 };
1787
1788 // YAML error class. http://stackoverflow.com/questions/8458984
1789
1790 function YAMLException(reason, mark) {
1791 // Super constructor
1792 Error.call(this);
1793
1794 this.name = 'YAMLException';
1795 this.reason = reason;
1796 this.mark = mark;
1797 this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
1798
1799 // Include stack trace in error object
1800 if (Error.captureStackTrace) {
1801 // Chrome and NodeJS
1802 Error.captureStackTrace(this, this.constructor);
1803 } else {
1804 // FF, IE 10+ and Safari 6+. Fallback for others
1805 this.stack = (new Error()).stack || '';
1806 }
1807 }
1808
1809
1810 // Inherit from Error
1811 YAMLException.prototype = Object.create(Error.prototype);
1812 YAMLException.prototype.constructor = YAMLException;
1813
1814
1815 YAMLException.prototype.toString = function toString(compact) {
1816 var result = this.name + ': ';
1817
1818 result += this.reason || '(unknown reason)';
1819
1820 if (!compact && this.mark) {
1821 result += ' ' + this.mark.toString();
1822 }
1823
1824 return result;
1825 };
1826
1827
1828 var exception = YAMLException;
1829
1830 function Mark(name, buffer, position, line, column) {
1831 this.name = name;
1832 this.buffer = buffer;
1833 this.position = position;
1834 this.line = line;
1835 this.column = column;
1836 }
1837
1838
1839 Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
1840 var head, start, tail, end, snippet;
1841
1842 if (!this.buffer) return null;
1843
1844 indent = indent || 4;
1845 maxLength = maxLength || 75;
1846
1847 head = '';
1848 start = this.position;
1849
1850 while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
1851 start -= 1;
1852 if (this.position - start > (maxLength / 2 - 1)) {
1853 head = ' ... ';
1854 start += 5;
1855 break;
1856 }
1857 }
1858
1859 tail = '';
1860 end = this.position;
1861
1862 while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
1863 end += 1;
1864 if (end - this.position > (maxLength / 2 - 1)) {
1865 tail = ' ... ';
1866 end -= 5;
1867 break;
1868 }
1869 }
1870
1871 snippet = this.buffer.slice(start, end);
1872
1873 return common.repeat(' ', indent) + head + snippet + tail + '\n' +
1874 common.repeat(' ', indent + this.position - start + head.length) + '^';
1875 };
1876
1877
1878 Mark.prototype.toString = function toString(compact) {
1879 var snippet, where = '';
1880
1881 if (this.name) {
1882 where += 'in "' + this.name + '" ';
1883 }
1884
1885 where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
1886
1887 if (!compact) {
1888 snippet = this.getSnippet();
1889
1890 if (snippet) {
1891 where += ':\n' + snippet;
1892 }
1893 }
1894
1895 return where;
1896 };
1897
1898
1899 var mark = Mark;
1900
1901 var TYPE_CONSTRUCTOR_OPTIONS = [
1902 'kind',
1903 'resolve',
1904 'construct',
1905 'instanceOf',
1906 'predicate',
1907 'represent',
1908 'defaultStyle',
1909 'styleAliases'
1910 ];
1911
1912 var YAML_NODE_KINDS = [
1913 'scalar',
1914 'sequence',
1915 'mapping'
1916 ];
1917
1918 function compileStyleAliases(map) {
1919 var result = {};
1920
1921 if (map !== null) {
1922 Object.keys(map).forEach(function (style) {
1923 map[style].forEach(function (alias) {
1924 result[String(alias)] = style;
1925 });
1926 });
1927 }
1928
1929 return result;
1930 }
1931
1932 function Type(tag, options) {
1933 options = options || {};
1934
1935 Object.keys(options).forEach(function (name) {
1936 if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
1937 throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
1938 }
1939 });
1940
1941 // TODO: Add tag format check.
1942 this.tag = tag;
1943 this.kind = options['kind'] || null;
1944 this.resolve = options['resolve'] || function () { return true; };
1945 this.construct = options['construct'] || function (data) { return data; };
1946 this.instanceOf = options['instanceOf'] || null;
1947 this.predicate = options['predicate'] || null;
1948 this.represent = options['represent'] || null;
1949 this.defaultStyle = options['defaultStyle'] || null;
1950 this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
1951
1952 if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
1953 throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
1954 }
1955 }
1956
1957 var type = Type;
1958
1959 /*eslint-disable max-len*/
1960
1961
1962
1963
1964
1965
1966 function compileList(schema, name, result) {
1967 var exclude = [];
1968
1969 schema.include.forEach(function (includedSchema) {
1970 result = compileList(includedSchema, name, result);
1971 });
1972
1973 schema[name].forEach(function (currentType) {
1974 result.forEach(function (previousType, previousIndex) {
1975 if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
1976 exclude.push(previousIndex);
1977 }
1978 });
1979
1980 result.push(currentType);
1981 });
1982
1983 return result.filter(function (type, index) {
1984 return exclude.indexOf(index) === -1;
1985 });
1986 }
1987
1988
1989 function compileMap(/* lists... */) {
1990 var result = {
1991 scalar: {},
1992 sequence: {},
1993 mapping: {},
1994 fallback: {}
1995 }, index, length;
1996
1997 function collectType(type) {
1998 result[type.kind][type.tag] = result['fallback'][type.tag] = type;
1999 }
2000
2001 for (index = 0, length = arguments.length; index < length; index += 1) {
2002 arguments[index].forEach(collectType);
2003 }
2004 return result;
2005 }
2006
2007
2008 function Schema(definition) {
2009 this.include = definition.include || [];
2010 this.implicit = definition.implicit || [];
2011 this.explicit = definition.explicit || [];
2012
2013 this.implicit.forEach(function (type) {
2014 if (type.loadKind && type.loadKind !== 'scalar') {
2015 throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
2016 }
2017 });
2018
2019 this.compiledImplicit = compileList(this, 'implicit', []);
2020 this.compiledExplicit = compileList(this, 'explicit', []);
2021 this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
2022 }
2023
2024
2025 Schema.DEFAULT = null;
2026
2027
2028 Schema.create = function createSchema() {
2029 var schemas, types;
2030
2031 switch (arguments.length) {
2032 case 1:
2033 schemas = Schema.DEFAULT;
2034 types = arguments[0];
2035 break;
2036
2037 case 2:
2038 schemas = arguments[0];
2039 types = arguments[1];
2040 break;
2041
2042 default:
2043 throw new exception('Wrong number of arguments for Schema.create function');
2044 }
2045
2046 schemas = common.toArray(schemas);
2047 types = common.toArray(types);
2048
2049 if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
2050 throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
2051 }
2052
2053 if (!types.every(function (type$1) { return type$1 instanceof type; })) {
2054 throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
2055 }
2056
2057 return new Schema({
2058 include: schemas,
2059 explicit: types
2060 });
2061 };
2062
2063
2064 var schema = Schema;
2065
2066 var str = new type('tag:yaml.org,2002:str', {
2067 kind: 'scalar',
2068 construct: function (data) { return data !== null ? data : ''; }
2069 });
2070
2071 var seq = new type('tag:yaml.org,2002:seq', {
2072 kind: 'sequence',
2073 construct: function (data) { return data !== null ? data : []; }
2074 });
2075
2076 var map = new type('tag:yaml.org,2002:map', {
2077 kind: 'mapping',
2078 construct: function (data) { return data !== null ? data : {}; }
2079 });
2080
2081 var failsafe = new schema({
2082 explicit: [
2083 str,
2084 seq,
2085 map
2086 ]
2087 });
2088
2089 function resolveYamlNull(data) {
2090 if (data === null) return true;
2091
2092 var max = data.length;
2093
2094 return (max === 1 && data === '~') ||
2095 (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
2096 }
2097
2098 function constructYamlNull() {
2099 return null;
2100 }
2101
2102 function isNull(object) {
2103 return object === null;
2104 }
2105
2106 var _null = new type('tag:yaml.org,2002:null', {
2107 kind: 'scalar',
2108 resolve: resolveYamlNull,
2109 construct: constructYamlNull,
2110 predicate: isNull,
2111 represent: {
2112 canonical: function () { return '~'; },
2113 lowercase: function () { return 'null'; },
2114 uppercase: function () { return 'NULL'; },
2115 camelcase: function () { return 'Null'; }
2116 },
2117 defaultStyle: 'lowercase'
2118 });
2119
2120 function resolveYamlBoolean(data) {
2121 if (data === null) return false;
2122
2123 var max = data.length;
2124
2125 return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
2126 (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
2127 }
2128
2129 function constructYamlBoolean(data) {
2130 return data === 'true' ||
2131 data === 'True' ||
2132 data === 'TRUE';
2133 }
2134
2135 function isBoolean(object) {
2136 return Object.prototype.toString.call(object) === '[object Boolean]';
2137 }
2138
2139 var bool = new type('tag:yaml.org,2002:bool', {
2140 kind: 'scalar',
2141 resolve: resolveYamlBoolean,
2142 construct: constructYamlBoolean,
2143 predicate: isBoolean,
2144 represent: {
2145 lowercase: function (object) { return object ? 'true' : 'false'; },
2146 uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
2147 camelcase: function (object) { return object ? 'True' : 'False'; }
2148 },
2149 defaultStyle: 'lowercase'
2150 });
2151
2152 function isHexCode(c) {
2153 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
2154 ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
2155 ((0x61/* a */ <= c) && (c <= 0x66/* f */));
2156 }
2157
2158 function isOctCode(c) {
2159 return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
2160 }
2161
2162 function isDecCode(c) {
2163 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
2164 }
2165
2166 function resolveYamlInteger(data) {
2167 if (data === null) return false;
2168
2169 var max = data.length,
2170 index = 0,
2171 hasDigits = false,
2172 ch;
2173
2174 if (!max) return false;
2175
2176 ch = data[index];
2177
2178 // sign
2179 if (ch === '-' || ch === '+') {
2180 ch = data[++index];
2181 }
2182
2183 if (ch === '0') {
2184 // 0
2185 if (index + 1 === max) return true;
2186 ch = data[++index];
2187
2188 // base 2, base 8, base 16
2189
2190 if (ch === 'b') {
2191 // base 2
2192 index++;
2193
2194 for (; index < max; index++) {
2195 ch = data[index];
2196 if (ch === '_') continue;
2197 if (ch !== '0' && ch !== '1') return false;
2198 hasDigits = true;
2199 }
2200 return hasDigits && ch !== '_';
2201 }
2202
2203
2204 if (ch === 'x') {
2205 // base 16
2206 index++;
2207
2208 for (; index < max; index++) {
2209 ch = data[index];
2210 if (ch === '_') continue;
2211 if (!isHexCode(data.charCodeAt(index))) return false;
2212 hasDigits = true;
2213 }
2214 return hasDigits && ch !== '_';
2215 }
2216
2217 // base 8
2218 for (; index < max; index++) {
2219 ch = data[index];
2220 if (ch === '_') continue;
2221 if (!isOctCode(data.charCodeAt(index))) return false;
2222 hasDigits = true;
2223 }
2224 return hasDigits && ch !== '_';
2225 }
2226
2227 // base 10 (except 0) or base 60
2228
2229 // value should not start with `_`;
2230 if (ch === '_') return false;
2231
2232 for (; index < max; index++) {
2233 ch = data[index];
2234 if (ch === '_') continue;
2235 if (ch === ':') break;
2236 if (!isDecCode(data.charCodeAt(index))) {
2237 return false;
2238 }
2239 hasDigits = true;
2240 }
2241
2242 // Should have digits and should not end with `_`
2243 if (!hasDigits || ch === '_') return false;
2244
2245 // if !base60 - done;
2246 if (ch !== ':') return true;
2247
2248 // base60 almost not used, no needs to optimize
2249 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
2250 }
2251
2252 function constructYamlInteger(data) {
2253 var value = data, sign = 1, ch, base, digits = [];
2254
2255 if (value.indexOf('_') !== -1) {
2256 value = value.replace(/_/g, '');
2257 }
2258
2259 ch = value[0];
2260
2261 if (ch === '-' || ch === '+') {
2262 if (ch === '-') sign = -1;
2263 value = value.slice(1);
2264 ch = value[0];
2265 }
2266
2267 if (value === '0') return 0;
2268
2269 if (ch === '0') {
2270 if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
2271 if (value[1] === 'x') return sign * parseInt(value, 16);
2272 return sign * parseInt(value, 8);
2273 }
2274
2275 if (value.indexOf(':') !== -1) {
2276 value.split(':').forEach(function (v) {
2277 digits.unshift(parseInt(v, 10));
2278 });
2279
2280 value = 0;
2281 base = 1;
2282
2283 digits.forEach(function (d) {
2284 value += (d * base);
2285 base *= 60;
2286 });
2287
2288 return sign * value;
2289
2290 }
2291
2292 return sign * parseInt(value, 10);
2293 }
2294
2295 function isInteger(object) {
2296 return (Object.prototype.toString.call(object)) === '[object Number]' &&
2297 (object % 1 === 0 && !common.isNegativeZero(object));
2298 }
2299
2300 var int_1 = new type('tag:yaml.org,2002:int', {
2301 kind: 'scalar',
2302 resolve: resolveYamlInteger,
2303 construct: constructYamlInteger,
2304 predicate: isInteger,
2305 represent: {
2306 binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
2307 octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },
2308 decimal: function (obj) { return obj.toString(10); },
2309 /* eslint-disable max-len */
2310 hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
2311 },
2312 defaultStyle: 'decimal',
2313 styleAliases: {
2314 binary: [ 2, 'bin' ],
2315 octal: [ 8, 'oct' ],
2316 decimal: [ 10, 'dec' ],
2317 hexadecimal: [ 16, 'hex' ]
2318 }
2319 });
2320
2321 var YAML_FLOAT_PATTERN = new RegExp(
2322 // 2.5e4, 2.5 and integers
2323 '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
2324 // .2e4, .2
2325 // special case, seems not from spec
2326 '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
2327 // 20:59
2328 '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
2329 // .inf
2330 '|[-+]?\\.(?:inf|Inf|INF)' +
2331 // .nan
2332 '|\\.(?:nan|NaN|NAN))$');
2333
2334 function resolveYamlFloat(data) {
2335 if (data === null) return false;
2336
2337 if (!YAML_FLOAT_PATTERN.test(data) ||
2338 // Quick hack to not allow integers end with `_`
2339 // Probably should update regexp & check speed
2340 data[data.length - 1] === '_') {
2341 return false;
2342 }
2343
2344 return true;
2345 }
2346
2347 function constructYamlFloat(data) {
2348 var value, sign, base, digits;
2349
2350 value = data.replace(/_/g, '').toLowerCase();
2351 sign = value[0] === '-' ? -1 : 1;
2352 digits = [];
2353
2354 if ('+-'.indexOf(value[0]) >= 0) {
2355 value = value.slice(1);
2356 }
2357
2358 if (value === '.inf') {
2359 return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
2360
2361 } else if (value === '.nan') {
2362 return NaN;
2363
2364 } else if (value.indexOf(':') >= 0) {
2365 value.split(':').forEach(function (v) {
2366 digits.unshift(parseFloat(v, 10));
2367 });
2368
2369 value = 0.0;
2370 base = 1;
2371
2372 digits.forEach(function (d) {
2373 value += d * base;
2374 base *= 60;
2375 });
2376
2377 return sign * value;
2378
2379 }
2380 return sign * parseFloat(value, 10);
2381 }
2382
2383
2384 var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
2385
2386 function representYamlFloat(object, style) {
2387 var res;
2388
2389 if (isNaN(object)) {
2390 switch (style) {
2391 case 'lowercase': return '.nan';
2392 case 'uppercase': return '.NAN';
2393 case 'camelcase': return '.NaN';
2394 }
2395 } else if (Number.POSITIVE_INFINITY === object) {
2396 switch (style) {
2397 case 'lowercase': return '.inf';
2398 case 'uppercase': return '.INF';
2399 case 'camelcase': return '.Inf';
2400 }
2401 } else if (Number.NEGATIVE_INFINITY === object) {
2402 switch (style) {
2403 case 'lowercase': return '-.inf';
2404 case 'uppercase': return '-.INF';
2405 case 'camelcase': return '-.Inf';
2406 }
2407 } else if (common.isNegativeZero(object)) {
2408 return '-0.0';
2409 }
2410
2411 res = object.toString(10);
2412
2413 // JS stringifier can build scientific format without dots: 5e-100,
2414 // while YAML requres dot: 5.e-100. Fix it with simple hack
2415
2416 return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
2417 }
2418
2419 function isFloat(object) {
2420 return (Object.prototype.toString.call(object) === '[object Number]') &&
2421 (object % 1 !== 0 || common.isNegativeZero(object));
2422 }
2423
2424 var float_1 = new type('tag:yaml.org,2002:float', {
2425 kind: 'scalar',
2426 resolve: resolveYamlFloat,
2427 construct: constructYamlFloat,
2428 predicate: isFloat,
2429 represent: representYamlFloat,
2430 defaultStyle: 'lowercase'
2431 });
2432
2433 var json = new schema({
2434 include: [
2435 failsafe
2436 ],
2437 implicit: [
2438 _null,
2439 bool,
2440 int_1,
2441 float_1
2442 ]
2443 });
2444
2445 var core = new schema({
2446 include: [
2447 json
2448 ]
2449 });
2450
2451 var YAML_DATE_REGEXP = new RegExp(
2452 '^([0-9][0-9][0-9][0-9])' + // [1] year
2453 '-([0-9][0-9])' + // [2] month
2454 '-([0-9][0-9])$'); // [3] day
2455
2456 var YAML_TIMESTAMP_REGEXP = new RegExp(
2457 '^([0-9][0-9][0-9][0-9])' + // [1] year
2458 '-([0-9][0-9]?)' + // [2] month
2459 '-([0-9][0-9]?)' + // [3] day
2460 '(?:[Tt]|[ \\t]+)' + // ...
2461 '([0-9][0-9]?)' + // [4] hour
2462 ':([0-9][0-9])' + // [5] minute
2463 ':([0-9][0-9])' + // [6] second
2464 '(?:\\.([0-9]*))?' + // [7] fraction
2465 '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
2466 '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
2467
2468 function resolveYamlTimestamp(data) {
2469 if (data === null) return false;
2470 if (YAML_DATE_REGEXP.exec(data) !== null) return true;
2471 if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
2472 return false;
2473 }
2474
2475 function constructYamlTimestamp(data) {
2476 var match, year, month, day, hour, minute, second, fraction = 0,
2477 delta = null, tz_hour, tz_minute, date;
2478
2479 match = YAML_DATE_REGEXP.exec(data);
2480 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
2481
2482 if (match === null) throw new Error('Date resolve error');
2483
2484 // match: [1] year [2] month [3] day
2485
2486 year = +(match[1]);
2487 month = +(match[2]) - 1; // JS month starts with 0
2488 day = +(match[3]);
2489
2490 if (!match[4]) { // no hour
2491 return new Date(Date.UTC(year, month, day));
2492 }
2493
2494 // match: [4] hour [5] minute [6] second [7] fraction
2495
2496 hour = +(match[4]);
2497 minute = +(match[5]);
2498 second = +(match[6]);
2499
2500 if (match[7]) {
2501 fraction = match[7].slice(0, 3);
2502 while (fraction.length < 3) { // milli-seconds
2503 fraction += '0';
2504 }
2505 fraction = +fraction;
2506 }
2507
2508 // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
2509
2510 if (match[9]) {
2511 tz_hour = +(match[10]);
2512 tz_minute = +(match[11] || 0);
2513 delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
2514 if (match[9] === '-') delta = -delta;
2515 }
2516
2517 date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
2518
2519 if (delta) date.setTime(date.getTime() - delta);
2520
2521 return date;
2522 }
2523
2524 function representYamlTimestamp(object /*, style*/) {
2525 return object.toISOString();
2526 }
2527
2528 var timestamp = new type('tag:yaml.org,2002:timestamp', {
2529 kind: 'scalar',
2530 resolve: resolveYamlTimestamp,
2531 construct: constructYamlTimestamp,
2532 instanceOf: Date,
2533 represent: representYamlTimestamp
2534 });
2535
2536 function resolveYamlMerge(data) {
2537 return data === '<<' || data === null;
2538 }
2539
2540 var merge = new type('tag:yaml.org,2002:merge', {
2541 kind: 'scalar',
2542 resolve: resolveYamlMerge
2543 });
2544
2545 /*eslint-disable no-bitwise*/
2546
2547 var NodeBuffer;
2548
2549 try {
2550 // A trick for browserified version, to not include `Buffer` shim
2551 var _require = commonjsRequire;
2552 NodeBuffer = _require('buffer').Buffer;
2553 } catch (__) {}
2554
2555
2556
2557
2558 // [ 64, 65, 66 ] -> [ padding, CR, LF ]
2559 var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
2560
2561
2562 function resolveYamlBinary(data) {
2563 if (data === null) return false;
2564
2565 var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
2566
2567 // Convert one by one.
2568 for (idx = 0; idx < max; idx++) {
2569 code = map.indexOf(data.charAt(idx));
2570
2571 // Skip CR/LF
2572 if (code > 64) continue;
2573
2574 // Fail on illegal characters
2575 if (code < 0) return false;
2576
2577 bitlen += 6;
2578 }
2579
2580 // If there are any bits left, source was corrupted
2581 return (bitlen % 8) === 0;
2582 }
2583
2584 function constructYamlBinary(data) {
2585 var idx, tailbits,
2586 input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
2587 max = input.length,
2588 map = BASE64_MAP,
2589 bits = 0,
2590 result = [];
2591
2592 // Collect by 6*4 bits (3 bytes)
2593
2594 for (idx = 0; idx < max; idx++) {
2595 if ((idx % 4 === 0) && idx) {
2596 result.push((bits >> 16) & 0xFF);
2597 result.push((bits >> 8) & 0xFF);
2598 result.push(bits & 0xFF);
2599 }
2600
2601 bits = (bits << 6) | map.indexOf(input.charAt(idx));
2602 }
2603
2604 // Dump tail
2605
2606 tailbits = (max % 4) * 6;
2607
2608 if (tailbits === 0) {
2609 result.push((bits >> 16) & 0xFF);
2610 result.push((bits >> 8) & 0xFF);
2611 result.push(bits & 0xFF);
2612 } else if (tailbits === 18) {
2613 result.push((bits >> 10) & 0xFF);
2614 result.push((bits >> 2) & 0xFF);
2615 } else if (tailbits === 12) {
2616 result.push((bits >> 4) & 0xFF);
2617 }
2618
2619 // Wrap into Buffer for NodeJS and leave Array for browser
2620 if (NodeBuffer) {
2621 // Support node 6.+ Buffer API when available
2622 return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
2623 }
2624
2625 return result;
2626 }
2627
2628 function representYamlBinary(object /*, style*/) {
2629 var result = '', bits = 0, idx, tail,
2630 max = object.length,
2631 map = BASE64_MAP;
2632
2633 // Convert every three bytes to 4 ASCII characters.
2634
2635 for (idx = 0; idx < max; idx++) {
2636 if ((idx % 3 === 0) && idx) {
2637 result += map[(bits >> 18) & 0x3F];
2638 result += map[(bits >> 12) & 0x3F];
2639 result += map[(bits >> 6) & 0x3F];
2640 result += map[bits & 0x3F];
2641 }
2642
2643 bits = (bits << 8) + object[idx];
2644 }
2645
2646 // Dump tail
2647
2648 tail = max % 3;
2649
2650 if (tail === 0) {
2651 result += map[(bits >> 18) & 0x3F];
2652 result += map[(bits >> 12) & 0x3F];
2653 result += map[(bits >> 6) & 0x3F];
2654 result += map[bits & 0x3F];
2655 } else if (tail === 2) {
2656 result += map[(bits >> 10) & 0x3F];
2657 result += map[(bits >> 4) & 0x3F];
2658 result += map[(bits << 2) & 0x3F];
2659 result += map[64];
2660 } else if (tail === 1) {
2661 result += map[(bits >> 2) & 0x3F];
2662 result += map[(bits << 4) & 0x3F];
2663 result += map[64];
2664 result += map[64];
2665 }
2666
2667 return result;
2668 }
2669
2670 function isBinary(object) {
2671 return NodeBuffer && NodeBuffer.isBuffer(object);
2672 }
2673
2674 var binary = new type('tag:yaml.org,2002:binary', {
2675 kind: 'scalar',
2676 resolve: resolveYamlBinary,
2677 construct: constructYamlBinary,
2678 predicate: isBinary,
2679 represent: representYamlBinary
2680 });
2681
2682 var _hasOwnProperty = Object.prototype.hasOwnProperty;
2683 var _toString = Object.prototype.toString;
2684
2685 function resolveYamlOmap(data) {
2686 if (data === null) return true;
2687
2688 var objectKeys = [], index, length, pair, pairKey, pairHasKey,
2689 object = data;
2690
2691 for (index = 0, length = object.length; index < length; index += 1) {
2692 pair = object[index];
2693 pairHasKey = false;
2694
2695 if (_toString.call(pair) !== '[object Object]') return false;
2696
2697 for (pairKey in pair) {
2698 if (_hasOwnProperty.call(pair, pairKey)) {
2699 if (!pairHasKey) pairHasKey = true;
2700 else return false;
2701 }
2702 }
2703
2704 if (!pairHasKey) return false;
2705
2706 if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
2707 else return false;
2708 }
2709
2710 return true;
2711 }
2712
2713 function constructYamlOmap(data) {
2714 return data !== null ? data : [];
2715 }
2716
2717 var omap = new type('tag:yaml.org,2002:omap', {
2718 kind: 'sequence',
2719 resolve: resolveYamlOmap,
2720 construct: constructYamlOmap
2721 });
2722
2723 var _toString$1 = Object.prototype.toString;
2724
2725 function resolveYamlPairs(data) {
2726 if (data === null) return true;
2727
2728 var index, length, pair, keys, result,
2729 object = data;
2730
2731 result = new Array(object.length);
2732
2733 for (index = 0, length = object.length; index < length; index += 1) {
2734 pair = object[index];
2735
2736 if (_toString$1.call(pair) !== '[object Object]') return false;
2737
2738 keys = Object.keys(pair);
2739
2740 if (keys.length !== 1) return false;
2741
2742 result[index] = [ keys[0], pair[keys[0]] ];
2743 }
2744
2745 return true;
2746 }
2747
2748 function constructYamlPairs(data) {
2749 if (data === null) return [];
2750
2751 var index, length, pair, keys, result,
2752 object = data;
2753
2754 result = new Array(object.length);
2755
2756 for (index = 0, length = object.length; index < length; index += 1) {
2757 pair = object[index];
2758
2759 keys = Object.keys(pair);
2760
2761 result[index] = [ keys[0], pair[keys[0]] ];
2762 }
2763
2764 return result;
2765 }
2766
2767 var pairs = new type('tag:yaml.org,2002:pairs', {
2768 kind: 'sequence',
2769 resolve: resolveYamlPairs,
2770 construct: constructYamlPairs
2771 });
2772
2773 var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
2774
2775 function resolveYamlSet(data) {
2776 if (data === null) return true;
2777
2778 var key, object = data;
2779
2780 for (key in object) {
2781 if (_hasOwnProperty$1.call(object, key)) {
2782 if (object[key] !== null) return false;
2783 }
2784 }
2785
2786 return true;
2787 }
2788
2789 function constructYamlSet(data) {
2790 return data !== null ? data : {};
2791 }
2792
2793 var set = new type('tag:yaml.org,2002:set', {
2794 kind: 'mapping',
2795 resolve: resolveYamlSet,
2796 construct: constructYamlSet
2797 });
2798
2799 var default_safe = new schema({
2800 include: [
2801 core
2802 ],
2803 implicit: [
2804 timestamp,
2805 merge
2806 ],
2807 explicit: [
2808 binary,
2809 omap,
2810 pairs,
2811 set
2812 ]
2813 });
2814
2815 function resolveJavascriptUndefined() {
2816 return true;
2817 }
2818
2819 function constructJavascriptUndefined() {
2820 /*eslint-disable no-undefined*/
2821 return undefined;
2822 }
2823
2824 function representJavascriptUndefined() {
2825 return '';
2826 }
2827
2828 function isUndefined(object) {
2829 return typeof object === 'undefined';
2830 }
2831
2832 var _undefined = new type('tag:yaml.org,2002:js/undefined', {
2833 kind: 'scalar',
2834 resolve: resolveJavascriptUndefined,
2835 construct: constructJavascriptUndefined,
2836 predicate: isUndefined,
2837 represent: representJavascriptUndefined
2838 });
2839
2840 function resolveJavascriptRegExp(data) {
2841 if (data === null) return false;
2842 if (data.length === 0) return false;
2843
2844 var regexp = data,
2845 tail = /\/([gim]*)$/.exec(data),
2846 modifiers = '';
2847
2848 // if regexp starts with '/' it can have modifiers and must be properly closed
2849 // `/foo/gim` - modifiers tail can be maximum 3 chars
2850 if (regexp[0] === '/') {
2851 if (tail) modifiers = tail[1];
2852
2853 if (modifiers.length > 3) return false;
2854 // if expression starts with /, is should be properly terminated
2855 if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
2856 }
2857
2858 return true;
2859 }
2860
2861 function constructJavascriptRegExp(data) {
2862 var regexp = data,
2863 tail = /\/([gim]*)$/.exec(data),
2864 modifiers = '';
2865
2866 // `/foo/gim` - tail can be maximum 4 chars
2867 if (regexp[0] === '/') {
2868 if (tail) modifiers = tail[1];
2869 regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
2870 }
2871
2872 return new RegExp(regexp, modifiers);
2873 }
2874
2875 function representJavascriptRegExp(object /*, style*/) {
2876 var result = '/' + object.source + '/';
2877
2878 if (object.global) result += 'g';
2879 if (object.multiline) result += 'm';
2880 if (object.ignoreCase) result += 'i';
2881
2882 return result;
2883 }
2884
2885 function isRegExp(object) {
2886 return Object.prototype.toString.call(object) === '[object RegExp]';
2887 }
2888
2889 var regexp = new type('tag:yaml.org,2002:js/regexp', {
2890 kind: 'scalar',
2891 resolve: resolveJavascriptRegExp,
2892 construct: constructJavascriptRegExp,
2893 predicate: isRegExp,
2894 represent: representJavascriptRegExp
2895 });
2896
2897 var esprima;
2898
2899 // Browserified version does not have esprima
2900 //
2901 // 1. For node.js just require module as deps
2902 // 2. For browser try to require mudule via external AMD system.
2903 // If not found - try to fallback to window.esprima. If not
2904 // found too - then fail to parse.
2905 //
2906 try {
2907 // workaround to exclude package from browserify list.
2908 var _require$1 = commonjsRequire;
2909 esprima = _require$1('esprima');
2910 } catch (_) {
2911 /*global window */
2912 if (typeof window !== 'undefined') esprima = window.esprima;
2913 }
2914
2915
2916
2917 function resolveJavascriptFunction(data) {
2918 if (data === null) return false;
2919
2920 try {
2921 var source = '(' + data + ')',
2922 ast = esprima.parse(source, { range: true });
2923
2924 if (ast.type !== 'Program' ||
2925 ast.body.length !== 1 ||
2926 ast.body[0].type !== 'ExpressionStatement' ||
2927 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
2928 ast.body[0].expression.type !== 'FunctionExpression')) {
2929 return false;
2930 }
2931
2932 return true;
2933 } catch (err) {
2934 return false;
2935 }
2936 }
2937
2938 function constructJavascriptFunction(data) {
2939 /*jslint evil:true*/
2940
2941 var source = '(' + data + ')',
2942 ast = esprima.parse(source, { range: true }),
2943 params = [],
2944 body;
2945
2946 if (ast.type !== 'Program' ||
2947 ast.body.length !== 1 ||
2948 ast.body[0].type !== 'ExpressionStatement' ||
2949 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
2950 ast.body[0].expression.type !== 'FunctionExpression')) {
2951 throw new Error('Failed to resolve function');
2952 }
2953
2954 ast.body[0].expression.params.forEach(function (param) {
2955 params.push(param.name);
2956 });
2957
2958 body = ast.body[0].expression.body.range;
2959
2960 // Esprima's ranges include the first '{' and the last '}' characters on
2961 // function expressions. So cut them out.
2962 if (ast.body[0].expression.body.type === 'BlockStatement') {
2963 /*eslint-disable no-new-func*/
2964 return new Function(params, source.slice(body[0] + 1, body[1] - 1));
2965 }
2966 // ES6 arrow functions can omit the BlockStatement. In that case, just return
2967 // the body.
2968 /*eslint-disable no-new-func*/
2969 return new Function(params, 'return ' + source.slice(body[0], body[1]));
2970 }
2971
2972 function representJavascriptFunction(object /*, style*/) {
2973 return object.toString();
2974 }
2975
2976 function isFunction(object) {
2977 return Object.prototype.toString.call(object) === '[object Function]';
2978 }
2979
2980 var _function = new type('tag:yaml.org,2002:js/function', {
2981 kind: 'scalar',
2982 resolve: resolveJavascriptFunction,
2983 construct: constructJavascriptFunction,
2984 predicate: isFunction,
2985 represent: representJavascriptFunction
2986 });
2987
2988 var default_full = schema.DEFAULT = new schema({
2989 include: [
2990 default_safe
2991 ],
2992 explicit: [
2993 _undefined,
2994 regexp,
2995 _function
2996 ]
2997 });
2998
2999 /*eslint-disable max-len,no-use-before-define*/
3000
3001
3002
3003
3004
3005
3006
3007
3008 var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
3009
3010
3011 var CONTEXT_FLOW_IN = 1;
3012 var CONTEXT_FLOW_OUT = 2;
3013 var CONTEXT_BLOCK_IN = 3;
3014 var CONTEXT_BLOCK_OUT = 4;
3015
3016
3017 var CHOMPING_CLIP = 1;
3018 var CHOMPING_STRIP = 2;
3019 var CHOMPING_KEEP = 3;
3020
3021
3022 var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
3023 var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
3024 var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
3025 var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
3026 var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
3027
3028
3029 function _class(obj) { return Object.prototype.toString.call(obj); }
3030
3031 function is_EOL(c) {
3032 return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
3033 }
3034
3035 function is_WHITE_SPACE(c) {
3036 return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
3037 }
3038
3039 function is_WS_OR_EOL(c) {
3040 return (c === 0x09/* Tab */) ||
3041 (c === 0x20/* Space */) ||
3042 (c === 0x0A/* LF */) ||
3043 (c === 0x0D/* CR */);
3044 }
3045
3046 function is_FLOW_INDICATOR(c) {
3047 return c === 0x2C/* , */ ||
3048 c === 0x5B/* [ */ ||
3049 c === 0x5D/* ] */ ||
3050 c === 0x7B/* { */ ||
3051 c === 0x7D/* } */;
3052 }
3053
3054 function fromHexCode(c) {
3055 var lc;
3056
3057 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
3058 return c - 0x30;
3059 }
3060
3061 /*eslint-disable no-bitwise*/
3062 lc = c | 0x20;
3063
3064 if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
3065 return lc - 0x61 + 10;
3066 }
3067
3068 return -1;
3069 }
3070
3071 function escapedHexLen(c) {
3072 if (c === 0x78/* x */) { return 2; }
3073 if (c === 0x75/* u */) { return 4; }
3074 if (c === 0x55/* U */) { return 8; }
3075 return 0;
3076 }
3077
3078 function fromDecimalCode(c) {
3079 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
3080 return c - 0x30;
3081 }
3082
3083 return -1;
3084 }
3085
3086 function simpleEscapeSequence(c) {
3087 /* eslint-disable indent */
3088 return (c === 0x30/* 0 */) ? '\x00' :
3089 (c === 0x61/* a */) ? '\x07' :
3090 (c === 0x62/* b */) ? '\x08' :
3091 (c === 0x74/* t */) ? '\x09' :
3092 (c === 0x09/* Tab */) ? '\x09' :
3093 (c === 0x6E/* n */) ? '\x0A' :
3094 (c === 0x76/* v */) ? '\x0B' :
3095 (c === 0x66/* f */) ? '\x0C' :
3096 (c === 0x72/* r */) ? '\x0D' :
3097 (c === 0x65/* e */) ? '\x1B' :
3098 (c === 0x20/* Space */) ? ' ' :
3099 (c === 0x22/* " */) ? '\x22' :
3100 (c === 0x2F/* / */) ? '/' :
3101 (c === 0x5C/* \ */) ? '\x5C' :
3102 (c === 0x4E/* N */) ? '\x85' :
3103 (c === 0x5F/* _ */) ? '\xA0' :
3104 (c === 0x4C/* L */) ? '\u2028' :
3105 (c === 0x50/* P */) ? '\u2029' : '';
3106 }
3107
3108 function charFromCodepoint(c) {
3109 if (c <= 0xFFFF) {
3110 return String.fromCharCode(c);
3111 }
3112 // Encode UTF-16 surrogate pair
3113 // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
3114 return String.fromCharCode(
3115 ((c - 0x010000) >> 10) + 0xD800,
3116 ((c - 0x010000) & 0x03FF) + 0xDC00
3117 );
3118 }
3119
3120 var simpleEscapeCheck = new Array(256); // integer, for fast access
3121 var simpleEscapeMap = new Array(256);
3122 for (var i = 0; i < 256; i++) {
3123 simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
3124 simpleEscapeMap[i] = simpleEscapeSequence(i);
3125 }
3126
3127
3128 function State(input, options) {
3129 this.input = input;
3130
3131 this.filename = options['filename'] || null;
3132 this.schema = options['schema'] || default_full;
3133 this.onWarning = options['onWarning'] || null;
3134 this.legacy = options['legacy'] || false;
3135 this.json = options['json'] || false;
3136 this.listener = options['listener'] || null;
3137
3138 this.implicitTypes = this.schema.compiledImplicit;
3139 this.typeMap = this.schema.compiledTypeMap;
3140
3141 this.length = input.length;
3142 this.position = 0;
3143 this.line = 0;
3144 this.lineStart = 0;
3145 this.lineIndent = 0;
3146
3147 this.documents = [];
3148
3149 /*
3150 this.version;
3151 this.checkLineBreaks;
3152 this.tagMap;
3153 this.anchorMap;
3154 this.tag;
3155 this.anchor;
3156 this.kind;
3157 this.result;*/
3158
3159 }
3160
3161
3162 function generateError(state, message) {
3163 return new exception(
3164 message,
3165 new mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
3166 }
3167
3168 function throwError(state, message) {
3169 throw generateError(state, message);
3170 }
3171
3172 function throwWarning(state, message) {
3173 if (state.onWarning) {
3174 state.onWarning.call(null, generateError(state, message));
3175 }
3176 }
3177
3178
3179 var directiveHandlers = {
3180
3181 YAML: function handleYamlDirective(state, name, args) {
3182
3183 var match, major, minor;
3184
3185 if (state.version !== null) {
3186 throwError(state, 'duplication of %YAML directive');
3187 }
3188
3189 if (args.length !== 1) {
3190 throwError(state, 'YAML directive accepts exactly one argument');
3191 }
3192
3193 match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
3194
3195 if (match === null) {
3196 throwError(state, 'ill-formed argument of the YAML directive');
3197 }
3198
3199 major = parseInt(match[1], 10);
3200 minor = parseInt(match[2], 10);
3201
3202 if (major !== 1) {
3203 throwError(state, 'unacceptable YAML version of the document');
3204 }
3205
3206 state.version = args[0];
3207 state.checkLineBreaks = (minor < 2);
3208
3209 if (minor !== 1 && minor !== 2) {
3210 throwWarning(state, 'unsupported YAML version of the document');
3211 }
3212 },
3213
3214 TAG: function handleTagDirective(state, name, args) {
3215
3216 var handle, prefix;
3217
3218 if (args.length !== 2) {
3219 throwError(state, 'TAG directive accepts exactly two arguments');
3220 }
3221
3222 handle = args[0];
3223 prefix = args[1];
3224
3225 if (!PATTERN_TAG_HANDLE.test(handle)) {
3226 throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
3227 }
3228
3229 if (_hasOwnProperty$2.call(state.tagMap, handle)) {
3230 throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
3231 }
3232
3233 if (!PATTERN_TAG_URI.test(prefix)) {
3234 throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
3235 }
3236
3237 state.tagMap[handle] = prefix;
3238 }
3239 };
3240
3241
3242 function captureSegment(state, start, end, checkJson) {
3243 var _position, _length, _character, _result;
3244
3245 if (start < end) {
3246 _result = state.input.slice(start, end);
3247
3248 if (checkJson) {
3249 for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
3250 _character = _result.charCodeAt(_position);
3251 if (!(_character === 0x09 ||
3252 (0x20 <= _character && _character <= 0x10FFFF))) {
3253 throwError(state, 'expected valid JSON character');
3254 }
3255 }
3256 } else if (PATTERN_NON_PRINTABLE.test(_result)) {
3257 throwError(state, 'the stream contains non-printable characters');
3258 }
3259
3260 state.result += _result;
3261 }
3262 }
3263
3264 function mergeMappings(state, destination, source, overridableKeys) {
3265 var sourceKeys, key, index, quantity;
3266
3267 if (!common.isObject(source)) {
3268 throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
3269 }
3270
3271 sourceKeys = Object.keys(source);
3272
3273 for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
3274 key = sourceKeys[index];
3275
3276 if (!_hasOwnProperty$2.call(destination, key)) {
3277 destination[key] = source[key];
3278 overridableKeys[key] = true;
3279 }
3280 }
3281 }
3282
3283 function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
3284 var index, quantity;
3285
3286 // The output is a plain object here, so keys can only be strings.
3287 // We need to convert keyNode to a string, but doing so can hang the process
3288 // (deeply nested arrays that explode exponentially using aliases).
3289 if (Array.isArray(keyNode)) {
3290 keyNode = Array.prototype.slice.call(keyNode);
3291
3292 for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
3293 if (Array.isArray(keyNode[index])) {
3294 throwError(state, 'nested arrays are not supported inside keys');
3295 }
3296
3297 if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
3298 keyNode[index] = '[object Object]';
3299 }
3300 }
3301 }
3302
3303 // Avoid code execution in load() via toString property
3304 // (still use its own toString for arrays, timestamps,
3305 // and whatever user schema extensions happen to have @@toStringTag)
3306 if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
3307 keyNode = '[object Object]';
3308 }
3309
3310
3311 keyNode = String(keyNode);
3312
3313 if (_result === null) {
3314 _result = {};
3315 }
3316
3317 if (keyTag === 'tag:yaml.org,2002:merge') {
3318 if (Array.isArray(valueNode)) {
3319 for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
3320 mergeMappings(state, _result, valueNode[index], overridableKeys);
3321 }
3322 } else {
3323 mergeMappings(state, _result, valueNode, overridableKeys);
3324 }
3325 } else {
3326 if (!state.json &&
3327 !_hasOwnProperty$2.call(overridableKeys, keyNode) &&
3328 _hasOwnProperty$2.call(_result, keyNode)) {
3329 state.line = startLine || state.line;
3330 state.position = startPos || state.position;
3331 throwError(state, 'duplicated mapping key');
3332 }
3333 _result[keyNode] = valueNode;
3334 delete overridableKeys[keyNode];
3335 }
3336
3337 return _result;
3338 }
3339
3340 function readLineBreak(state) {
3341 var ch;
3342
3343 ch = state.input.charCodeAt(state.position);
3344
3345 if (ch === 0x0A/* LF */) {
3346 state.position++;
3347 } else if (ch === 0x0D/* CR */) {
3348 state.position++;
3349 if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
3350 state.position++;
3351 }
3352 } else {
3353 throwError(state, 'a line break is expected');
3354 }
3355
3356 state.line += 1;
3357 state.lineStart = state.position;
3358 }
3359
3360 function skipSeparationSpace(state, allowComments, checkIndent) {
3361 var lineBreaks = 0,
3362 ch = state.input.charCodeAt(state.position);
3363
3364 while (ch !== 0) {
3365 while (is_WHITE_SPACE(ch)) {
3366 ch = state.input.charCodeAt(++state.position);
3367 }
3368
3369 if (allowComments && ch === 0x23/* # */) {
3370 do {
3371 ch = state.input.charCodeAt(++state.position);
3372 } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
3373 }
3374
3375 if (is_EOL(ch)) {
3376 readLineBreak(state);
3377
3378 ch = state.input.charCodeAt(state.position);
3379 lineBreaks++;
3380 state.lineIndent = 0;
3381
3382 while (ch === 0x20/* Space */) {
3383 state.lineIndent++;
3384 ch = state.input.charCodeAt(++state.position);
3385 }
3386 } else {
3387 break;
3388 }
3389 }
3390
3391 if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
3392 throwWarning(state, 'deficient indentation');
3393 }
3394
3395 return lineBreaks;
3396 }
3397
3398 function testDocumentSeparator(state) {
3399 var _position = state.position,
3400 ch;
3401
3402 ch = state.input.charCodeAt(_position);
3403
3404 // Condition state.position === state.lineStart is tested
3405 // in parent on each call, for efficiency. No needs to test here again.
3406 if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
3407 ch === state.input.charCodeAt(_position + 1) &&
3408 ch === state.input.charCodeAt(_position + 2)) {
3409
3410 _position += 3;
3411
3412 ch = state.input.charCodeAt(_position);
3413
3414 if (ch === 0 || is_WS_OR_EOL(ch)) {
3415 return true;
3416 }
3417 }
3418
3419 return false;
3420 }
3421
3422 function writeFoldedLines(state, count) {
3423 if (count === 1) {
3424 state.result += ' ';
3425 } else if (count > 1) {
3426 state.result += common.repeat('\n', count - 1);
3427 }
3428 }
3429
3430
3431 function readPlainScalar(state, nodeIndent, withinFlowCollection) {
3432 var preceding,
3433 following,
3434 captureStart,
3435 captureEnd,
3436 hasPendingContent,
3437 _line,
3438 _lineStart,
3439 _lineIndent,
3440 _kind = state.kind,
3441 _result = state.result,
3442 ch;
3443
3444 ch = state.input.charCodeAt(state.position);
3445
3446 if (is_WS_OR_EOL(ch) ||
3447 is_FLOW_INDICATOR(ch) ||
3448 ch === 0x23/* # */ ||
3449 ch === 0x26/* & */ ||
3450 ch === 0x2A/* * */ ||
3451 ch === 0x21/* ! */ ||
3452 ch === 0x7C/* | */ ||
3453 ch === 0x3E/* > */ ||
3454 ch === 0x27/* ' */ ||
3455 ch === 0x22/* " */ ||
3456 ch === 0x25/* % */ ||
3457 ch === 0x40/* @ */ ||
3458 ch === 0x60/* ` */) {
3459 return false;
3460 }
3461
3462 if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
3463 following = state.input.charCodeAt(state.position + 1);
3464
3465 if (is_WS_OR_EOL(following) ||
3466 withinFlowCollection && is_FLOW_INDICATOR(following)) {
3467 return false;
3468 }
3469 }
3470
3471 state.kind = 'scalar';
3472 state.result = '';
3473 captureStart = captureEnd = state.position;
3474 hasPendingContent = false;
3475
3476 while (ch !== 0) {
3477 if (ch === 0x3A/* : */) {
3478 following = state.input.charCodeAt(state.position + 1);
3479
3480 if (is_WS_OR_EOL(following) ||
3481 withinFlowCollection && is_FLOW_INDICATOR(following)) {
3482 break;
3483 }
3484
3485 } else if (ch === 0x23/* # */) {
3486 preceding = state.input.charCodeAt(state.position - 1);
3487
3488 if (is_WS_OR_EOL(preceding)) {
3489 break;
3490 }
3491
3492 } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
3493 withinFlowCollection && is_FLOW_INDICATOR(ch)) {
3494 break;
3495
3496 } else if (is_EOL(ch)) {
3497 _line = state.line;
3498 _lineStart = state.lineStart;
3499 _lineIndent = state.lineIndent;
3500 skipSeparationSpace(state, false, -1);
3501
3502 if (state.lineIndent >= nodeIndent) {
3503 hasPendingContent = true;
3504 ch = state.input.charCodeAt(state.position);
3505 continue;
3506 } else {
3507 state.position = captureEnd;
3508 state.line = _line;
3509 state.lineStart = _lineStart;
3510 state.lineIndent = _lineIndent;
3511 break;
3512 }
3513 }
3514
3515 if (hasPendingContent) {
3516 captureSegment(state, captureStart, captureEnd, false);
3517 writeFoldedLines(state, state.line - _line);
3518 captureStart = captureEnd = state.position;
3519 hasPendingContent = false;
3520 }
3521
3522 if (!is_WHITE_SPACE(ch)) {
3523 captureEnd = state.position + 1;
3524 }
3525
3526 ch = state.input.charCodeAt(++state.position);
3527 }
3528
3529 captureSegment(state, captureStart, captureEnd, false);
3530
3531 if (state.result) {
3532 return true;
3533 }
3534
3535 state.kind = _kind;
3536 state.result = _result;
3537 return false;
3538 }
3539
3540 function readSingleQuotedScalar(state, nodeIndent) {
3541 var ch,
3542 captureStart, captureEnd;
3543
3544 ch = state.input.charCodeAt(state.position);
3545
3546 if (ch !== 0x27/* ' */) {
3547 return false;
3548 }
3549
3550 state.kind = 'scalar';
3551 state.result = '';
3552 state.position++;
3553 captureStart = captureEnd = state.position;
3554
3555 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
3556 if (ch === 0x27/* ' */) {
3557 captureSegment(state, captureStart, state.position, true);
3558 ch = state.input.charCodeAt(++state.position);
3559
3560 if (ch === 0x27/* ' */) {
3561 captureStart = state.position;
3562 state.position++;
3563 captureEnd = state.position;
3564 } else {
3565 return true;
3566 }
3567
3568 } else if (is_EOL(ch)) {
3569 captureSegment(state, captureStart, captureEnd, true);
3570 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
3571 captureStart = captureEnd = state.position;
3572
3573 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
3574 throwError(state, 'unexpected end of the document within a single quoted scalar');
3575
3576 } else {
3577 state.position++;
3578 captureEnd = state.position;
3579 }
3580 }
3581
3582 throwError(state, 'unexpected end of the stream within a single quoted scalar');
3583 }
3584
3585 function readDoubleQuotedScalar(state, nodeIndent) {
3586 var captureStart,
3587 captureEnd,
3588 hexLength,
3589 hexResult,
3590 tmp,
3591 ch;
3592
3593 ch = state.input.charCodeAt(state.position);
3594
3595 if (ch !== 0x22/* " */) {
3596 return false;
3597 }
3598
3599 state.kind = 'scalar';
3600 state.result = '';
3601 state.position++;
3602 captureStart = captureEnd = state.position;
3603
3604 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
3605 if (ch === 0x22/* " */) {
3606 captureSegment(state, captureStart, state.position, true);
3607 state.position++;
3608 return true;
3609
3610 } else if (ch === 0x5C/* \ */) {
3611 captureSegment(state, captureStart, state.position, true);
3612 ch = state.input.charCodeAt(++state.position);
3613
3614 if (is_EOL(ch)) {
3615 skipSeparationSpace(state, false, nodeIndent);
3616
3617 // TODO: rework to inline fn with no type cast?
3618 } else if (ch < 256 && simpleEscapeCheck[ch]) {
3619 state.result += simpleEscapeMap[ch];
3620 state.position++;
3621
3622 } else if ((tmp = escapedHexLen(ch)) > 0) {
3623 hexLength = tmp;
3624 hexResult = 0;
3625
3626 for (; hexLength > 0; hexLength--) {
3627 ch = state.input.charCodeAt(++state.position);
3628
3629 if ((tmp = fromHexCode(ch)) >= 0) {
3630 hexResult = (hexResult << 4) + tmp;
3631
3632 } else {
3633 throwError(state, 'expected hexadecimal character');
3634 }
3635 }
3636
3637 state.result += charFromCodepoint(hexResult);
3638
3639 state.position++;
3640
3641 } else {
3642 throwError(state, 'unknown escape sequence');
3643 }
3644
3645 captureStart = captureEnd = state.position;
3646
3647 } else if (is_EOL(ch)) {
3648 captureSegment(state, captureStart, captureEnd, true);
3649 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
3650 captureStart = captureEnd = state.position;
3651
3652 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
3653 throwError(state, 'unexpected end of the document within a double quoted scalar');
3654
3655 } else {
3656 state.position++;
3657 captureEnd = state.position;
3658 }
3659 }
3660
3661 throwError(state, 'unexpected end of the stream within a double quoted scalar');
3662 }
3663
3664 function readFlowCollection(state, nodeIndent) {
3665 var readNext = true,
3666 _line,
3667 _tag = state.tag,
3668 _result,
3669 _anchor = state.anchor,
3670 following,
3671 terminator,
3672 isPair,
3673 isExplicitPair,
3674 isMapping,
3675 overridableKeys = {},
3676 keyNode,
3677 keyTag,
3678 valueNode,
3679 ch;
3680
3681 ch = state.input.charCodeAt(state.position);
3682
3683 if (ch === 0x5B/* [ */) {
3684 terminator = 0x5D;/* ] */
3685 isMapping = false;
3686 _result = [];
3687 } else if (ch === 0x7B/* { */) {
3688 terminator = 0x7D;/* } */
3689 isMapping = true;
3690 _result = {};
3691 } else {
3692 return false;
3693 }
3694
3695 if (state.anchor !== null) {
3696 state.anchorMap[state.anchor] = _result;
3697 }
3698
3699 ch = state.input.charCodeAt(++state.position);
3700
3701 while (ch !== 0) {
3702 skipSeparationSpace(state, true, nodeIndent);
3703
3704 ch = state.input.charCodeAt(state.position);
3705
3706 if (ch === terminator) {
3707 state.position++;
3708 state.tag = _tag;
3709 state.anchor = _anchor;
3710 state.kind = isMapping ? 'mapping' : 'sequence';
3711 state.result = _result;
3712 return true;
3713 } else if (!readNext) {
3714 throwError(state, 'missed comma between flow collection entries');
3715 }
3716
3717 keyTag = keyNode = valueNode = null;
3718 isPair = isExplicitPair = false;
3719
3720 if (ch === 0x3F/* ? */) {
3721 following = state.input.charCodeAt(state.position + 1);
3722
3723 if (is_WS_OR_EOL(following)) {
3724 isPair = isExplicitPair = true;
3725 state.position++;
3726 skipSeparationSpace(state, true, nodeIndent);
3727 }
3728 }
3729
3730 _line = state.line;
3731 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
3732 keyTag = state.tag;
3733 keyNode = state.result;
3734 skipSeparationSpace(state, true, nodeIndent);
3735
3736 ch = state.input.charCodeAt(state.position);
3737
3738 if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
3739 isPair = true;
3740 ch = state.input.charCodeAt(++state.position);
3741 skipSeparationSpace(state, true, nodeIndent);
3742 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
3743 valueNode = state.result;
3744 }
3745
3746 if (isMapping) {
3747 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
3748 } else if (isPair) {
3749 _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
3750 } else {
3751 _result.push(keyNode);
3752 }
3753
3754 skipSeparationSpace(state, true, nodeIndent);
3755
3756 ch = state.input.charCodeAt(state.position);
3757
3758 if (ch === 0x2C/* , */) {
3759 readNext = true;
3760 ch = state.input.charCodeAt(++state.position);
3761 } else {
3762 readNext = false;
3763 }
3764 }
3765
3766 throwError(state, 'unexpected end of the stream within a flow collection');
3767 }
3768
3769 function readBlockScalar(state, nodeIndent) {
3770 var captureStart,
3771 folding,
3772 chomping = CHOMPING_CLIP,
3773 didReadContent = false,
3774 detectedIndent = false,
3775 textIndent = nodeIndent,
3776 emptyLines = 0,
3777 atMoreIndented = false,
3778 tmp,
3779 ch;
3780
3781 ch = state.input.charCodeAt(state.position);
3782
3783 if (ch === 0x7C/* | */) {
3784 folding = false;
3785 } else if (ch === 0x3E/* > */) {
3786 folding = true;
3787 } else {
3788 return false;
3789 }
3790
3791 state.kind = 'scalar';
3792 state.result = '';
3793
3794 while (ch !== 0) {
3795 ch = state.input.charCodeAt(++state.position);
3796
3797 if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
3798 if (CHOMPING_CLIP === chomping) {
3799 chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
3800 } else {
3801 throwError(state, 'repeat of a chomping mode identifier');
3802 }
3803
3804 } else if ((tmp = fromDecimalCode(ch)) >= 0) {
3805 if (tmp === 0) {
3806 throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
3807 } else if (!detectedIndent) {
3808 textIndent = nodeIndent + tmp - 1;
3809 detectedIndent = true;
3810 } else {
3811 throwError(state, 'repeat of an indentation width identifier');
3812 }
3813
3814 } else {
3815 break;
3816 }
3817 }
3818
3819 if (is_WHITE_SPACE(ch)) {
3820 do { ch = state.input.charCodeAt(++state.position); }
3821 while (is_WHITE_SPACE(ch));
3822
3823 if (ch === 0x23/* # */) {
3824 do { ch = state.input.charCodeAt(++state.position); }
3825 while (!is_EOL(ch) && (ch !== 0));
3826 }
3827 }
3828
3829 while (ch !== 0) {
3830 readLineBreak(state);
3831 state.lineIndent = 0;
3832
3833 ch = state.input.charCodeAt(state.position);
3834
3835 while ((!detectedIndent || state.lineIndent < textIndent) &&
3836 (ch === 0x20/* Space */)) {
3837 state.lineIndent++;
3838 ch = state.input.charCodeAt(++state.position);
3839 }
3840
3841 if (!detectedIndent && state.lineIndent > textIndent) {
3842 textIndent = state.lineIndent;
3843 }
3844
3845 if (is_EOL(ch)) {
3846 emptyLines++;
3847 continue;
3848 }
3849
3850 // End of the scalar.
3851 if (state.lineIndent < textIndent) {
3852
3853 // Perform the chomping.
3854 if (chomping === CHOMPING_KEEP) {
3855 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
3856 } else if (chomping === CHOMPING_CLIP) {
3857 if (didReadContent) { // i.e. only if the scalar is not empty.
3858 state.result += '\n';
3859 }
3860 }
3861
3862 // Break this `while` cycle and go to the funciton's epilogue.
3863 break;
3864 }
3865
3866 // Folded style: use fancy rules to handle line breaks.
3867 if (folding) {
3868
3869 // Lines starting with white space characters (more-indented lines) are not folded.
3870 if (is_WHITE_SPACE(ch)) {
3871 atMoreIndented = true;
3872 // except for the first content line (cf. Example 8.1)
3873 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
3874
3875 // End of more-indented block.
3876 } else if (atMoreIndented) {
3877 atMoreIndented = false;
3878 state.result += common.repeat('\n', emptyLines + 1);
3879
3880 // Just one line break - perceive as the same line.
3881 } else if (emptyLines === 0) {
3882 if (didReadContent) { // i.e. only if we have already read some scalar content.
3883 state.result += ' ';
3884 }
3885
3886 // Several line breaks - perceive as different lines.
3887 } else {
3888 state.result += common.repeat('\n', emptyLines);
3889 }
3890
3891 // Literal style: just add exact number of line breaks between content lines.
3892 } else {
3893 // Keep all line breaks except the header line break.
3894 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
3895 }
3896
3897 didReadContent = true;
3898 detectedIndent = true;
3899 emptyLines = 0;
3900 captureStart = state.position;
3901
3902 while (!is_EOL(ch) && (ch !== 0)) {
3903 ch = state.input.charCodeAt(++state.position);
3904 }
3905
3906 captureSegment(state, captureStart, state.position, false);
3907 }
3908
3909 return true;
3910 }
3911
3912 function readBlockSequence(state, nodeIndent) {
3913 var _line,
3914 _tag = state.tag,
3915 _anchor = state.anchor,
3916 _result = [],
3917 following,
3918 detected = false,
3919 ch;
3920
3921 if (state.anchor !== null) {
3922 state.anchorMap[state.anchor] = _result;
3923 }
3924
3925 ch = state.input.charCodeAt(state.position);
3926
3927 while (ch !== 0) {
3928
3929 if (ch !== 0x2D/* - */) {
3930 break;
3931 }
3932
3933 following = state.input.charCodeAt(state.position + 1);
3934
3935 if (!is_WS_OR_EOL(following)) {
3936 break;
3937 }
3938
3939 detected = true;
3940 state.position++;
3941
3942 if (skipSeparationSpace(state, true, -1)) {
3943 if (state.lineIndent <= nodeIndent) {
3944 _result.push(null);
3945 ch = state.input.charCodeAt(state.position);
3946 continue;
3947 }
3948 }
3949
3950 _line = state.line;
3951 composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
3952 _result.push(state.result);
3953 skipSeparationSpace(state, true, -1);
3954
3955 ch = state.input.charCodeAt(state.position);
3956
3957 if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
3958 throwError(state, 'bad indentation of a sequence entry');
3959 } else if (state.lineIndent < nodeIndent) {
3960 break;
3961 }
3962 }
3963
3964 if (detected) {
3965 state.tag = _tag;
3966 state.anchor = _anchor;
3967 state.kind = 'sequence';
3968 state.result = _result;
3969 return true;
3970 }
3971 return false;
3972 }
3973
3974 function readBlockMapping(state, nodeIndent, flowIndent) {
3975 var following,
3976 allowCompact,
3977 _line,
3978 _pos,
3979 _tag = state.tag,
3980 _anchor = state.anchor,
3981 _result = {},
3982 overridableKeys = {},
3983 keyTag = null,
3984 keyNode = null,
3985 valueNode = null,
3986 atExplicitKey = false,
3987 detected = false,
3988 ch;
3989
3990 if (state.anchor !== null) {
3991 state.anchorMap[state.anchor] = _result;
3992 }
3993
3994 ch = state.input.charCodeAt(state.position);
3995
3996 while (ch !== 0) {
3997 following = state.input.charCodeAt(state.position + 1);
3998 _line = state.line; // Save the current line.
3999 _pos = state.position;
4000
4001 //
4002 // Explicit notation case. There are two separate blocks:
4003 // first for the key (denoted by "?") and second for the value (denoted by ":")
4004 //
4005 if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
4006
4007 if (ch === 0x3F/* ? */) {
4008 if (atExplicitKey) {
4009 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
4010 keyTag = keyNode = valueNode = null;
4011 }
4012
4013 detected = true;
4014 atExplicitKey = true;
4015 allowCompact = true;
4016
4017 } else if (atExplicitKey) {
4018 // i.e. 0x3A/* : */ === character after the explicit key.
4019 atExplicitKey = false;
4020 allowCompact = true;
4021
4022 } else {
4023 throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
4024 }
4025
4026 state.position += 1;
4027 ch = following;
4028
4029 //
4030 // Implicit notation case. Flow-style node as the key first, then ":", and the value.
4031 //
4032 } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
4033
4034 if (state.line === _line) {
4035 ch = state.input.charCodeAt(state.position);
4036
4037 while (is_WHITE_SPACE(ch)) {
4038 ch = state.input.charCodeAt(++state.position);
4039 }
4040
4041 if (ch === 0x3A/* : */) {
4042 ch = state.input.charCodeAt(++state.position);
4043
4044 if (!is_WS_OR_EOL(ch)) {
4045 throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
4046 }
4047
4048 if (atExplicitKey) {
4049 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
4050 keyTag = keyNode = valueNode = null;
4051 }
4052
4053 detected = true;
4054 atExplicitKey = false;
4055 allowCompact = false;
4056 keyTag = state.tag;
4057 keyNode = state.result;
4058
4059 } else if (detected) {
4060 throwError(state, 'can not read an implicit mapping pair; a colon is missed');
4061
4062 } else {
4063 state.tag = _tag;
4064 state.anchor = _anchor;
4065 return true; // Keep the result of `composeNode`.
4066 }
4067
4068 } else if (detected) {
4069 throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
4070
4071 } else {
4072 state.tag = _tag;
4073 state.anchor = _anchor;
4074 return true; // Keep the result of `composeNode`.
4075 }
4076
4077 } else {
4078 break; // Reading is done. Go to the epilogue.
4079 }
4080
4081 //
4082 // Common reading code for both explicit and implicit notations.
4083 //
4084 if (state.line === _line || state.lineIndent > nodeIndent) {
4085 if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
4086 if (atExplicitKey) {
4087 keyNode = state.result;
4088 } else {
4089 valueNode = state.result;
4090 }
4091 }
4092
4093 if (!atExplicitKey) {
4094 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
4095 keyTag = keyNode = valueNode = null;
4096 }
4097
4098 skipSeparationSpace(state, true, -1);
4099 ch = state.input.charCodeAt(state.position);
4100 }
4101
4102 if (state.lineIndent > nodeIndent && (ch !== 0)) {
4103 throwError(state, 'bad indentation of a mapping entry');
4104 } else if (state.lineIndent < nodeIndent) {
4105 break;
4106 }
4107 }
4108
4109 //
4110 // Epilogue.
4111 //
4112
4113 // Special case: last mapping's node contains only the key in explicit notation.
4114 if (atExplicitKey) {
4115 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
4116 }
4117
4118 // Expose the resulting mapping.
4119 if (detected) {
4120 state.tag = _tag;
4121 state.anchor = _anchor;
4122 state.kind = 'mapping';
4123 state.result = _result;
4124 }
4125
4126 return detected;
4127 }
4128
4129 function readTagProperty(state) {
4130 var _position,
4131 isVerbatim = false,
4132 isNamed = false,
4133 tagHandle,
4134 tagName,
4135 ch;
4136
4137 ch = state.input.charCodeAt(state.position);
4138
4139 if (ch !== 0x21/* ! */) return false;
4140
4141 if (state.tag !== null) {
4142 throwError(state, 'duplication of a tag property');
4143 }
4144
4145 ch = state.input.charCodeAt(++state.position);
4146
4147 if (ch === 0x3C/* < */) {
4148 isVerbatim = true;
4149 ch = state.input.charCodeAt(++state.position);
4150
4151 } else if (ch === 0x21/* ! */) {
4152 isNamed = true;
4153 tagHandle = '!!';
4154 ch = state.input.charCodeAt(++state.position);
4155
4156 } else {
4157 tagHandle = '!';
4158 }
4159
4160 _position = state.position;
4161
4162 if (isVerbatim) {
4163 do { ch = state.input.charCodeAt(++state.position); }
4164 while (ch !== 0 && ch !== 0x3E/* > */);
4165
4166 if (state.position < state.length) {
4167 tagName = state.input.slice(_position, state.position);
4168 ch = state.input.charCodeAt(++state.position);
4169 } else {
4170 throwError(state, 'unexpected end of the stream within a verbatim tag');
4171 }
4172 } else {
4173 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
4174
4175 if (ch === 0x21/* ! */) {
4176 if (!isNamed) {
4177 tagHandle = state.input.slice(_position - 1, state.position + 1);
4178
4179 if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
4180 throwError(state, 'named tag handle cannot contain such characters');
4181 }
4182
4183 isNamed = true;
4184 _position = state.position + 1;
4185 } else {
4186 throwError(state, 'tag suffix cannot contain exclamation marks');
4187 }
4188 }
4189
4190 ch = state.input.charCodeAt(++state.position);
4191 }
4192
4193 tagName = state.input.slice(_position, state.position);
4194
4195 if (PATTERN_FLOW_INDICATORS.test(tagName)) {
4196 throwError(state, 'tag suffix cannot contain flow indicator characters');
4197 }
4198 }
4199
4200 if (tagName && !PATTERN_TAG_URI.test(tagName)) {
4201 throwError(state, 'tag name cannot contain such characters: ' + tagName);
4202 }
4203
4204 if (isVerbatim) {
4205 state.tag = tagName;
4206
4207 } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) {
4208 state.tag = state.tagMap[tagHandle] + tagName;
4209
4210 } else if (tagHandle === '!') {
4211 state.tag = '!' + tagName;
4212
4213 } else if (tagHandle === '!!') {
4214 state.tag = 'tag:yaml.org,2002:' + tagName;
4215
4216 } else {
4217 throwError(state, 'undeclared tag handle "' + tagHandle + '"');
4218 }
4219
4220 return true;
4221 }
4222
4223 function readAnchorProperty(state) {
4224 var _position,
4225 ch;
4226
4227 ch = state.input.charCodeAt(state.position);
4228
4229 if (ch !== 0x26/* & */) return false;
4230
4231 if (state.anchor !== null) {
4232 throwError(state, 'duplication of an anchor property');
4233 }
4234
4235 ch = state.input.charCodeAt(++state.position);
4236 _position = state.position;
4237
4238 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
4239 ch = state.input.charCodeAt(++state.position);
4240 }
4241
4242 if (state.position === _position) {
4243 throwError(state, 'name of an anchor node must contain at least one character');
4244 }
4245
4246 state.anchor = state.input.slice(_position, state.position);
4247 return true;
4248 }
4249
4250 function readAlias(state) {
4251 var _position, alias,
4252 ch;
4253
4254 ch = state.input.charCodeAt(state.position);
4255
4256 if (ch !== 0x2A/* * */) return false;
4257
4258 ch = state.input.charCodeAt(++state.position);
4259 _position = state.position;
4260
4261 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
4262 ch = state.input.charCodeAt(++state.position);
4263 }
4264
4265 if (state.position === _position) {
4266 throwError(state, 'name of an alias node must contain at least one character');
4267 }
4268
4269 alias = state.input.slice(_position, state.position);
4270
4271 if (!state.anchorMap.hasOwnProperty(alias)) {
4272 throwError(state, 'unidentified alias "' + alias + '"');
4273 }
4274
4275 state.result = state.anchorMap[alias];
4276 skipSeparationSpace(state, true, -1);
4277 return true;
4278 }
4279
4280 function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
4281 var allowBlockStyles,
4282 allowBlockScalars,
4283 allowBlockCollections,
4284 indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
4285 atNewLine = false,
4286 hasContent = false,
4287 typeIndex,
4288 typeQuantity,
4289 type,
4290 flowIndent,
4291 blockIndent;
4292
4293 if (state.listener !== null) {
4294 state.listener('open', state);
4295 }
4296
4297 state.tag = null;
4298 state.anchor = null;
4299 state.kind = null;
4300 state.result = null;
4301
4302 allowBlockStyles = allowBlockScalars = allowBlockCollections =
4303 CONTEXT_BLOCK_OUT === nodeContext ||
4304 CONTEXT_BLOCK_IN === nodeContext;
4305
4306 if (allowToSeek) {
4307 if (skipSeparationSpace(state, true, -1)) {
4308 atNewLine = true;
4309
4310 if (state.lineIndent > parentIndent) {
4311 indentStatus = 1;
4312 } else if (state.lineIndent === parentIndent) {
4313 indentStatus = 0;
4314 } else if (state.lineIndent < parentIndent) {
4315 indentStatus = -1;
4316 }
4317 }
4318 }
4319
4320 if (indentStatus === 1) {
4321 while (readTagProperty(state) || readAnchorProperty(state)) {
4322 if (skipSeparationSpace(state, true, -1)) {
4323 atNewLine = true;
4324 allowBlockCollections = allowBlockStyles;
4325
4326 if (state.lineIndent > parentIndent) {
4327 indentStatus = 1;
4328 } else if (state.lineIndent === parentIndent) {
4329 indentStatus = 0;
4330 } else if (state.lineIndent < parentIndent) {
4331 indentStatus = -1;
4332 }
4333 } else {
4334 allowBlockCollections = false;
4335 }
4336 }
4337 }
4338
4339 if (allowBlockCollections) {
4340 allowBlockCollections = atNewLine || allowCompact;
4341 }
4342
4343 if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
4344 if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
4345 flowIndent = parentIndent;
4346 } else {
4347 flowIndent = parentIndent + 1;
4348 }
4349
4350 blockIndent = state.position - state.lineStart;
4351
4352 if (indentStatus === 1) {
4353 if (allowBlockCollections &&
4354 (readBlockSequence(state, blockIndent) ||
4355 readBlockMapping(state, blockIndent, flowIndent)) ||
4356 readFlowCollection(state, flowIndent)) {
4357 hasContent = true;
4358 } else {
4359 if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
4360 readSingleQuotedScalar(state, flowIndent) ||
4361 readDoubleQuotedScalar(state, flowIndent)) {
4362 hasContent = true;
4363
4364 } else if (readAlias(state)) {
4365 hasContent = true;
4366
4367 if (state.tag !== null || state.anchor !== null) {
4368 throwError(state, 'alias node should not have any properties');
4369 }
4370
4371 } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
4372 hasContent = true;
4373
4374 if (state.tag === null) {
4375 state.tag = '?';
4376 }
4377 }
4378
4379 if (state.anchor !== null) {
4380 state.anchorMap[state.anchor] = state.result;
4381 }
4382 }
4383 } else if (indentStatus === 0) {
4384 // Special case: block sequences are allowed to have same indentation level as the parent.
4385 // http://www.yaml.org/spec/1.2/spec.html#id2799784
4386 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
4387 }
4388 }
4389
4390 if (state.tag !== null && state.tag !== '!') {
4391 if (state.tag === '?') {
4392 for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
4393 type = state.implicitTypes[typeIndex];
4394
4395 // Implicit resolving is not allowed for non-scalar types, and '?'
4396 // non-specific tag is only assigned to plain scalars. So, it isn't
4397 // needed to check for 'kind' conformity.
4398
4399 if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
4400 state.result = type.construct(state.result);
4401 state.tag = type.tag;
4402 if (state.anchor !== null) {
4403 state.anchorMap[state.anchor] = state.result;
4404 }
4405 break;
4406 }
4407 }
4408 } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
4409 type = state.typeMap[state.kind || 'fallback'][state.tag];
4410
4411 if (state.result !== null && type.kind !== state.kind) {
4412 throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
4413 }
4414
4415 if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
4416 throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
4417 } else {
4418 state.result = type.construct(state.result);
4419 if (state.anchor !== null) {
4420 state.anchorMap[state.anchor] = state.result;
4421 }
4422 }
4423 } else {
4424 throwError(state, 'unknown tag !<' + state.tag + '>');
4425 }
4426 }
4427
4428 if (state.listener !== null) {
4429 state.listener('close', state);
4430 }
4431 return state.tag !== null || state.anchor !== null || hasContent;
4432 }
4433
4434 function readDocument(state) {
4435 var documentStart = state.position,
4436 _position,
4437 directiveName,
4438 directiveArgs,
4439 hasDirectives = false,
4440 ch;
4441
4442 state.version = null;
4443 state.checkLineBreaks = state.legacy;
4444 state.tagMap = {};
4445 state.anchorMap = {};
4446
4447 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
4448 skipSeparationSpace(state, true, -1);
4449
4450 ch = state.input.charCodeAt(state.position);
4451
4452 if (state.lineIndent > 0 || ch !== 0x25/* % */) {
4453 break;
4454 }
4455
4456 hasDirectives = true;
4457 ch = state.input.charCodeAt(++state.position);
4458 _position = state.position;
4459
4460 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
4461 ch = state.input.charCodeAt(++state.position);
4462 }
4463
4464 directiveName = state.input.slice(_position, state.position);
4465 directiveArgs = [];
4466
4467 if (directiveName.length < 1) {
4468 throwError(state, 'directive name must not be less than one character in length');
4469 }
4470
4471 while (ch !== 0) {
4472 while (is_WHITE_SPACE(ch)) {
4473 ch = state.input.charCodeAt(++state.position);
4474 }
4475
4476 if (ch === 0x23/* # */) {
4477 do { ch = state.input.charCodeAt(++state.position); }
4478 while (ch !== 0 && !is_EOL(ch));
4479 break;
4480 }
4481
4482 if (is_EOL(ch)) break;
4483
4484 _position = state.position;
4485
4486 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
4487 ch = state.input.charCodeAt(++state.position);
4488 }
4489
4490 directiveArgs.push(state.input.slice(_position, state.position));
4491 }
4492
4493 if (ch !== 0) readLineBreak(state);
4494
4495 if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) {
4496 directiveHandlers[directiveName](state, directiveName, directiveArgs);
4497 } else {
4498 throwWarning(state, 'unknown document directive "' + directiveName + '"');
4499 }
4500 }
4501
4502 skipSeparationSpace(state, true, -1);
4503
4504 if (state.lineIndent === 0 &&
4505 state.input.charCodeAt(state.position) === 0x2D/* - */ &&
4506 state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
4507 state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
4508 state.position += 3;
4509 skipSeparationSpace(state, true, -1);
4510
4511 } else if (hasDirectives) {
4512 throwError(state, 'directives end mark is expected');
4513 }
4514
4515 composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
4516 skipSeparationSpace(state, true, -1);
4517
4518 if (state.checkLineBreaks &&
4519 PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
4520 throwWarning(state, 'non-ASCII line breaks are interpreted as content');
4521 }
4522
4523 state.documents.push(state.result);
4524
4525 if (state.position === state.lineStart && testDocumentSeparator(state)) {
4526
4527 if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
4528 state.position += 3;
4529 skipSeparationSpace(state, true, -1);
4530 }
4531 return;
4532 }
4533
4534 if (state.position < (state.length - 1)) {
4535 throwError(state, 'end of the stream or a document separator is expected');
4536 } else {
4537 return;
4538 }
4539 }
4540
4541
4542 function loadDocuments(input, options) {
4543 input = String(input);
4544 options = options || {};
4545
4546 if (input.length !== 0) {
4547
4548 // Add tailing `\n` if not exists
4549 if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
4550 input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
4551 input += '\n';
4552 }
4553
4554 // Strip BOM
4555 if (input.charCodeAt(0) === 0xFEFF) {
4556 input = input.slice(1);
4557 }
4558 }
4559
4560 var state = new State(input, options);
4561
4562 // Use 0 as string terminator. That significantly simplifies bounds check.
4563 state.input += '\0';
4564
4565 while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
4566 state.lineIndent += 1;
4567 state.position += 1;
4568 }
4569
4570 while (state.position < (state.length - 1)) {
4571 readDocument(state);
4572 }
4573
4574 return state.documents;
4575 }
4576
4577
4578 function loadAll(input, iterator, options) {
4579 var documents = loadDocuments(input, options), index, length;
4580
4581 if (typeof iterator !== 'function') {
4582 return documents;
4583 }
4584
4585 for (index = 0, length = documents.length; index < length; index += 1) {
4586 iterator(documents[index]);
4587 }
4588 }
4589
4590
4591 function load(input, options) {
4592 var documents = loadDocuments(input, options);
4593
4594 if (documents.length === 0) {
4595 /*eslint-disable no-undefined*/
4596 return undefined;
4597 } else if (documents.length === 1) {
4598 return documents[0];
4599 }
4600 throw new exception('expected a single document in the stream, but found more');
4601 }
4602
4603
4604 function safeLoadAll(input, output, options) {
4605 if (typeof output === 'function') {
4606 loadAll(input, output, common.extend({ schema: default_safe }, options));
4607 } else {
4608 return loadAll(input, common.extend({ schema: default_safe }, options));
4609 }
4610 }
4611
4612
4613 function safeLoad(input, options) {
4614 return load(input, common.extend({ schema: default_safe }, options));
4615 }
4616
4617
4618 var loadAll_1 = loadAll;
4619 var load_1 = load;
4620 var safeLoadAll_1 = safeLoadAll;
4621 var safeLoad_1 = safeLoad;
4622
4623 var loader = {
4624 loadAll: loadAll_1,
4625 load: load_1,
4626 safeLoadAll: safeLoadAll_1,
4627 safeLoad: safeLoad_1
4628 };
4629
4630 /*eslint-disable no-use-before-define*/
4631
4632
4633
4634
4635
4636
4637 var _toString$2 = Object.prototype.toString;
4638 var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
4639
4640 var CHAR_TAB = 0x09; /* Tab */
4641 var CHAR_LINE_FEED = 0x0A; /* LF */
4642 var CHAR_SPACE = 0x20; /* Space */
4643 var CHAR_EXCLAMATION = 0x21; /* ! */
4644 var CHAR_DOUBLE_QUOTE = 0x22; /* " */
4645 var CHAR_SHARP = 0x23; /* # */
4646 var CHAR_PERCENT = 0x25; /* % */
4647 var CHAR_AMPERSAND = 0x26; /* & */
4648 var CHAR_SINGLE_QUOTE = 0x27; /* ' */
4649 var CHAR_ASTERISK = 0x2A; /* * */
4650 var CHAR_COMMA = 0x2C; /* , */
4651 var CHAR_MINUS = 0x2D; /* - */
4652 var CHAR_COLON = 0x3A; /* : */
4653 var CHAR_GREATER_THAN = 0x3E; /* > */
4654 var CHAR_QUESTION = 0x3F; /* ? */
4655 var CHAR_COMMERCIAL_AT = 0x40; /* @ */
4656 var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
4657 var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
4658 var CHAR_GRAVE_ACCENT = 0x60; /* ` */
4659 var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
4660 var CHAR_VERTICAL_LINE = 0x7C; /* | */
4661 var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
4662
4663 var ESCAPE_SEQUENCES = {};
4664
4665 ESCAPE_SEQUENCES[0x00] = '\\0';
4666 ESCAPE_SEQUENCES[0x07] = '\\a';
4667 ESCAPE_SEQUENCES[0x08] = '\\b';
4668 ESCAPE_SEQUENCES[0x09] = '\\t';
4669 ESCAPE_SEQUENCES[0x0A] = '\\n';
4670 ESCAPE_SEQUENCES[0x0B] = '\\v';
4671 ESCAPE_SEQUENCES[0x0C] = '\\f';
4672 ESCAPE_SEQUENCES[0x0D] = '\\r';
4673 ESCAPE_SEQUENCES[0x1B] = '\\e';
4674 ESCAPE_SEQUENCES[0x22] = '\\"';
4675 ESCAPE_SEQUENCES[0x5C] = '\\\\';
4676 ESCAPE_SEQUENCES[0x85] = '\\N';
4677 ESCAPE_SEQUENCES[0xA0] = '\\_';
4678 ESCAPE_SEQUENCES[0x2028] = '\\L';
4679 ESCAPE_SEQUENCES[0x2029] = '\\P';
4680
4681 var DEPRECATED_BOOLEANS_SYNTAX = [
4682 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
4683 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
4684 ];
4685
4686 function compileStyleMap(schema, map) {
4687 var result, keys, index, length, tag, style, type;
4688
4689 if (map === null) return {};
4690
4691 result = {};
4692 keys = Object.keys(map);
4693
4694 for (index = 0, length = keys.length; index < length; index += 1) {
4695 tag = keys[index];
4696 style = String(map[tag]);
4697
4698 if (tag.slice(0, 2) === '!!') {
4699 tag = 'tag:yaml.org,2002:' + tag.slice(2);
4700 }
4701 type = schema.compiledTypeMap['fallback'][tag];
4702
4703 if (type && _hasOwnProperty$3.call(type.styleAliases, style)) {
4704 style = type.styleAliases[style];
4705 }
4706
4707 result[tag] = style;
4708 }
4709
4710 return result;
4711 }
4712
4713 function encodeHex(character) {
4714 var string, handle, length;
4715
4716 string = character.toString(16).toUpperCase();
4717
4718 if (character <= 0xFF) {
4719 handle = 'x';
4720 length = 2;
4721 } else if (character <= 0xFFFF) {
4722 handle = 'u';
4723 length = 4;
4724 } else if (character <= 0xFFFFFFFF) {
4725 handle = 'U';
4726 length = 8;
4727 } else {
4728 throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
4729 }
4730
4731 return '\\' + handle + common.repeat('0', length - string.length) + string;
4732 }
4733
4734 function State$1(options) {
4735 this.schema = options['schema'] || default_full;
4736 this.indent = Math.max(1, (options['indent'] || 2));
4737 this.noArrayIndent = options['noArrayIndent'] || false;
4738 this.skipInvalid = options['skipInvalid'] || false;
4739 this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
4740 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
4741 this.sortKeys = options['sortKeys'] || false;
4742 this.lineWidth = options['lineWidth'] || 80;
4743 this.noRefs = options['noRefs'] || false;
4744 this.noCompatMode = options['noCompatMode'] || false;
4745 this.condenseFlow = options['condenseFlow'] || false;
4746
4747 this.implicitTypes = this.schema.compiledImplicit;
4748 this.explicitTypes = this.schema.compiledExplicit;
4749
4750 this.tag = null;
4751 this.result = '';
4752
4753 this.duplicates = [];
4754 this.usedDuplicates = null;
4755 }
4756
4757 // Indents every line in a string. Empty lines (\n only) are not indented.
4758 function indentString(string, spaces) {
4759 var ind = common.repeat(' ', spaces),
4760 position = 0,
4761 next = -1,
4762 result = '',
4763 line,
4764 length = string.length;
4765
4766 while (position < length) {
4767 next = string.indexOf('\n', position);
4768 if (next === -1) {
4769 line = string.slice(position);
4770 position = length;
4771 } else {
4772 line = string.slice(position, next + 1);
4773 position = next + 1;
4774 }
4775
4776 if (line.length && line !== '\n') result += ind;
4777
4778 result += line;
4779 }
4780
4781 return result;
4782 }
4783
4784 function generateNextLine(state, level) {
4785 return '\n' + common.repeat(' ', state.indent * level);
4786 }
4787
4788 function testImplicitResolving(state, str) {
4789 var index, length, type;
4790
4791 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
4792 type = state.implicitTypes[index];
4793
4794 if (type.resolve(str)) {
4795 return true;
4796 }
4797 }
4798
4799 return false;
4800 }
4801
4802 // [33] s-white ::= s-space | s-tab
4803 function isWhitespace(c) {
4804 return c === CHAR_SPACE || c === CHAR_TAB;
4805 }
4806
4807 // Returns true if the character can be printed without escaping.
4808 // From YAML 1.2: "any allowed characters known to be non-printable
4809 // should also be escaped. [However,] This isn’t mandatory"
4810 // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
4811 function isPrintable(c) {
4812 return (0x00020 <= c && c <= 0x00007E)
4813 || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
4814 || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
4815 || (0x10000 <= c && c <= 0x10FFFF);
4816 }
4817
4818 // Simplified test for values allowed after the first character in plain style.
4819 function isPlainSafe(c) {
4820 // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
4821 // where nb-char ::= c-printable - b-char - c-byte-order-mark.
4822 return isPrintable(c) && c !== 0xFEFF
4823 // - c-flow-indicator
4824 && c !== CHAR_COMMA
4825 && c !== CHAR_LEFT_SQUARE_BRACKET
4826 && c !== CHAR_RIGHT_SQUARE_BRACKET
4827 && c !== CHAR_LEFT_CURLY_BRACKET
4828 && c !== CHAR_RIGHT_CURLY_BRACKET
4829 // - ":" - "#"
4830 && c !== CHAR_COLON
4831 && c !== CHAR_SHARP;
4832 }
4833
4834 // Simplified test for values allowed as the first character in plain style.
4835 function isPlainSafeFirst(c) {
4836 // Uses a subset of ns-char - c-indicator
4837 // where ns-char = nb-char - s-white.
4838 return isPrintable(c) && c !== 0xFEFF
4839 && !isWhitespace(c) // - s-white
4840 // - (c-indicator ::=
4841 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
4842 && c !== CHAR_MINUS
4843 && c !== CHAR_QUESTION
4844 && c !== CHAR_COLON
4845 && c !== CHAR_COMMA
4846 && c !== CHAR_LEFT_SQUARE_BRACKET
4847 && c !== CHAR_RIGHT_SQUARE_BRACKET
4848 && c !== CHAR_LEFT_CURLY_BRACKET
4849 && c !== CHAR_RIGHT_CURLY_BRACKET
4850 // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
4851 && c !== CHAR_SHARP
4852 && c !== CHAR_AMPERSAND
4853 && c !== CHAR_ASTERISK
4854 && c !== CHAR_EXCLAMATION
4855 && c !== CHAR_VERTICAL_LINE
4856 && c !== CHAR_GREATER_THAN
4857 && c !== CHAR_SINGLE_QUOTE
4858 && c !== CHAR_DOUBLE_QUOTE
4859 // | “%” | “@” | “`”)
4860 && c !== CHAR_PERCENT
4861 && c !== CHAR_COMMERCIAL_AT
4862 && c !== CHAR_GRAVE_ACCENT;
4863 }
4864
4865 // Determines whether block indentation indicator is required.
4866 function needIndentIndicator(string) {
4867 var leadingSpaceRe = /^\n* /;
4868 return leadingSpaceRe.test(string);
4869 }
4870
4871 var STYLE_PLAIN = 1,
4872 STYLE_SINGLE = 2,
4873 STYLE_LITERAL = 3,
4874 STYLE_FOLDED = 4,
4875 STYLE_DOUBLE = 5;
4876
4877 // Determines which scalar styles are possible and returns the preferred style.
4878 // lineWidth = -1 => no limit.
4879 // Pre-conditions: str.length > 0.
4880 // Post-conditions:
4881 // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
4882 // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
4883 // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
4884 function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
4885 var i;
4886 var char;
4887 var hasLineBreak = false;
4888 var hasFoldableLine = false; // only checked if shouldTrackWidth
4889 var shouldTrackWidth = lineWidth !== -1;
4890 var previousLineBreak = -1; // count the first line correctly
4891 var plain = isPlainSafeFirst(string.charCodeAt(0))
4892 && !isWhitespace(string.charCodeAt(string.length - 1));
4893
4894 if (singleLineOnly) {
4895 // Case: no block styles.
4896 // Check for disallowed characters to rule out plain and single.
4897 for (i = 0; i < string.length; i++) {
4898 char = string.charCodeAt(i);
4899 if (!isPrintable(char)) {
4900 return STYLE_DOUBLE;
4901 }
4902 plain = plain && isPlainSafe(char);
4903 }
4904 } else {
4905 // Case: block styles permitted.
4906 for (i = 0; i < string.length; i++) {
4907 char = string.charCodeAt(i);
4908 if (char === CHAR_LINE_FEED) {
4909 hasLineBreak = true;
4910 // Check if any line can be folded.
4911 if (shouldTrackWidth) {
4912 hasFoldableLine = hasFoldableLine ||
4913 // Foldable line = too long, and not more-indented.
4914 (i - previousLineBreak - 1 > lineWidth &&
4915 string[previousLineBreak + 1] !== ' ');
4916 previousLineBreak = i;
4917 }
4918 } else if (!isPrintable(char)) {
4919 return STYLE_DOUBLE;
4920 }
4921 plain = plain && isPlainSafe(char);
4922 }
4923 // in case the end is missing a \n
4924 hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
4925 (i - previousLineBreak - 1 > lineWidth &&
4926 string[previousLineBreak + 1] !== ' '));
4927 }
4928 // Although every style can represent \n without escaping, prefer block styles
4929 // for multiline, since they're more readable and they don't add empty lines.
4930 // Also prefer folding a super-long line.
4931 if (!hasLineBreak && !hasFoldableLine) {
4932 // Strings interpretable as another type have to be quoted;
4933 // e.g. the string 'true' vs. the boolean true.
4934 return plain && !testAmbiguousType(string)
4935 ? STYLE_PLAIN : STYLE_SINGLE;
4936 }
4937 // Edge case: block indentation indicator can only have one digit.
4938 if (indentPerLevel > 9 && needIndentIndicator(string)) {
4939 return STYLE_DOUBLE;
4940 }
4941 // At this point we know block styles are valid.
4942 // Prefer literal style unless we want to fold.
4943 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
4944 }
4945
4946 // Note: line breaking/folding is implemented for only the folded style.
4947 // NB. We drop the last trailing newline (if any) of a returned block scalar
4948 // since the dumper adds its own newline. This always works:
4949 // • No ending newline => unaffected; already using strip "-" chomping.
4950 // • Ending newline => removed then restored.
4951 // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
4952 function writeScalar(state, string, level, iskey) {
4953 state.dump = (function () {
4954 if (string.length === 0) {
4955 return "''";
4956 }
4957 if (!state.noCompatMode &&
4958 DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
4959 return "'" + string + "'";
4960 }
4961
4962 var indent = state.indent * Math.max(1, level); // no 0-indent scalars
4963 // As indentation gets deeper, let the width decrease monotonically
4964 // to the lower bound min(state.lineWidth, 40).
4965 // Note that this implies
4966 // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
4967 // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
4968 // This behaves better than a constant minimum width which disallows narrower options,
4969 // or an indent threshold which causes the width to suddenly increase.
4970 var lineWidth = state.lineWidth === -1
4971 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
4972
4973 // Without knowing if keys are implicit/explicit, assume implicit for safety.
4974 var singleLineOnly = iskey
4975 // No block styles in flow mode.
4976 || (state.flowLevel > -1 && level >= state.flowLevel);
4977 function testAmbiguity(string) {
4978 return testImplicitResolving(state, string);
4979 }
4980
4981 switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
4982 case STYLE_PLAIN:
4983 return string;
4984 case STYLE_SINGLE:
4985 return "'" + string.replace(/'/g, "''") + "'";
4986 case STYLE_LITERAL:
4987 return '|' + blockHeader(string, state.indent)
4988 + dropEndingNewline(indentString(string, indent));
4989 case STYLE_FOLDED:
4990 return '>' + blockHeader(string, state.indent)
4991 + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
4992 case STYLE_DOUBLE:
4993 return '"' + escapeString(string) + '"';
4994 default:
4995 throw new exception('impossible error: invalid scalar style');
4996 }
4997 }());
4998 }
4999
5000 // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
5001 function blockHeader(string, indentPerLevel) {
5002 var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
5003
5004 // note the special case: the string '\n' counts as a "trailing" empty line.
5005 var clip = string[string.length - 1] === '\n';
5006 var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
5007 var chomp = keep ? '+' : (clip ? '' : '-');
5008
5009 return indentIndicator + chomp + '\n';
5010 }
5011
5012 // (See the note for writeScalar.)
5013 function dropEndingNewline(string) {
5014 return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
5015 }
5016
5017 // Note: a long line without a suitable break point will exceed the width limit.
5018 // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
5019 function foldString(string, width) {
5020 // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
5021 // unless they're before or after a more-indented line, or at the very
5022 // beginning or end, in which case $k$ maps to $k$.
5023 // Therefore, parse each chunk as newline(s) followed by a content line.
5024 var lineRe = /(\n+)([^\n]*)/g;
5025
5026 // first line (possibly an empty line)
5027 var result = (function () {
5028 var nextLF = string.indexOf('\n');
5029 nextLF = nextLF !== -1 ? nextLF : string.length;
5030 lineRe.lastIndex = nextLF;
5031 return foldLine(string.slice(0, nextLF), width);
5032 }());
5033 // If we haven't reached the first content line yet, don't add an extra \n.
5034 var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
5035 var moreIndented;
5036
5037 // rest of the lines
5038 var match;
5039 while ((match = lineRe.exec(string))) {
5040 var prefix = match[1], line = match[2];
5041 moreIndented = (line[0] === ' ');
5042 result += prefix
5043 + (!prevMoreIndented && !moreIndented && line !== ''
5044 ? '\n' : '')
5045 + foldLine(line, width);
5046 prevMoreIndented = moreIndented;
5047 }
5048
5049 return result;
5050 }
5051
5052 // Greedy line breaking.
5053 // Picks the longest line under the limit each time,
5054 // otherwise settles for the shortest line over the limit.
5055 // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
5056 function foldLine(line, width) {
5057 if (line === '' || line[0] === ' ') return line;
5058
5059 // Since a more-indented line adds a \n, breaks can't be followed by a space.
5060 var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
5061 var match;
5062 // start is an inclusive index. end, curr, and next are exclusive.
5063 var start = 0, end, curr = 0, next = 0;
5064 var result = '';
5065
5066 // Invariants: 0 <= start <= length-1.
5067 // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
5068 // Inside the loop:
5069 // A match implies length >= 2, so curr and next are <= length-2.
5070 while ((match = breakRe.exec(line))) {
5071 next = match.index;
5072 // maintain invariant: curr - start <= width
5073 if (next - start > width) {
5074 end = (curr > start) ? curr : next; // derive end <= length-2
5075 result += '\n' + line.slice(start, end);
5076 // skip the space that was output as \n
5077 start = end + 1; // derive start <= length-1
5078 }
5079 curr = next;
5080 }
5081
5082 // By the invariants, start <= length-1, so there is something left over.
5083 // It is either the whole string or a part starting from non-whitespace.
5084 result += '\n';
5085 // Insert a break if the remainder is too long and there is a break available.
5086 if (line.length - start > width && curr > start) {
5087 result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
5088 } else {
5089 result += line.slice(start);
5090 }
5091
5092 return result.slice(1); // drop extra \n joiner
5093 }
5094
5095 // Escapes a double-quoted string.
5096 function escapeString(string) {
5097 var result = '';
5098 var char, nextChar;
5099 var escapeSeq;
5100
5101 for (var i = 0; i < string.length; i++) {
5102 char = string.charCodeAt(i);
5103 // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
5104 if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
5105 nextChar = string.charCodeAt(i + 1);
5106 if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
5107 // Combine the surrogate pair and store it escaped.
5108 result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
5109 // Advance index one extra since we already used that char here.
5110 i++; continue;
5111 }
5112 }
5113 escapeSeq = ESCAPE_SEQUENCES[char];
5114 result += !escapeSeq && isPrintable(char)
5115 ? string[i]
5116 : escapeSeq || encodeHex(char);
5117 }
5118
5119 return result;
5120 }
5121
5122 function writeFlowSequence(state, level, object) {
5123 var _result = '',
5124 _tag = state.tag,
5125 index,
5126 length;
5127
5128 for (index = 0, length = object.length; index < length; index += 1) {
5129 // Write only valid elements.
5130 if (writeNode(state, level, object[index], false, false)) {
5131 if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
5132 _result += state.dump;
5133 }
5134 }
5135
5136 state.tag = _tag;
5137 state.dump = '[' + _result + ']';
5138 }
5139
5140 function writeBlockSequence(state, level, object, compact) {
5141 var _result = '',
5142 _tag = state.tag,
5143 index,
5144 length;
5145
5146 for (index = 0, length = object.length; index < length; index += 1) {
5147 // Write only valid elements.
5148 if (writeNode(state, level + 1, object[index], true, true)) {
5149 if (!compact || index !== 0) {
5150 _result += generateNextLine(state, level);
5151 }
5152
5153 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
5154 _result += '-';
5155 } else {
5156 _result += '- ';
5157 }
5158
5159 _result += state.dump;
5160 }
5161 }
5162
5163 state.tag = _tag;
5164 state.dump = _result || '[]'; // Empty sequence if no valid values.
5165 }
5166
5167 function writeFlowMapping(state, level, object) {
5168 var _result = '',
5169 _tag = state.tag,
5170 objectKeyList = Object.keys(object),
5171 index,
5172 length,
5173 objectKey,
5174 objectValue,
5175 pairBuffer;
5176
5177 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
5178 pairBuffer = state.condenseFlow ? '"' : '';
5179
5180 if (index !== 0) pairBuffer += ', ';
5181
5182 objectKey = objectKeyList[index];
5183 objectValue = object[objectKey];
5184
5185 if (!writeNode(state, level, objectKey, false, false)) {
5186 continue; // Skip this pair because of invalid key;
5187 }
5188
5189 if (state.dump.length > 1024) pairBuffer += '? ';
5190
5191 pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
5192
5193 if (!writeNode(state, level, objectValue, false, false)) {
5194 continue; // Skip this pair because of invalid value.
5195 }
5196
5197 pairBuffer += state.dump;
5198
5199 // Both key and value are valid.
5200 _result += pairBuffer;
5201 }
5202
5203 state.tag = _tag;
5204 state.dump = '{' + _result + '}';
5205 }
5206
5207 function writeBlockMapping(state, level, object, compact) {
5208 var _result = '',
5209 _tag = state.tag,
5210 objectKeyList = Object.keys(object),
5211 index,
5212 length,
5213 objectKey,
5214 objectValue,
5215 explicitPair,
5216 pairBuffer;
5217
5218 // Allow sorting keys so that the output file is deterministic
5219 if (state.sortKeys === true) {
5220 // Default sorting
5221 objectKeyList.sort();
5222 } else if (typeof state.sortKeys === 'function') {
5223 // Custom sort function
5224 objectKeyList.sort(state.sortKeys);
5225 } else if (state.sortKeys) {
5226 // Something is wrong
5227 throw new exception('sortKeys must be a boolean or a function');
5228 }
5229
5230 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
5231 pairBuffer = '';
5232
5233 if (!compact || index !== 0) {
5234 pairBuffer += generateNextLine(state, level);
5235 }
5236
5237 objectKey = objectKeyList[index];
5238 objectValue = object[objectKey];
5239
5240 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
5241 continue; // Skip this pair because of invalid key.
5242 }
5243
5244 explicitPair = (state.tag !== null && state.tag !== '?') ||
5245 (state.dump && state.dump.length > 1024);
5246
5247 if (explicitPair) {
5248 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
5249 pairBuffer += '?';
5250 } else {
5251 pairBuffer += '? ';
5252 }
5253 }
5254
5255 pairBuffer += state.dump;
5256
5257 if (explicitPair) {
5258 pairBuffer += generateNextLine(state, level);
5259 }
5260
5261 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
5262 continue; // Skip this pair because of invalid value.
5263 }
5264
5265 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
5266 pairBuffer += ':';
5267 } else {
5268 pairBuffer += ': ';
5269 }
5270
5271 pairBuffer += state.dump;
5272
5273 // Both key and value are valid.
5274 _result += pairBuffer;
5275 }
5276
5277 state.tag = _tag;
5278 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
5279 }
5280
5281 function detectType(state, object, explicit) {
5282 var _result, typeList, index, length, type, style;
5283
5284 typeList = explicit ? state.explicitTypes : state.implicitTypes;
5285
5286 for (index = 0, length = typeList.length; index < length; index += 1) {
5287 type = typeList[index];
5288
5289 if ((type.instanceOf || type.predicate) &&
5290 (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
5291 (!type.predicate || type.predicate(object))) {
5292
5293 state.tag = explicit ? type.tag : '?';
5294
5295 if (type.represent) {
5296 style = state.styleMap[type.tag] || type.defaultStyle;
5297
5298 if (_toString$2.call(type.represent) === '[object Function]') {
5299 _result = type.represent(object, style);
5300 } else if (_hasOwnProperty$3.call(type.represent, style)) {
5301 _result = type.represent[style](object, style);
5302 } else {
5303 throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
5304 }
5305
5306 state.dump = _result;
5307 }
5308
5309 return true;
5310 }
5311 }
5312
5313 return false;
5314 }
5315
5316 // Serializes `object` and writes it to global `result`.
5317 // Returns true on success, or false on invalid object.
5318 //
5319 function writeNode(state, level, object, block, compact, iskey) {
5320 state.tag = null;
5321 state.dump = object;
5322
5323 if (!detectType(state, object, false)) {
5324 detectType(state, object, true);
5325 }
5326
5327 var type = _toString$2.call(state.dump);
5328
5329 if (block) {
5330 block = (state.flowLevel < 0 || state.flowLevel > level);
5331 }
5332
5333 var objectOrArray = type === '[object Object]' || type === '[object Array]',
5334 duplicateIndex,
5335 duplicate;
5336
5337 if (objectOrArray) {
5338 duplicateIndex = state.duplicates.indexOf(object);
5339 duplicate = duplicateIndex !== -1;
5340 }
5341
5342 if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
5343 compact = false;
5344 }
5345
5346 if (duplicate && state.usedDuplicates[duplicateIndex]) {
5347 state.dump = '*ref_' + duplicateIndex;
5348 } else {
5349 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
5350 state.usedDuplicates[duplicateIndex] = true;
5351 }
5352 if (type === '[object Object]') {
5353 if (block && (Object.keys(state.dump).length !== 0)) {
5354 writeBlockMapping(state, level, state.dump, compact);
5355 if (duplicate) {
5356 state.dump = '&ref_' + duplicateIndex + state.dump;
5357 }
5358 } else {
5359 writeFlowMapping(state, level, state.dump);
5360 if (duplicate) {
5361 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
5362 }
5363 }
5364 } else if (type === '[object Array]') {
5365 var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
5366 if (block && (state.dump.length !== 0)) {
5367 writeBlockSequence(state, arrayLevel, state.dump, compact);
5368 if (duplicate) {
5369 state.dump = '&ref_' + duplicateIndex + state.dump;
5370 }
5371 } else {
5372 writeFlowSequence(state, arrayLevel, state.dump);
5373 if (duplicate) {
5374 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
5375 }
5376 }
5377 } else if (type === '[object String]') {
5378 if (state.tag !== '?') {
5379 writeScalar(state, state.dump, level, iskey);
5380 }
5381 } else {
5382 if (state.skipInvalid) return false;
5383 throw new exception('unacceptable kind of an object to dump ' + type);
5384 }
5385
5386 if (state.tag !== null && state.tag !== '?') {
5387 state.dump = '!<' + state.tag + '> ' + state.dump;
5388 }
5389 }
5390
5391 return true;
5392 }
5393
5394 function getDuplicateReferences(object, state) {
5395 var objects = [],
5396 duplicatesIndexes = [],
5397 index,
5398 length;
5399
5400 inspectNode(object, objects, duplicatesIndexes);
5401
5402 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
5403 state.duplicates.push(objects[duplicatesIndexes[index]]);
5404 }
5405 state.usedDuplicates = new Array(length);
5406 }
5407
5408 function inspectNode(object, objects, duplicatesIndexes) {
5409 var objectKeyList,
5410 index,
5411 length;
5412
5413 if (object !== null && typeof object === 'object') {
5414 index = objects.indexOf(object);
5415 if (index !== -1) {
5416 if (duplicatesIndexes.indexOf(index) === -1) {
5417 duplicatesIndexes.push(index);
5418 }
5419 } else {
5420 objects.push(object);
5421
5422 if (Array.isArray(object)) {
5423 for (index = 0, length = object.length; index < length; index += 1) {
5424 inspectNode(object[index], objects, duplicatesIndexes);
5425 }
5426 } else {
5427 objectKeyList = Object.keys(object);
5428
5429 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
5430 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
5431 }
5432 }
5433 }
5434 }
5435 }
5436
5437 function dump(input, options) {
5438 options = options || {};
5439
5440 var state = new State$1(options);
5441
5442 if (!state.noRefs) getDuplicateReferences(input, state);
5443
5444 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
5445
5446 return '';
5447 }
5448
5449 function safeDump(input, options) {
5450 return dump(input, common.extend({ schema: default_safe }, options));
5451 }
5452
5453 var dump_1 = dump;
5454 var safeDump_1 = safeDump;
5455
5456 var dumper = {
5457 dump: dump_1,
5458 safeDump: safeDump_1
5459 };
5460
5461 function deprecated(name) {
5462 return function () {
5463 throw new Error('Function ' + name + ' is deprecated and cannot be used.');
5464 };
5465 }
5466
5467
5468 var Type$1 = type;
5469 var Schema$1 = schema;
5470 var FAILSAFE_SCHEMA = failsafe;
5471 var JSON_SCHEMA = json;
5472 var CORE_SCHEMA = core;
5473 var DEFAULT_SAFE_SCHEMA = default_safe;
5474 var DEFAULT_FULL_SCHEMA = default_full;
5475 var load$1 = loader.load;
5476 var loadAll$1 = loader.loadAll;
5477 var safeLoad$1 = loader.safeLoad;
5478 var safeLoadAll$1 = loader.safeLoadAll;
5479 var dump$1 = dumper.dump;
5480 var safeDump$1 = dumper.safeDump;
5481 var YAMLException$1 = exception;
5482
5483 // Deprecated schema names from JS-YAML 2.0.x
5484 var MINIMAL_SCHEMA = failsafe;
5485 var SAFE_SCHEMA = default_safe;
5486 var DEFAULT_SCHEMA = default_full;
5487
5488 // Deprecated functions from JS-YAML 1.x.x
5489 var scan = deprecated('scan');
5490 var parse = deprecated('parse');
5491 var compose = deprecated('compose');
5492 var addConstructor = deprecated('addConstructor');
5493
5494 var jsYaml = {
5495 Type: Type$1,
5496 Schema: Schema$1,
5497 FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
5498 JSON_SCHEMA: JSON_SCHEMA,
5499 CORE_SCHEMA: CORE_SCHEMA,
5500 DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA,
5501 DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA,
5502 load: load$1,
5503 loadAll: loadAll$1,
5504 safeLoad: safeLoad$1,
5505 safeLoadAll: safeLoadAll$1,
5506 dump: dump$1,
5507 safeDump: safeDump$1,
5508 YAMLException: YAMLException$1,
5509 MINIMAL_SCHEMA: MINIMAL_SCHEMA,
5510 SAFE_SCHEMA: SAFE_SCHEMA,
5511 DEFAULT_SCHEMA: DEFAULT_SCHEMA,
5512 scan: scan,
5513 parse: parse,
5514 compose: compose,
5515 addConstructor: addConstructor
5516 };
5517
5518 var jsYaml$1 = jsYaml;
5519
5520 var Step =
5521 /*#__PURE__*/
5522 function () {
5523 function Step(cvs, userStepConfig, defaultStepConfig) {
5524 _classCallCheck(this, Step);
5525
5526 this.cvs = cvs;
5527 this.localPath;
5528 this.gitURL;
5529 this.libraryURL;
5530 this.id;
5531 this.version;
5532 this.userStepConfig = userStepConfig;
5533
5534 if (!this.userStepConfig) {
5535 this.userStepConfig = {};
5536 }
5537
5538 this.defaultStepConfig = defaultStepConfig;
5539 }
5540
5541 _createClass(Step, null, [{
5542 key: "cvsFromWrappedStepConfig",
5543 value: function cvsFromWrappedStepConfig(wrappedStepConfig) {
5544 return underscore.first(underscore.keys(wrappedStepConfig));
5545 }
5546 }]);
5547
5548 return Step;
5549 }();
5550
5551 var Workflow = function Workflow(id, workflowConfig, stepSourceService) {
5552 _classCallCheck(this, Workflow);
5553
5554 this.id = id;
5555 this.workflowConfig = workflowConfig;
5556
5557 if (!this.workflowConfig) {
5558 return;
5559 }
5560
5561 this.steps = underscore.map(workflowConfig.steps, function (aWrappedUserStepConfig) {
5562 var stepCVS = Step.cvsFromWrappedStepConfig(aWrappedUserStepConfig);
5563 var step;
5564 var userStepConfig = aWrappedUserStepConfig[stepCVS];
5565
5566 try {
5567 step = stepSourceService.stepFromCVS(stepCVS);
5568 step.userStepConfig = userStepConfig;
5569 } catch (error) {
5570 console.log(error.message);
5571 step = new Step(stepCVS, userStepConfig);
5572 }
5573
5574 return step;
5575 });
5576 };
5577
5578 var App = function App(bitriseYML, stepSourceService) {
5579 _classCallCheck(this, App);
5580
5581 var appConfig = jsYaml$1.safeLoad(bitriseYML);
5582 this.defaultLibraryURL = appConfig.default_step_lib_source;
5583 this.workflows = underscore.map(appConfig.workflows, function (workflowConfig, workflowID) {
5584 return new Workflow(workflowID, workflowConfig, stepSourceService);
5585 });
5586 };
5587
5588 var RequestService =
5589 /*#__PURE__*/
5590 function () {
5591 function RequestService() {
5592 _classCallCheck(this, RequestService);
5593 }
5594
5595 _createClass(RequestService, null, [{
5596 key: "libraryFetch",
5597 value: function libraryFetch(libraryURLs) {
5598 var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'website';
5599 return new Promise(function (resolve, reject) {
5600 var request = new XMLHttpRequest();
5601 var requestMethod;
5602 var requestURL;
5603
5604 switch (mode) {
5605 case 'website':
5606 requestMethod = 'get';
5607 requestURL = 'https://bitrise-steplib-collection.s3.amazonaws.com/spec.json.gz';
5608 break;
5609
5610 case 'cli':
5611 requestMethod = 'post';
5612 requestURL = '/api/spec';
5613 break;
5614 }
5615
5616 request.open(requestMethod, requestURL);
5617 request.setRequestHeader('Content-Type', 'application/json');
5618 var requestData = {};
5619
5620 if (libraryURLs) {
5621 requestData = {
5622 libraries: libraryURLs
5623 };
5624 }
5625
5626 request.onload = function () {
5627 if (request.status === 200) {
5628 var responseData = JSON.parse(request.response);
5629
5630 switch (mode) {
5631 case 'website':
5632 var libraryMap = {};
5633 libraryMap[responseData.steplib_source] = responseData;
5634 resolve(libraryMap);
5635 break;
5636
5637 case 'cli':
5638 resolve(responseData.library_map);
5639 break;
5640 }
5641 } else {
5642 reject(new Error('Error loading library.'));
5643 }
5644 };
5645
5646 request.send(JSON.stringify(requestData));
5647 });
5648 }
5649 }]);
5650
5651 return RequestService;
5652 }();
5653
5654 var BITRISE_STEPLIB_URL = 'https://github.com/bitrise-io/bitrise-steplib.git';
5655 var StepSourceService =
5656 /*#__PURE__*/
5657 function () {
5658 function StepSourceService() {
5659 var defaultLibraryURL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : BITRISE_STEPLIB_URL;
5660 var libraries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
5661 var localSteps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
5662 var gitSteps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
5663
5664 _classCallCheck(this, StepSourceService);
5665
5666 this.defaultLibraryURL = defaultLibraryURL;
5667 this.libraries = libraries;
5668 this.localSteps = localSteps;
5669 this.gitSteps = gitSteps;
5670 }
5671
5672 _createClass(StepSourceService, [{
5673 key: "loadDefaultLibrary",
5674 value: function loadDefaultLibrary() {
5675 return this.loadLibrariesWithURLs([this.defaultLibraryURL]);
5676 }
5677 }, {
5678 key: "loadLibrariesWithURLs",
5679 value: function loadLibrariesWithURLs() {
5680 var _this = this;
5681
5682 var libraryURLs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
5683 return new Promise(function (resolve, reject) {
5684 var notLoadedLibraryURLs = underscore.reject(underscore.uniq(libraryURLs.concat(_this.defaultLibraryURL)), function (aLibraryURL) {
5685 return underscore.find(_this.libraries, {
5686 url: aLibraryURL
5687 });
5688 });
5689
5690 if (notLoadedLibraryURLs.length == 0) {
5691 resolve();
5692 return;
5693 }
5694
5695 return RequestService.libraryFetch(notLoadedLibraryURLs).then(function (data) {
5696 underscore.each(data, function (aLibraryData, aLibraryURL) {
5697 try {
5698 var library = {
5699 url: aLibraryURL
5700 };
5701
5702 var stepIDs = underscore.keys(aLibraryData.steps).sort();
5703
5704 library.steps = {};
5705 library.latestStepVersions = {};
5706 library.deprecatedSteps = [];
5707
5708 underscore.each(stepIDs, function (aStepID) {
5709 library.steps[aStepID] = {};
5710 library.latestStepVersions[aStepID] = aLibraryData.steps[aStepID].latest_version_number;
5711 library.steps[aStepID] = underscore.mapObject(aLibraryData.steps[aStepID].versions, function (aStepConfig, version) {
5712 var cvs = aStepID + '@' + version;
5713
5714 var step = _this.stepFromCVS(cvs);
5715
5716 step.defaultStepConfig = aStepConfig;
5717 return step;
5718 });
5719
5720 if (aLibraryData.steps[aStepID].info !== undefined && aLibraryData.steps[aStepID].info.deprecate_notes !== undefined) {
5721 underscore.each(library.steps[aStepID], function (aStep) {
5722 library.deprecatedSteps.push(aStep);
5723 });
5724 }
5725 });
5726
5727 _this.libraries.push(library);
5728
5729 resolve();
5730 } catch (error) {
5731 console.log(error.message);
5732 reject(new Error('Error loading library.'));
5733 }
5734 });
5735 }, function (error) {
5736 reject(error);
5737 });
5738 });
5739 }
5740 }, {
5741 key: "stepFromCVS",
5742 value: function stepFromCVS(cvs) {
5743 var step = new Step(cvs);
5744 var idStartIndex = cvs.indexOf('::') != -1 ? cvs.indexOf('::') + 2 : 0;
5745 var versionStartIndex = cvs.lastIndexOf('@') != -1 && cvs.indexOf('::') < cvs.lastIndexOf('@') ? cvs.lastIndexOf('@') + 1 : -1;
5746 var source = idStartIndex > 0 && cvs.slice(0, idStartIndex - 2).length > 0 ? cvs.slice(0, idStartIndex - 2) : null;
5747 var id = cvs.slice(idStartIndex, versionStartIndex != -1 ? versionStartIndex - 1 : undefined);
5748 var version = versionStartIndex != -1 && versionStartIndex != cvs.length ? cvs.slice(versionStartIndex) : null;
5749
5750 switch (source) {
5751 case 'path':
5752 if (id.length == 0) {
5753 throw new Error('Path not specified.');
5754 }
5755
5756 step.localPath = id;
5757
5758 var localStep = underscore.find(this.localSteps, {
5759 localPath: step.localPath
5760 });
5761
5762 if (localStep) {
5763 step.defaultStepConfig = localStep.defaultStepConfig;
5764 }
5765
5766 break;
5767
5768 case 'git':
5769 if (id.length == 0) {
5770 throw new Error('Git URL not specified.');
5771 }
5772
5773 step.gitURL = id;
5774 step.version = version;
5775
5776 var gitStep = underscore.find(this.gitSteps, {
5777 gitURL: step.gitURL,
5778 version: step.version
5779 });
5780
5781 if (gitStep) {
5782 step.defaultStepConfig = gitStep.defaultStepConfig;
5783 }
5784
5785 break;
5786
5787 default:
5788 if (!source && !this.defaultLibraryURL) {
5789 throw new Error('Step library not specified.');
5790 }
5791
5792 if (id.length == 0) {
5793 throw new Error('Step ID not specified.');
5794 }
5795
5796 step.libraryURL = source != null ? source : this.defaultLibraryURL;
5797 step.id = id;
5798 step.version = version;
5799
5800 var library = underscore.find(this.libraries, {
5801 url: step.libraryURL
5802 });
5803
5804 if (!library) {
5805 break;
5806 }
5807
5808 if (!library.steps[step.id]) {
5809 throw new Error("Step with ID not found in library: ".concat(step.id));
5810 }
5811
5812 var requestedVersion = step.version ? step.version : library.latestStepVersions[step.id];
5813
5814 if (!library.steps[step.id][requestedVersion]) {
5815 throw new Error("Step with version not found in library: ".concat(requestedVersion));
5816 }
5817
5818 step.version = requestedVersion;
5819 step.defaultStepConfig = library.steps[step.id][requestedVersion].defaultStepConfig;
5820 }
5821
5822 return step;
5823 }
5824 }, {
5825 key: "versionsOfStep",
5826 value: function versionsOfStep(step) {
5827 if (step.libraryURL !== undefined) {
5828 var library = underscore.find(this.libraries, {
5829 url: step.libraryURL
5830 });
5831
5832 return underscore.sortBy(underscore.keys(library.steps[step.id]), function (version) {
5833 return underscore.map(version.split('.'), function (aVersionPart) {
5834 var pad = '000000';
5835 var versionPartWithLeadingZeros = pad.substring(0, pad.length - aVersionPart.length) + aVersionPart;
5836 return versionPartWithLeadingZeros;
5837 }).join('.');
5838 }).reverse();
5839 } else if (step.localPath !== undefined) {
5840 return undefined;
5841 } else if (step.gitURL !== undefined) {
5842 return [step.version];
5843 }
5844 }
5845 }, {
5846 key: "isLatestStepVersion",
5847 value: function isLatestStepVersion(step) {
5848 if (step.libraryURL !== undefined) {
5849 var library = underscore.find(this.libraries, {
5850 url: step.libraryURL
5851 });
5852
5853 return step.version === null || step.version == library.latestStepVersions[step.id];
5854 } else if (step.localPath !== undefined) {
5855 return undefined;
5856 } else if (step.gitURL !== undefined) {
5857 return true;
5858 }
5859 }
5860 }, {
5861 key: "isStepAtLeastOnVersion",
5862 value: function isStepAtLeastOnVersion(step, version) {
5863 var versions = this.versionsOfStep(step);
5864 return versions.indexOf(step.version) <= versions.indexOf(version);
5865 }
5866 }]);
5867
5868 return StepSourceService;
5869 }();
5870
5871 exports.App = App;
5872 exports.Step = Step;
5873 exports.StepSourceService = StepSourceService;
5874 exports.Workflow = Workflow;
5875
5876 Object.defineProperty(exports, '__esModule', { value: true });
5877
5878}));