UNPKG

186 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var path$4 = require('path');
6var stream = require('stream');
7var SVGIcons2SVGFontStream = require('svgicons2svgfont');
8var require$$0$2 = require('os');
9var require$$0 = require('parse-json');
10var require$$1 = require('resolve-from');
11var require$$0$1 = require('fs');
12var crypto = require('crypto');
13var deepmerge = require('deepmerge');
14var globby = require('globby');
15var nunjucks = require('nunjucks');
16var pLimit = require('p-limit');
17var svg2ttf = require('svg2ttf');
18var ttf2eot = require('ttf2eot');
19var ttf2woff = require('ttf2woff');
20var wawoff2 = require('wawoff2');
21var xml2js = require('xml2js');
22
23function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
25var path__default = /*#__PURE__*/_interopDefaultLegacy(path$4);
26var SVGIcons2SVGFontStream__default = /*#__PURE__*/_interopDefaultLegacy(SVGIcons2SVGFontStream);
27var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
28var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
29var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
30var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
31var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
32var deepmerge__default = /*#__PURE__*/_interopDefaultLegacy(deepmerge);
33var globby__default = /*#__PURE__*/_interopDefaultLegacy(globby);
34var nunjucks__default = /*#__PURE__*/_interopDefaultLegacy(nunjucks);
35var pLimit__default = /*#__PURE__*/_interopDefaultLegacy(pLimit);
36var svg2ttf__default = /*#__PURE__*/_interopDefaultLegacy(svg2ttf);
37var ttf2eot__default = /*#__PURE__*/_interopDefaultLegacy(ttf2eot);
38var ttf2woff__default = /*#__PURE__*/_interopDefaultLegacy(ttf2woff);
39var wawoff2__default = /*#__PURE__*/_interopDefaultLegacy(wawoff2);
40var xml2js__default = /*#__PURE__*/_interopDefaultLegacy(xml2js);
41
42/*! *****************************************************************************
43Copyright (c) Microsoft Corporation.
44
45Permission to use, copy, modify, and/or distribute this software for any
46purpose with or without fee is hereby granted.
47
48THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
49REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
50AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
51INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
52LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
53OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
54PERFORMANCE OF THIS SOFTWARE.
55***************************************************************************** */
56
57var __assign = function() {
58 __assign = Object.assign || function __assign(t) {
59 for (var s, i = 1, n = arguments.length; i < n; i++) {
60 s = arguments[i];
61 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
62 }
63 return t;
64 };
65 return __assign.apply(this, arguments);
66};
67
68function __awaiter(thisArg, _arguments, P, generator) {
69 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
70 return new (P || (P = Promise))(function (resolve, reject) {
71 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
72 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
73 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
74 step((generator = generator.apply(thisArg, _arguments || [])).next());
75 });
76}
77
78function __generator(thisArg, body) {
79 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
80 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
81 function verb(n) { return function (v) { return step([n, v]); }; }
82 function step(op) {
83 if (f) throw new TypeError("Generator is already executing.");
84 while (_) try {
85 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
86 if (y = 0, t) op = [op[0] & 2, t.value];
87 switch (op[0]) {
88 case 0: case 1: t = op; break;
89 case 4: _.label++; return { value: op[1], done: false };
90 case 5: _.label++; y = op[1]; op = [0]; continue;
91 case 7: op = _.ops.pop(); _.trys.pop(); continue;
92 default:
93 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
94 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
95 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
96 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
97 if (t[2]) _.ops.pop();
98 _.trys.pop(); continue;
99 }
100 op = body.call(thisArg, _);
101 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
102 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
103 }
104}
105
106var getTemplateDirectory = function () { return path__default['default'].resolve(__dirname, "../templates"); };
107var getTemplateFilePath = function (template) {
108 var templateDirectory = getTemplateDirectory();
109 return templateDirectory + "/template." + template + ".njk";
110};
111var getBuiltInTemplates = function () {
112 var templateDirectory = getTemplateDirectory();
113 return {
114 css: { path: path__default['default'].join(templateDirectory, "template.css.njk") },
115 html: { path: path__default['default'].join(templateDirectory, "template.html.njk") },
116 json: { path: path__default['default'].join(templateDirectory, "template.json.njk") },
117 scss: { path: path__default['default'].join(templateDirectory, "template.scss.njk") },
118 styl: { path: path__default['default'].join(templateDirectory, "template.styl.njk") }
119 };
120};
121
122function commonjsRequire (path) {
123 throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
124}
125
126var jsYaml$1 = {};
127
128var loader$1 = {};
129
130var common$6 = {};
131
132function isNothing(subject) {
133 return (typeof subject === 'undefined') || (subject === null);
134}
135
136
137function isObject(subject) {
138 return (typeof subject === 'object') && (subject !== null);
139}
140
141
142function toArray(sequence) {
143 if (Array.isArray(sequence)) return sequence;
144 else if (isNothing(sequence)) return [];
145
146 return [ sequence ];
147}
148
149
150function extend(target, source) {
151 var index, length, key, sourceKeys;
152
153 if (source) {
154 sourceKeys = Object.keys(source);
155
156 for (index = 0, length = sourceKeys.length; index < length; index += 1) {
157 key = sourceKeys[index];
158 target[key] = source[key];
159 }
160 }
161
162 return target;
163}
164
165
166function repeat(string, count) {
167 var result = '', cycle;
168
169 for (cycle = 0; cycle < count; cycle += 1) {
170 result += string;
171 }
172
173 return result;
174}
175
176
177function isNegativeZero(number) {
178 return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
179}
180
181
182common$6.isNothing = isNothing;
183common$6.isObject = isObject;
184common$6.toArray = toArray;
185common$6.repeat = repeat;
186common$6.isNegativeZero = isNegativeZero;
187common$6.extend = extend;
188
189function YAMLException$4(reason, mark) {
190 // Super constructor
191 Error.call(this);
192
193 this.name = 'YAMLException';
194 this.reason = reason;
195 this.mark = mark;
196 this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
197
198 // Include stack trace in error object
199 if (Error.captureStackTrace) {
200 // Chrome and NodeJS
201 Error.captureStackTrace(this, this.constructor);
202 } else {
203 // FF, IE 10+ and Safari 6+. Fallback for others
204 this.stack = (new Error()).stack || '';
205 }
206}
207
208
209// Inherit from Error
210YAMLException$4.prototype = Object.create(Error.prototype);
211YAMLException$4.prototype.constructor = YAMLException$4;
212
213
214YAMLException$4.prototype.toString = function toString(compact) {
215 var result = this.name + ': ';
216
217 result += this.reason || '(unknown reason)';
218
219 if (!compact && this.mark) {
220 result += ' ' + this.mark.toString();
221 }
222
223 return result;
224};
225
226
227var exception = YAMLException$4;
228
229var common$5 = common$6;
230
231
232function Mark$1(name, buffer, position, line, column) {
233 this.name = name;
234 this.buffer = buffer;
235 this.position = position;
236 this.line = line;
237 this.column = column;
238}
239
240
241Mark$1.prototype.getSnippet = function getSnippet(indent, maxLength) {
242 var head, start, tail, end, snippet;
243
244 if (!this.buffer) return null;
245
246 indent = indent || 4;
247 maxLength = maxLength || 75;
248
249 head = '';
250 start = this.position;
251
252 while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
253 start -= 1;
254 if (this.position - start > (maxLength / 2 - 1)) {
255 head = ' ... ';
256 start += 5;
257 break;
258 }
259 }
260
261 tail = '';
262 end = this.position;
263
264 while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
265 end += 1;
266 if (end - this.position > (maxLength / 2 - 1)) {
267 tail = ' ... ';
268 end -= 5;
269 break;
270 }
271 }
272
273 snippet = this.buffer.slice(start, end);
274
275 return common$5.repeat(' ', indent) + head + snippet + tail + '\n' +
276 common$5.repeat(' ', indent + this.position - start + head.length) + '^';
277};
278
279
280Mark$1.prototype.toString = function toString(compact) {
281 var snippet, where = '';
282
283 if (this.name) {
284 where += 'in "' + this.name + '" ';
285 }
286
287 where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
288
289 if (!compact) {
290 snippet = this.getSnippet();
291
292 if (snippet) {
293 where += ':\n' + snippet;
294 }
295 }
296
297 return where;
298};
299
300
301var mark = Mark$1;
302
303var YAMLException$3 = exception;
304
305var TYPE_CONSTRUCTOR_OPTIONS = [
306 'kind',
307 'resolve',
308 'construct',
309 'instanceOf',
310 'predicate',
311 'represent',
312 'defaultStyle',
313 'styleAliases'
314];
315
316var YAML_NODE_KINDS = [
317 'scalar',
318 'sequence',
319 'mapping'
320];
321
322function compileStyleAliases(map) {
323 var result = {};
324
325 if (map !== null) {
326 Object.keys(map).forEach(function (style) {
327 map[style].forEach(function (alias) {
328 result[String(alias)] = style;
329 });
330 });
331 }
332
333 return result;
334}
335
336function Type$h(tag, options) {
337 options = options || {};
338
339 Object.keys(options).forEach(function (name) {
340 if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
341 throw new YAMLException$3('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
342 }
343 });
344
345 // TODO: Add tag format check.
346 this.tag = tag;
347 this.kind = options['kind'] || null;
348 this.resolve = options['resolve'] || function () { return true; };
349 this.construct = options['construct'] || function (data) { return data; };
350 this.instanceOf = options['instanceOf'] || null;
351 this.predicate = options['predicate'] || null;
352 this.represent = options['represent'] || null;
353 this.defaultStyle = options['defaultStyle'] || null;
354 this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
355
356 if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
357 throw new YAMLException$3('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
358 }
359}
360
361var type = Type$h;
362
363/*eslint-disable max-len*/
364
365var common$4 = common$6;
366var YAMLException$2 = exception;
367var Type$g = type;
368
369
370function compileList(schema, name, result) {
371 var exclude = [];
372
373 schema.include.forEach(function (includedSchema) {
374 result = compileList(includedSchema, name, result);
375 });
376
377 schema[name].forEach(function (currentType) {
378 result.forEach(function (previousType, previousIndex) {
379 if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
380 exclude.push(previousIndex);
381 }
382 });
383
384 result.push(currentType);
385 });
386
387 return result.filter(function (type, index) {
388 return exclude.indexOf(index) === -1;
389 });
390}
391
392
393function compileMap(/* lists... */) {
394 var result = {
395 scalar: {},
396 sequence: {},
397 mapping: {},
398 fallback: {}
399 }, index, length;
400
401 function collectType(type) {
402 result[type.kind][type.tag] = result['fallback'][type.tag] = type;
403 }
404
405 for (index = 0, length = arguments.length; index < length; index += 1) {
406 arguments[index].forEach(collectType);
407 }
408 return result;
409}
410
411
412function Schema$5(definition) {
413 this.include = definition.include || [];
414 this.implicit = definition.implicit || [];
415 this.explicit = definition.explicit || [];
416
417 this.implicit.forEach(function (type) {
418 if (type.loadKind && type.loadKind !== 'scalar') {
419 throw new YAMLException$2('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
420 }
421 });
422
423 this.compiledImplicit = compileList(this, 'implicit', []);
424 this.compiledExplicit = compileList(this, 'explicit', []);
425 this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
426}
427
428
429Schema$5.DEFAULT = null;
430
431
432Schema$5.create = function createSchema() {
433 var schemas, types;
434
435 switch (arguments.length) {
436 case 1:
437 schemas = Schema$5.DEFAULT;
438 types = arguments[0];
439 break;
440
441 case 2:
442 schemas = arguments[0];
443 types = arguments[1];
444 break;
445
446 default:
447 throw new YAMLException$2('Wrong number of arguments for Schema.create function');
448 }
449
450 schemas = common$4.toArray(schemas);
451 types = common$4.toArray(types);
452
453 if (!schemas.every(function (schema) { return schema instanceof Schema$5; })) {
454 throw new YAMLException$2('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
455 }
456
457 if (!types.every(function (type) { return type instanceof Type$g; })) {
458 throw new YAMLException$2('Specified list of YAML types (or a single Type object) contains a non-Type object.');
459 }
460
461 return new Schema$5({
462 include: schemas,
463 explicit: types
464 });
465};
466
467
468var schema = Schema$5;
469
470var Type$f = type;
471
472var str = new Type$f('tag:yaml.org,2002:str', {
473 kind: 'scalar',
474 construct: function (data) { return data !== null ? data : ''; }
475});
476
477var Type$e = type;
478
479var seq = new Type$e('tag:yaml.org,2002:seq', {
480 kind: 'sequence',
481 construct: function (data) { return data !== null ? data : []; }
482});
483
484var Type$d = type;
485
486var map = new Type$d('tag:yaml.org,2002:map', {
487 kind: 'mapping',
488 construct: function (data) { return data !== null ? data : {}; }
489});
490
491var Schema$4 = schema;
492
493
494var failsafe = new Schema$4({
495 explicit: [
496 str,
497 seq,
498 map
499 ]
500});
501
502var Type$c = type;
503
504function resolveYamlNull(data) {
505 if (data === null) return true;
506
507 var max = data.length;
508
509 return (max === 1 && data === '~') ||
510 (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
511}
512
513function constructYamlNull() {
514 return null;
515}
516
517function isNull(object) {
518 return object === null;
519}
520
521var _null = new Type$c('tag:yaml.org,2002:null', {
522 kind: 'scalar',
523 resolve: resolveYamlNull,
524 construct: constructYamlNull,
525 predicate: isNull,
526 represent: {
527 canonical: function () { return '~'; },
528 lowercase: function () { return 'null'; },
529 uppercase: function () { return 'NULL'; },
530 camelcase: function () { return 'Null'; }
531 },
532 defaultStyle: 'lowercase'
533});
534
535var Type$b = type;
536
537function resolveYamlBoolean(data) {
538 if (data === null) return false;
539
540 var max = data.length;
541
542 return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
543 (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
544}
545
546function constructYamlBoolean(data) {
547 return data === 'true' ||
548 data === 'True' ||
549 data === 'TRUE';
550}
551
552function isBoolean(object) {
553 return Object.prototype.toString.call(object) === '[object Boolean]';
554}
555
556var bool = new Type$b('tag:yaml.org,2002:bool', {
557 kind: 'scalar',
558 resolve: resolveYamlBoolean,
559 construct: constructYamlBoolean,
560 predicate: isBoolean,
561 represent: {
562 lowercase: function (object) { return object ? 'true' : 'false'; },
563 uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
564 camelcase: function (object) { return object ? 'True' : 'False'; }
565 },
566 defaultStyle: 'lowercase'
567});
568
569var common$3 = common$6;
570var Type$a = type;
571
572function isHexCode(c) {
573 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
574 ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
575 ((0x61/* a */ <= c) && (c <= 0x66/* f */));
576}
577
578function isOctCode(c) {
579 return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
580}
581
582function isDecCode(c) {
583 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
584}
585
586function resolveYamlInteger(data) {
587 if (data === null) return false;
588
589 var max = data.length,
590 index = 0,
591 hasDigits = false,
592 ch;
593
594 if (!max) return false;
595
596 ch = data[index];
597
598 // sign
599 if (ch === '-' || ch === '+') {
600 ch = data[++index];
601 }
602
603 if (ch === '0') {
604 // 0
605 if (index + 1 === max) return true;
606 ch = data[++index];
607
608 // base 2, base 8, base 16
609
610 if (ch === 'b') {
611 // base 2
612 index++;
613
614 for (; index < max; index++) {
615 ch = data[index];
616 if (ch === '_') continue;
617 if (ch !== '0' && ch !== '1') return false;
618 hasDigits = true;
619 }
620 return hasDigits && ch !== '_';
621 }
622
623
624 if (ch === 'x') {
625 // base 16
626 index++;
627
628 for (; index < max; index++) {
629 ch = data[index];
630 if (ch === '_') continue;
631 if (!isHexCode(data.charCodeAt(index))) return false;
632 hasDigits = true;
633 }
634 return hasDigits && ch !== '_';
635 }
636
637 // base 8
638 for (; index < max; index++) {
639 ch = data[index];
640 if (ch === '_') continue;
641 if (!isOctCode(data.charCodeAt(index))) return false;
642 hasDigits = true;
643 }
644 return hasDigits && ch !== '_';
645 }
646
647 // base 10 (except 0) or base 60
648
649 // value should not start with `_`;
650 if (ch === '_') return false;
651
652 for (; index < max; index++) {
653 ch = data[index];
654 if (ch === '_') continue;
655 if (ch === ':') break;
656 if (!isDecCode(data.charCodeAt(index))) {
657 return false;
658 }
659 hasDigits = true;
660 }
661
662 // Should have digits and should not end with `_`
663 if (!hasDigits || ch === '_') return false;
664
665 // if !base60 - done;
666 if (ch !== ':') return true;
667
668 // base60 almost not used, no needs to optimize
669 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
670}
671
672function constructYamlInteger(data) {
673 var value = data, sign = 1, ch, base, digits = [];
674
675 if (value.indexOf('_') !== -1) {
676 value = value.replace(/_/g, '');
677 }
678
679 ch = value[0];
680
681 if (ch === '-' || ch === '+') {
682 if (ch === '-') sign = -1;
683 value = value.slice(1);
684 ch = value[0];
685 }
686
687 if (value === '0') return 0;
688
689 if (ch === '0') {
690 if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
691 if (value[1] === 'x') return sign * parseInt(value, 16);
692 return sign * parseInt(value, 8);
693 }
694
695 if (value.indexOf(':') !== -1) {
696 value.split(':').forEach(function (v) {
697 digits.unshift(parseInt(v, 10));
698 });
699
700 value = 0;
701 base = 1;
702
703 digits.forEach(function (d) {
704 value += (d * base);
705 base *= 60;
706 });
707
708 return sign * value;
709
710 }
711
712 return sign * parseInt(value, 10);
713}
714
715function isInteger(object) {
716 return (Object.prototype.toString.call(object)) === '[object Number]' &&
717 (object % 1 === 0 && !common$3.isNegativeZero(object));
718}
719
720var int = new Type$a('tag:yaml.org,2002:int', {
721 kind: 'scalar',
722 resolve: resolveYamlInteger,
723 construct: constructYamlInteger,
724 predicate: isInteger,
725 represent: {
726 binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
727 octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },
728 decimal: function (obj) { return obj.toString(10); },
729 /* eslint-disable max-len */
730 hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
731 },
732 defaultStyle: 'decimal',
733 styleAliases: {
734 binary: [ 2, 'bin' ],
735 octal: [ 8, 'oct' ],
736 decimal: [ 10, 'dec' ],
737 hexadecimal: [ 16, 'hex' ]
738 }
739});
740
741var common$2 = common$6;
742var Type$9 = type;
743
744var YAML_FLOAT_PATTERN = new RegExp(
745 // 2.5e4, 2.5 and integers
746 '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
747 // .2e4, .2
748 // special case, seems not from spec
749 '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
750 // 20:59
751 '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
752 // .inf
753 '|[-+]?\\.(?:inf|Inf|INF)' +
754 // .nan
755 '|\\.(?:nan|NaN|NAN))$');
756
757function resolveYamlFloat(data) {
758 if (data === null) return false;
759
760 if (!YAML_FLOAT_PATTERN.test(data) ||
761 // Quick hack to not allow integers end with `_`
762 // Probably should update regexp & check speed
763 data[data.length - 1] === '_') {
764 return false;
765 }
766
767 return true;
768}
769
770function constructYamlFloat(data) {
771 var value, sign, base, digits;
772
773 value = data.replace(/_/g, '').toLowerCase();
774 sign = value[0] === '-' ? -1 : 1;
775 digits = [];
776
777 if ('+-'.indexOf(value[0]) >= 0) {
778 value = value.slice(1);
779 }
780
781 if (value === '.inf') {
782 return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
783
784 } else if (value === '.nan') {
785 return NaN;
786
787 } else if (value.indexOf(':') >= 0) {
788 value.split(':').forEach(function (v) {
789 digits.unshift(parseFloat(v, 10));
790 });
791
792 value = 0.0;
793 base = 1;
794
795 digits.forEach(function (d) {
796 value += d * base;
797 base *= 60;
798 });
799
800 return sign * value;
801
802 }
803 return sign * parseFloat(value, 10);
804}
805
806
807var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
808
809function representYamlFloat(object, style) {
810 var res;
811
812 if (isNaN(object)) {
813 switch (style) {
814 case 'lowercase': return '.nan';
815 case 'uppercase': return '.NAN';
816 case 'camelcase': return '.NaN';
817 }
818 } else if (Number.POSITIVE_INFINITY === object) {
819 switch (style) {
820 case 'lowercase': return '.inf';
821 case 'uppercase': return '.INF';
822 case 'camelcase': return '.Inf';
823 }
824 } else if (Number.NEGATIVE_INFINITY === object) {
825 switch (style) {
826 case 'lowercase': return '-.inf';
827 case 'uppercase': return '-.INF';
828 case 'camelcase': return '-.Inf';
829 }
830 } else if (common$2.isNegativeZero(object)) {
831 return '-0.0';
832 }
833
834 res = object.toString(10);
835
836 // JS stringifier can build scientific format without dots: 5e-100,
837 // while YAML requres dot: 5.e-100. Fix it with simple hack
838
839 return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
840}
841
842function isFloat(object) {
843 return (Object.prototype.toString.call(object) === '[object Number]') &&
844 (object % 1 !== 0 || common$2.isNegativeZero(object));
845}
846
847var float = new Type$9('tag:yaml.org,2002:float', {
848 kind: 'scalar',
849 resolve: resolveYamlFloat,
850 construct: constructYamlFloat,
851 predicate: isFloat,
852 represent: representYamlFloat,
853 defaultStyle: 'lowercase'
854});
855
856var Schema$3 = schema;
857
858
859var json = new Schema$3({
860 include: [
861 failsafe
862 ],
863 implicit: [
864 _null,
865 bool,
866 int,
867 float
868 ]
869});
870
871var Schema$2 = schema;
872
873
874var core = new Schema$2({
875 include: [
876 json
877 ]
878});
879
880var Type$8 = type;
881
882var YAML_DATE_REGEXP = new RegExp(
883 '^([0-9][0-9][0-9][0-9])' + // [1] year
884 '-([0-9][0-9])' + // [2] month
885 '-([0-9][0-9])$'); // [3] day
886
887var YAML_TIMESTAMP_REGEXP = new RegExp(
888 '^([0-9][0-9][0-9][0-9])' + // [1] year
889 '-([0-9][0-9]?)' + // [2] month
890 '-([0-9][0-9]?)' + // [3] day
891 '(?:[Tt]|[ \\t]+)' + // ...
892 '([0-9][0-9]?)' + // [4] hour
893 ':([0-9][0-9])' + // [5] minute
894 ':([0-9][0-9])' + // [6] second
895 '(?:\\.([0-9]*))?' + // [7] fraction
896 '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
897 '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
898
899function resolveYamlTimestamp(data) {
900 if (data === null) return false;
901 if (YAML_DATE_REGEXP.exec(data) !== null) return true;
902 if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
903 return false;
904}
905
906function constructYamlTimestamp(data) {
907 var match, year, month, day, hour, minute, second, fraction = 0,
908 delta = null, tz_hour, tz_minute, date;
909
910 match = YAML_DATE_REGEXP.exec(data);
911 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
912
913 if (match === null) throw new Error('Date resolve error');
914
915 // match: [1] year [2] month [3] day
916
917 year = +(match[1]);
918 month = +(match[2]) - 1; // JS month starts with 0
919 day = +(match[3]);
920
921 if (!match[4]) { // no hour
922 return new Date(Date.UTC(year, month, day));
923 }
924
925 // match: [4] hour [5] minute [6] second [7] fraction
926
927 hour = +(match[4]);
928 minute = +(match[5]);
929 second = +(match[6]);
930
931 if (match[7]) {
932 fraction = match[7].slice(0, 3);
933 while (fraction.length < 3) { // milli-seconds
934 fraction += '0';
935 }
936 fraction = +fraction;
937 }
938
939 // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
940
941 if (match[9]) {
942 tz_hour = +(match[10]);
943 tz_minute = +(match[11] || 0);
944 delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
945 if (match[9] === '-') delta = -delta;
946 }
947
948 date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
949
950 if (delta) date.setTime(date.getTime() - delta);
951
952 return date;
953}
954
955function representYamlTimestamp(object /*, style*/) {
956 return object.toISOString();
957}
958
959var timestamp = new Type$8('tag:yaml.org,2002:timestamp', {
960 kind: 'scalar',
961 resolve: resolveYamlTimestamp,
962 construct: constructYamlTimestamp,
963 instanceOf: Date,
964 represent: representYamlTimestamp
965});
966
967var Type$7 = type;
968
969function resolveYamlMerge(data) {
970 return data === '<<' || data === null;
971}
972
973var merge = new Type$7('tag:yaml.org,2002:merge', {
974 kind: 'scalar',
975 resolve: resolveYamlMerge
976});
977
978/*eslint-disable no-bitwise*/
979
980var NodeBuffer;
981
982try {
983 // A trick for browserified version, to not include `Buffer` shim
984 var _require$1 = commonjsRequire;
985 NodeBuffer = _require$1('buffer').Buffer;
986} catch (__) {}
987
988var Type$6 = type;
989
990
991// [ 64, 65, 66 ] -> [ padding, CR, LF ]
992var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
993
994
995function resolveYamlBinary(data) {
996 if (data === null) return false;
997
998 var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
999
1000 // Convert one by one.
1001 for (idx = 0; idx < max; idx++) {
1002 code = map.indexOf(data.charAt(idx));
1003
1004 // Skip CR/LF
1005 if (code > 64) continue;
1006
1007 // Fail on illegal characters
1008 if (code < 0) return false;
1009
1010 bitlen += 6;
1011 }
1012
1013 // If there are any bits left, source was corrupted
1014 return (bitlen % 8) === 0;
1015}
1016
1017function constructYamlBinary(data) {
1018 var idx, tailbits,
1019 input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
1020 max = input.length,
1021 map = BASE64_MAP,
1022 bits = 0,
1023 result = [];
1024
1025 // Collect by 6*4 bits (3 bytes)
1026
1027 for (idx = 0; idx < max; idx++) {
1028 if ((idx % 4 === 0) && idx) {
1029 result.push((bits >> 16) & 0xFF);
1030 result.push((bits >> 8) & 0xFF);
1031 result.push(bits & 0xFF);
1032 }
1033
1034 bits = (bits << 6) | map.indexOf(input.charAt(idx));
1035 }
1036
1037 // Dump tail
1038
1039 tailbits = (max % 4) * 6;
1040
1041 if (tailbits === 0) {
1042 result.push((bits >> 16) & 0xFF);
1043 result.push((bits >> 8) & 0xFF);
1044 result.push(bits & 0xFF);
1045 } else if (tailbits === 18) {
1046 result.push((bits >> 10) & 0xFF);
1047 result.push((bits >> 2) & 0xFF);
1048 } else if (tailbits === 12) {
1049 result.push((bits >> 4) & 0xFF);
1050 }
1051
1052 // Wrap into Buffer for NodeJS and leave Array for browser
1053 if (NodeBuffer) {
1054 // Support node 6.+ Buffer API when available
1055 return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
1056 }
1057
1058 return result;
1059}
1060
1061function representYamlBinary(object /*, style*/) {
1062 var result = '', bits = 0, idx, tail,
1063 max = object.length,
1064 map = BASE64_MAP;
1065
1066 // Convert every three bytes to 4 ASCII characters.
1067
1068 for (idx = 0; idx < max; idx++) {
1069 if ((idx % 3 === 0) && idx) {
1070 result += map[(bits >> 18) & 0x3F];
1071 result += map[(bits >> 12) & 0x3F];
1072 result += map[(bits >> 6) & 0x3F];
1073 result += map[bits & 0x3F];
1074 }
1075
1076 bits = (bits << 8) + object[idx];
1077 }
1078
1079 // Dump tail
1080
1081 tail = max % 3;
1082
1083 if (tail === 0) {
1084 result += map[(bits >> 18) & 0x3F];
1085 result += map[(bits >> 12) & 0x3F];
1086 result += map[(bits >> 6) & 0x3F];
1087 result += map[bits & 0x3F];
1088 } else if (tail === 2) {
1089 result += map[(bits >> 10) & 0x3F];
1090 result += map[(bits >> 4) & 0x3F];
1091 result += map[(bits << 2) & 0x3F];
1092 result += map[64];
1093 } else if (tail === 1) {
1094 result += map[(bits >> 2) & 0x3F];
1095 result += map[(bits << 4) & 0x3F];
1096 result += map[64];
1097 result += map[64];
1098 }
1099
1100 return result;
1101}
1102
1103function isBinary$1(object) {
1104 return NodeBuffer && NodeBuffer.isBuffer(object);
1105}
1106
1107var binary = new Type$6('tag:yaml.org,2002:binary', {
1108 kind: 'scalar',
1109 resolve: resolveYamlBinary,
1110 construct: constructYamlBinary,
1111 predicate: isBinary$1,
1112 represent: representYamlBinary
1113});
1114
1115var Type$5 = type;
1116
1117var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
1118var _toString$2 = Object.prototype.toString;
1119
1120function resolveYamlOmap(data) {
1121 if (data === null) return true;
1122
1123 var objectKeys = [], index, length, pair, pairKey, pairHasKey,
1124 object = data;
1125
1126 for (index = 0, length = object.length; index < length; index += 1) {
1127 pair = object[index];
1128 pairHasKey = false;
1129
1130 if (_toString$2.call(pair) !== '[object Object]') return false;
1131
1132 for (pairKey in pair) {
1133 if (_hasOwnProperty$3.call(pair, pairKey)) {
1134 if (!pairHasKey) pairHasKey = true;
1135 else return false;
1136 }
1137 }
1138
1139 if (!pairHasKey) return false;
1140
1141 if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
1142 else return false;
1143 }
1144
1145 return true;
1146}
1147
1148function constructYamlOmap(data) {
1149 return data !== null ? data : [];
1150}
1151
1152var omap = new Type$5('tag:yaml.org,2002:omap', {
1153 kind: 'sequence',
1154 resolve: resolveYamlOmap,
1155 construct: constructYamlOmap
1156});
1157
1158var Type$4 = type;
1159
1160var _toString$1 = Object.prototype.toString;
1161
1162function resolveYamlPairs(data) {
1163 if (data === null) return true;
1164
1165 var index, length, pair, keys, result,
1166 object = data;
1167
1168 result = new Array(object.length);
1169
1170 for (index = 0, length = object.length; index < length; index += 1) {
1171 pair = object[index];
1172
1173 if (_toString$1.call(pair) !== '[object Object]') return false;
1174
1175 keys = Object.keys(pair);
1176
1177 if (keys.length !== 1) return false;
1178
1179 result[index] = [ keys[0], pair[keys[0]] ];
1180 }
1181
1182 return true;
1183}
1184
1185function constructYamlPairs(data) {
1186 if (data === null) return [];
1187
1188 var index, length, pair, keys, result,
1189 object = data;
1190
1191 result = new Array(object.length);
1192
1193 for (index = 0, length = object.length; index < length; index += 1) {
1194 pair = object[index];
1195
1196 keys = Object.keys(pair);
1197
1198 result[index] = [ keys[0], pair[keys[0]] ];
1199 }
1200
1201 return result;
1202}
1203
1204var pairs = new Type$4('tag:yaml.org,2002:pairs', {
1205 kind: 'sequence',
1206 resolve: resolveYamlPairs,
1207 construct: constructYamlPairs
1208});
1209
1210var Type$3 = type;
1211
1212var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
1213
1214function resolveYamlSet(data) {
1215 if (data === null) return true;
1216
1217 var key, object = data;
1218
1219 for (key in object) {
1220 if (_hasOwnProperty$2.call(object, key)) {
1221 if (object[key] !== null) return false;
1222 }
1223 }
1224
1225 return true;
1226}
1227
1228function constructYamlSet(data) {
1229 return data !== null ? data : {};
1230}
1231
1232var set = new Type$3('tag:yaml.org,2002:set', {
1233 kind: 'mapping',
1234 resolve: resolveYamlSet,
1235 construct: constructYamlSet
1236});
1237
1238var Schema$1 = schema;
1239
1240
1241var default_safe = new Schema$1({
1242 include: [
1243 core
1244 ],
1245 implicit: [
1246 timestamp,
1247 merge
1248 ],
1249 explicit: [
1250 binary,
1251 omap,
1252 pairs,
1253 set
1254 ]
1255});
1256
1257var Type$2 = type;
1258
1259function resolveJavascriptUndefined() {
1260 return true;
1261}
1262
1263function constructJavascriptUndefined() {
1264 /*eslint-disable no-undefined*/
1265 return undefined;
1266}
1267
1268function representJavascriptUndefined() {
1269 return '';
1270}
1271
1272function isUndefined(object) {
1273 return typeof object === 'undefined';
1274}
1275
1276var _undefined = new Type$2('tag:yaml.org,2002:js/undefined', {
1277 kind: 'scalar',
1278 resolve: resolveJavascriptUndefined,
1279 construct: constructJavascriptUndefined,
1280 predicate: isUndefined,
1281 represent: representJavascriptUndefined
1282});
1283
1284var Type$1 = type;
1285
1286function resolveJavascriptRegExp(data) {
1287 if (data === null) return false;
1288 if (data.length === 0) return false;
1289
1290 var regexp = data,
1291 tail = /\/([gim]*)$/.exec(data),
1292 modifiers = '';
1293
1294 // if regexp starts with '/' it can have modifiers and must be properly closed
1295 // `/foo/gim` - modifiers tail can be maximum 3 chars
1296 if (regexp[0] === '/') {
1297 if (tail) modifiers = tail[1];
1298
1299 if (modifiers.length > 3) return false;
1300 // if expression starts with /, is should be properly terminated
1301 if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
1302 }
1303
1304 return true;
1305}
1306
1307function constructJavascriptRegExp(data) {
1308 var regexp = data,
1309 tail = /\/([gim]*)$/.exec(data),
1310 modifiers = '';
1311
1312 // `/foo/gim` - tail can be maximum 4 chars
1313 if (regexp[0] === '/') {
1314 if (tail) modifiers = tail[1];
1315 regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
1316 }
1317
1318 return new RegExp(regexp, modifiers);
1319}
1320
1321function representJavascriptRegExp(object /*, style*/) {
1322 var result = '/' + object.source + '/';
1323
1324 if (object.global) result += 'g';
1325 if (object.multiline) result += 'm';
1326 if (object.ignoreCase) result += 'i';
1327
1328 return result;
1329}
1330
1331function isRegExp(object) {
1332 return Object.prototype.toString.call(object) === '[object RegExp]';
1333}
1334
1335var regexp = new Type$1('tag:yaml.org,2002:js/regexp', {
1336 kind: 'scalar',
1337 resolve: resolveJavascriptRegExp,
1338 construct: constructJavascriptRegExp,
1339 predicate: isRegExp,
1340 represent: representJavascriptRegExp
1341});
1342
1343var esprima;
1344
1345// Browserified version does not have esprima
1346//
1347// 1. For node.js just require module as deps
1348// 2. For browser try to require mudule via external AMD system.
1349// If not found - try to fallback to window.esprima. If not
1350// found too - then fail to parse.
1351//
1352try {
1353 // workaround to exclude package from browserify list.
1354 var _require = commonjsRequire;
1355 esprima = _require('esprima');
1356} catch (_) {
1357 /* eslint-disable no-redeclare */
1358 /* global window */
1359 if (typeof window !== 'undefined') esprima = window.esprima;
1360}
1361
1362var Type = type;
1363
1364function resolveJavascriptFunction(data) {
1365 if (data === null) return false;
1366
1367 try {
1368 var source = '(' + data + ')',
1369 ast = esprima.parse(source, { range: true });
1370
1371 if (ast.type !== 'Program' ||
1372 ast.body.length !== 1 ||
1373 ast.body[0].type !== 'ExpressionStatement' ||
1374 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
1375 ast.body[0].expression.type !== 'FunctionExpression')) {
1376 return false;
1377 }
1378
1379 return true;
1380 } catch (err) {
1381 return false;
1382 }
1383}
1384
1385function constructJavascriptFunction(data) {
1386 /*jslint evil:true*/
1387
1388 var source = '(' + data + ')',
1389 ast = esprima.parse(source, { range: true }),
1390 params = [],
1391 body;
1392
1393 if (ast.type !== 'Program' ||
1394 ast.body.length !== 1 ||
1395 ast.body[0].type !== 'ExpressionStatement' ||
1396 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
1397 ast.body[0].expression.type !== 'FunctionExpression')) {
1398 throw new Error('Failed to resolve function');
1399 }
1400
1401 ast.body[0].expression.params.forEach(function (param) {
1402 params.push(param.name);
1403 });
1404
1405 body = ast.body[0].expression.body.range;
1406
1407 // Esprima's ranges include the first '{' and the last '}' characters on
1408 // function expressions. So cut them out.
1409 if (ast.body[0].expression.body.type === 'BlockStatement') {
1410 /*eslint-disable no-new-func*/
1411 return new Function(params, source.slice(body[0] + 1, body[1] - 1));
1412 }
1413 // ES6 arrow functions can omit the BlockStatement. In that case, just return
1414 // the body.
1415 /*eslint-disable no-new-func*/
1416 return new Function(params, 'return ' + source.slice(body[0], body[1]));
1417}
1418
1419function representJavascriptFunction(object /*, style*/) {
1420 return object.toString();
1421}
1422
1423function isFunction$1(object) {
1424 return Object.prototype.toString.call(object) === '[object Function]';
1425}
1426
1427var _function = new Type('tag:yaml.org,2002:js/function', {
1428 kind: 'scalar',
1429 resolve: resolveJavascriptFunction,
1430 construct: constructJavascriptFunction,
1431 predicate: isFunction$1,
1432 represent: representJavascriptFunction
1433});
1434
1435var Schema = schema;
1436
1437
1438var default_full = Schema.DEFAULT = new Schema({
1439 include: [
1440 default_safe
1441 ],
1442 explicit: [
1443 _undefined,
1444 regexp,
1445 _function
1446 ]
1447});
1448
1449/*eslint-disable max-len,no-use-before-define*/
1450
1451var common$1 = common$6;
1452var YAMLException$1 = exception;
1453var Mark = mark;
1454var DEFAULT_SAFE_SCHEMA$1 = default_safe;
1455var DEFAULT_FULL_SCHEMA$1 = default_full;
1456
1457
1458var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
1459
1460
1461var CONTEXT_FLOW_IN = 1;
1462var CONTEXT_FLOW_OUT = 2;
1463var CONTEXT_BLOCK_IN = 3;
1464var CONTEXT_BLOCK_OUT = 4;
1465
1466
1467var CHOMPING_CLIP = 1;
1468var CHOMPING_STRIP = 2;
1469var CHOMPING_KEEP = 3;
1470
1471
1472var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1473var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
1474var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
1475var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
1476var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
1477
1478
1479function _class(obj) { return Object.prototype.toString.call(obj); }
1480
1481function is_EOL(c) {
1482 return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
1483}
1484
1485function is_WHITE_SPACE(c) {
1486 return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
1487}
1488
1489function is_WS_OR_EOL(c) {
1490 return (c === 0x09/* Tab */) ||
1491 (c === 0x20/* Space */) ||
1492 (c === 0x0A/* LF */) ||
1493 (c === 0x0D/* CR */);
1494}
1495
1496function is_FLOW_INDICATOR(c) {
1497 return c === 0x2C/* , */ ||
1498 c === 0x5B/* [ */ ||
1499 c === 0x5D/* ] */ ||
1500 c === 0x7B/* { */ ||
1501 c === 0x7D/* } */;
1502}
1503
1504function fromHexCode(c) {
1505 var lc;
1506
1507 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
1508 return c - 0x30;
1509 }
1510
1511 /*eslint-disable no-bitwise*/
1512 lc = c | 0x20;
1513
1514 if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
1515 return lc - 0x61 + 10;
1516 }
1517
1518 return -1;
1519}
1520
1521function escapedHexLen(c) {
1522 if (c === 0x78/* x */) { return 2; }
1523 if (c === 0x75/* u */) { return 4; }
1524 if (c === 0x55/* U */) { return 8; }
1525 return 0;
1526}
1527
1528function fromDecimalCode(c) {
1529 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
1530 return c - 0x30;
1531 }
1532
1533 return -1;
1534}
1535
1536function simpleEscapeSequence(c) {
1537 /* eslint-disable indent */
1538 return (c === 0x30/* 0 */) ? '\x00' :
1539 (c === 0x61/* a */) ? '\x07' :
1540 (c === 0x62/* b */) ? '\x08' :
1541 (c === 0x74/* t */) ? '\x09' :
1542 (c === 0x09/* Tab */) ? '\x09' :
1543 (c === 0x6E/* n */) ? '\x0A' :
1544 (c === 0x76/* v */) ? '\x0B' :
1545 (c === 0x66/* f */) ? '\x0C' :
1546 (c === 0x72/* r */) ? '\x0D' :
1547 (c === 0x65/* e */) ? '\x1B' :
1548 (c === 0x20/* Space */) ? ' ' :
1549 (c === 0x22/* " */) ? '\x22' :
1550 (c === 0x2F/* / */) ? '/' :
1551 (c === 0x5C/* \ */) ? '\x5C' :
1552 (c === 0x4E/* N */) ? '\x85' :
1553 (c === 0x5F/* _ */) ? '\xA0' :
1554 (c === 0x4C/* L */) ? '\u2028' :
1555 (c === 0x50/* P */) ? '\u2029' : '';
1556}
1557
1558function charFromCodepoint(c) {
1559 if (c <= 0xFFFF) {
1560 return String.fromCharCode(c);
1561 }
1562 // Encode UTF-16 surrogate pair
1563 // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
1564 return String.fromCharCode(
1565 ((c - 0x010000) >> 10) + 0xD800,
1566 ((c - 0x010000) & 0x03FF) + 0xDC00
1567 );
1568}
1569
1570var simpleEscapeCheck = new Array(256); // integer, for fast access
1571var simpleEscapeMap = new Array(256);
1572for (var i = 0; i < 256; i++) {
1573 simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1574 simpleEscapeMap[i] = simpleEscapeSequence(i);
1575}
1576
1577
1578function State$1(input, options) {
1579 this.input = input;
1580
1581 this.filename = options['filename'] || null;
1582 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA$1;
1583 this.onWarning = options['onWarning'] || null;
1584 this.legacy = options['legacy'] || false;
1585 this.json = options['json'] || false;
1586 this.listener = options['listener'] || null;
1587
1588 this.implicitTypes = this.schema.compiledImplicit;
1589 this.typeMap = this.schema.compiledTypeMap;
1590
1591 this.length = input.length;
1592 this.position = 0;
1593 this.line = 0;
1594 this.lineStart = 0;
1595 this.lineIndent = 0;
1596
1597 this.documents = [];
1598
1599 /*
1600 this.version;
1601 this.checkLineBreaks;
1602 this.tagMap;
1603 this.anchorMap;
1604 this.tag;
1605 this.anchor;
1606 this.kind;
1607 this.result;*/
1608
1609}
1610
1611
1612function generateError(state, message) {
1613 return new YAMLException$1(
1614 message,
1615 new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
1616}
1617
1618function throwError(state, message) {
1619 throw generateError(state, message);
1620}
1621
1622function throwWarning(state, message) {
1623 if (state.onWarning) {
1624 state.onWarning.call(null, generateError(state, message));
1625 }
1626}
1627
1628
1629var directiveHandlers = {
1630
1631 YAML: function handleYamlDirective(state, name, args) {
1632
1633 var match, major, minor;
1634
1635 if (state.version !== null) {
1636 throwError(state, 'duplication of %YAML directive');
1637 }
1638
1639 if (args.length !== 1) {
1640 throwError(state, 'YAML directive accepts exactly one argument');
1641 }
1642
1643 match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
1644
1645 if (match === null) {
1646 throwError(state, 'ill-formed argument of the YAML directive');
1647 }
1648
1649 major = parseInt(match[1], 10);
1650 minor = parseInt(match[2], 10);
1651
1652 if (major !== 1) {
1653 throwError(state, 'unacceptable YAML version of the document');
1654 }
1655
1656 state.version = args[0];
1657 state.checkLineBreaks = (minor < 2);
1658
1659 if (minor !== 1 && minor !== 2) {
1660 throwWarning(state, 'unsupported YAML version of the document');
1661 }
1662 },
1663
1664 TAG: function handleTagDirective(state, name, args) {
1665
1666 var handle, prefix;
1667
1668 if (args.length !== 2) {
1669 throwError(state, 'TAG directive accepts exactly two arguments');
1670 }
1671
1672 handle = args[0];
1673 prefix = args[1];
1674
1675 if (!PATTERN_TAG_HANDLE.test(handle)) {
1676 throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
1677 }
1678
1679 if (_hasOwnProperty$1.call(state.tagMap, handle)) {
1680 throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
1681 }
1682
1683 if (!PATTERN_TAG_URI.test(prefix)) {
1684 throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
1685 }
1686
1687 state.tagMap[handle] = prefix;
1688 }
1689};
1690
1691
1692function captureSegment(state, start, end, checkJson) {
1693 var _position, _length, _character, _result;
1694
1695 if (start < end) {
1696 _result = state.input.slice(start, end);
1697
1698 if (checkJson) {
1699 for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
1700 _character = _result.charCodeAt(_position);
1701 if (!(_character === 0x09 ||
1702 (0x20 <= _character && _character <= 0x10FFFF))) {
1703 throwError(state, 'expected valid JSON character');
1704 }
1705 }
1706 } else if (PATTERN_NON_PRINTABLE.test(_result)) {
1707 throwError(state, 'the stream contains non-printable characters');
1708 }
1709
1710 state.result += _result;
1711 }
1712}
1713
1714function mergeMappings(state, destination, source, overridableKeys) {
1715 var sourceKeys, key, index, quantity;
1716
1717 if (!common$1.isObject(source)) {
1718 throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
1719 }
1720
1721 sourceKeys = Object.keys(source);
1722
1723 for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
1724 key = sourceKeys[index];
1725
1726 if (!_hasOwnProperty$1.call(destination, key)) {
1727 destination[key] = source[key];
1728 overridableKeys[key] = true;
1729 }
1730 }
1731}
1732
1733function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
1734 var index, quantity;
1735
1736 // The output is a plain object here, so keys can only be strings.
1737 // We need to convert keyNode to a string, but doing so can hang the process
1738 // (deeply nested arrays that explode exponentially using aliases).
1739 if (Array.isArray(keyNode)) {
1740 keyNode = Array.prototype.slice.call(keyNode);
1741
1742 for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
1743 if (Array.isArray(keyNode[index])) {
1744 throwError(state, 'nested arrays are not supported inside keys');
1745 }
1746
1747 if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
1748 keyNode[index] = '[object Object]';
1749 }
1750 }
1751 }
1752
1753 // Avoid code execution in load() via toString property
1754 // (still use its own toString for arrays, timestamps,
1755 // and whatever user schema extensions happen to have @@toStringTag)
1756 if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
1757 keyNode = '[object Object]';
1758 }
1759
1760
1761 keyNode = String(keyNode);
1762
1763 if (_result === null) {
1764 _result = {};
1765 }
1766
1767 if (keyTag === 'tag:yaml.org,2002:merge') {
1768 if (Array.isArray(valueNode)) {
1769 for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
1770 mergeMappings(state, _result, valueNode[index], overridableKeys);
1771 }
1772 } else {
1773 mergeMappings(state, _result, valueNode, overridableKeys);
1774 }
1775 } else {
1776 if (!state.json &&
1777 !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
1778 _hasOwnProperty$1.call(_result, keyNode)) {
1779 state.line = startLine || state.line;
1780 state.position = startPos || state.position;
1781 throwError(state, 'duplicated mapping key');
1782 }
1783 _result[keyNode] = valueNode;
1784 delete overridableKeys[keyNode];
1785 }
1786
1787 return _result;
1788}
1789
1790function readLineBreak(state) {
1791 var ch;
1792
1793 ch = state.input.charCodeAt(state.position);
1794
1795 if (ch === 0x0A/* LF */) {
1796 state.position++;
1797 } else if (ch === 0x0D/* CR */) {
1798 state.position++;
1799 if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
1800 state.position++;
1801 }
1802 } else {
1803 throwError(state, 'a line break is expected');
1804 }
1805
1806 state.line += 1;
1807 state.lineStart = state.position;
1808}
1809
1810function skipSeparationSpace(state, allowComments, checkIndent) {
1811 var lineBreaks = 0,
1812 ch = state.input.charCodeAt(state.position);
1813
1814 while (ch !== 0) {
1815 while (is_WHITE_SPACE(ch)) {
1816 ch = state.input.charCodeAt(++state.position);
1817 }
1818
1819 if (allowComments && ch === 0x23/* # */) {
1820 do {
1821 ch = state.input.charCodeAt(++state.position);
1822 } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
1823 }
1824
1825 if (is_EOL(ch)) {
1826 readLineBreak(state);
1827
1828 ch = state.input.charCodeAt(state.position);
1829 lineBreaks++;
1830 state.lineIndent = 0;
1831
1832 while (ch === 0x20/* Space */) {
1833 state.lineIndent++;
1834 ch = state.input.charCodeAt(++state.position);
1835 }
1836 } else {
1837 break;
1838 }
1839 }
1840
1841 if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
1842 throwWarning(state, 'deficient indentation');
1843 }
1844
1845 return lineBreaks;
1846}
1847
1848function testDocumentSeparator(state) {
1849 var _position = state.position,
1850 ch;
1851
1852 ch = state.input.charCodeAt(_position);
1853
1854 // Condition state.position === state.lineStart is tested
1855 // in parent on each call, for efficiency. No needs to test here again.
1856 if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
1857 ch === state.input.charCodeAt(_position + 1) &&
1858 ch === state.input.charCodeAt(_position + 2)) {
1859
1860 _position += 3;
1861
1862 ch = state.input.charCodeAt(_position);
1863
1864 if (ch === 0 || is_WS_OR_EOL(ch)) {
1865 return true;
1866 }
1867 }
1868
1869 return false;
1870}
1871
1872function writeFoldedLines(state, count) {
1873 if (count === 1) {
1874 state.result += ' ';
1875 } else if (count > 1) {
1876 state.result += common$1.repeat('\n', count - 1);
1877 }
1878}
1879
1880
1881function readPlainScalar(state, nodeIndent, withinFlowCollection) {
1882 var preceding,
1883 following,
1884 captureStart,
1885 captureEnd,
1886 hasPendingContent,
1887 _line,
1888 _lineStart,
1889 _lineIndent,
1890 _kind = state.kind,
1891 _result = state.result,
1892 ch;
1893
1894 ch = state.input.charCodeAt(state.position);
1895
1896 if (is_WS_OR_EOL(ch) ||
1897 is_FLOW_INDICATOR(ch) ||
1898 ch === 0x23/* # */ ||
1899 ch === 0x26/* & */ ||
1900 ch === 0x2A/* * */ ||
1901 ch === 0x21/* ! */ ||
1902 ch === 0x7C/* | */ ||
1903 ch === 0x3E/* > */ ||
1904 ch === 0x27/* ' */ ||
1905 ch === 0x22/* " */ ||
1906 ch === 0x25/* % */ ||
1907 ch === 0x40/* @ */ ||
1908 ch === 0x60/* ` */) {
1909 return false;
1910 }
1911
1912 if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
1913 following = state.input.charCodeAt(state.position + 1);
1914
1915 if (is_WS_OR_EOL(following) ||
1916 withinFlowCollection && is_FLOW_INDICATOR(following)) {
1917 return false;
1918 }
1919 }
1920
1921 state.kind = 'scalar';
1922 state.result = '';
1923 captureStart = captureEnd = state.position;
1924 hasPendingContent = false;
1925
1926 while (ch !== 0) {
1927 if (ch === 0x3A/* : */) {
1928 following = state.input.charCodeAt(state.position + 1);
1929
1930 if (is_WS_OR_EOL(following) ||
1931 withinFlowCollection && is_FLOW_INDICATOR(following)) {
1932 break;
1933 }
1934
1935 } else if (ch === 0x23/* # */) {
1936 preceding = state.input.charCodeAt(state.position - 1);
1937
1938 if (is_WS_OR_EOL(preceding)) {
1939 break;
1940 }
1941
1942 } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
1943 withinFlowCollection && is_FLOW_INDICATOR(ch)) {
1944 break;
1945
1946 } else if (is_EOL(ch)) {
1947 _line = state.line;
1948 _lineStart = state.lineStart;
1949 _lineIndent = state.lineIndent;
1950 skipSeparationSpace(state, false, -1);
1951
1952 if (state.lineIndent >= nodeIndent) {
1953 hasPendingContent = true;
1954 ch = state.input.charCodeAt(state.position);
1955 continue;
1956 } else {
1957 state.position = captureEnd;
1958 state.line = _line;
1959 state.lineStart = _lineStart;
1960 state.lineIndent = _lineIndent;
1961 break;
1962 }
1963 }
1964
1965 if (hasPendingContent) {
1966 captureSegment(state, captureStart, captureEnd, false);
1967 writeFoldedLines(state, state.line - _line);
1968 captureStart = captureEnd = state.position;
1969 hasPendingContent = false;
1970 }
1971
1972 if (!is_WHITE_SPACE(ch)) {
1973 captureEnd = state.position + 1;
1974 }
1975
1976 ch = state.input.charCodeAt(++state.position);
1977 }
1978
1979 captureSegment(state, captureStart, captureEnd, false);
1980
1981 if (state.result) {
1982 return true;
1983 }
1984
1985 state.kind = _kind;
1986 state.result = _result;
1987 return false;
1988}
1989
1990function readSingleQuotedScalar(state, nodeIndent) {
1991 var ch,
1992 captureStart, captureEnd;
1993
1994 ch = state.input.charCodeAt(state.position);
1995
1996 if (ch !== 0x27/* ' */) {
1997 return false;
1998 }
1999
2000 state.kind = 'scalar';
2001 state.result = '';
2002 state.position++;
2003 captureStart = captureEnd = state.position;
2004
2005 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2006 if (ch === 0x27/* ' */) {
2007 captureSegment(state, captureStart, state.position, true);
2008 ch = state.input.charCodeAt(++state.position);
2009
2010 if (ch === 0x27/* ' */) {
2011 captureStart = state.position;
2012 state.position++;
2013 captureEnd = state.position;
2014 } else {
2015 return true;
2016 }
2017
2018 } else if (is_EOL(ch)) {
2019 captureSegment(state, captureStart, captureEnd, true);
2020 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
2021 captureStart = captureEnd = state.position;
2022
2023 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
2024 throwError(state, 'unexpected end of the document within a single quoted scalar');
2025
2026 } else {
2027 state.position++;
2028 captureEnd = state.position;
2029 }
2030 }
2031
2032 throwError(state, 'unexpected end of the stream within a single quoted scalar');
2033}
2034
2035function readDoubleQuotedScalar(state, nodeIndent) {
2036 var captureStart,
2037 captureEnd,
2038 hexLength,
2039 hexResult,
2040 tmp,
2041 ch;
2042
2043 ch = state.input.charCodeAt(state.position);
2044
2045 if (ch !== 0x22/* " */) {
2046 return false;
2047 }
2048
2049 state.kind = 'scalar';
2050 state.result = '';
2051 state.position++;
2052 captureStart = captureEnd = state.position;
2053
2054 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2055 if (ch === 0x22/* " */) {
2056 captureSegment(state, captureStart, state.position, true);
2057 state.position++;
2058 return true;
2059
2060 } else if (ch === 0x5C/* \ */) {
2061 captureSegment(state, captureStart, state.position, true);
2062 ch = state.input.charCodeAt(++state.position);
2063
2064 if (is_EOL(ch)) {
2065 skipSeparationSpace(state, false, nodeIndent);
2066
2067 // TODO: rework to inline fn with no type cast?
2068 } else if (ch < 256 && simpleEscapeCheck[ch]) {
2069 state.result += simpleEscapeMap[ch];
2070 state.position++;
2071
2072 } else if ((tmp = escapedHexLen(ch)) > 0) {
2073 hexLength = tmp;
2074 hexResult = 0;
2075
2076 for (; hexLength > 0; hexLength--) {
2077 ch = state.input.charCodeAt(++state.position);
2078
2079 if ((tmp = fromHexCode(ch)) >= 0) {
2080 hexResult = (hexResult << 4) + tmp;
2081
2082 } else {
2083 throwError(state, 'expected hexadecimal character');
2084 }
2085 }
2086
2087 state.result += charFromCodepoint(hexResult);
2088
2089 state.position++;
2090
2091 } else {
2092 throwError(state, 'unknown escape sequence');
2093 }
2094
2095 captureStart = captureEnd = state.position;
2096
2097 } else if (is_EOL(ch)) {
2098 captureSegment(state, captureStart, captureEnd, true);
2099 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
2100 captureStart = captureEnd = state.position;
2101
2102 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
2103 throwError(state, 'unexpected end of the document within a double quoted scalar');
2104
2105 } else {
2106 state.position++;
2107 captureEnd = state.position;
2108 }
2109 }
2110
2111 throwError(state, 'unexpected end of the stream within a double quoted scalar');
2112}
2113
2114function readFlowCollection(state, nodeIndent) {
2115 var readNext = true,
2116 _line,
2117 _tag = state.tag,
2118 _result,
2119 _anchor = state.anchor,
2120 following,
2121 terminator,
2122 isPair,
2123 isExplicitPair,
2124 isMapping,
2125 overridableKeys = {},
2126 keyNode,
2127 keyTag,
2128 valueNode,
2129 ch;
2130
2131 ch = state.input.charCodeAt(state.position);
2132
2133 if (ch === 0x5B/* [ */) {
2134 terminator = 0x5D;/* ] */
2135 isMapping = false;
2136 _result = [];
2137 } else if (ch === 0x7B/* { */) {
2138 terminator = 0x7D;/* } */
2139 isMapping = true;
2140 _result = {};
2141 } else {
2142 return false;
2143 }
2144
2145 if (state.anchor !== null) {
2146 state.anchorMap[state.anchor] = _result;
2147 }
2148
2149 ch = state.input.charCodeAt(++state.position);
2150
2151 while (ch !== 0) {
2152 skipSeparationSpace(state, true, nodeIndent);
2153
2154 ch = state.input.charCodeAt(state.position);
2155
2156 if (ch === terminator) {
2157 state.position++;
2158 state.tag = _tag;
2159 state.anchor = _anchor;
2160 state.kind = isMapping ? 'mapping' : 'sequence';
2161 state.result = _result;
2162 return true;
2163 } else if (!readNext) {
2164 throwError(state, 'missed comma between flow collection entries');
2165 }
2166
2167 keyTag = keyNode = valueNode = null;
2168 isPair = isExplicitPair = false;
2169
2170 if (ch === 0x3F/* ? */) {
2171 following = state.input.charCodeAt(state.position + 1);
2172
2173 if (is_WS_OR_EOL(following)) {
2174 isPair = isExplicitPair = true;
2175 state.position++;
2176 skipSeparationSpace(state, true, nodeIndent);
2177 }
2178 }
2179
2180 _line = state.line;
2181 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2182 keyTag = state.tag;
2183 keyNode = state.result;
2184 skipSeparationSpace(state, true, nodeIndent);
2185
2186 ch = state.input.charCodeAt(state.position);
2187
2188 if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
2189 isPair = true;
2190 ch = state.input.charCodeAt(++state.position);
2191 skipSeparationSpace(state, true, nodeIndent);
2192 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2193 valueNode = state.result;
2194 }
2195
2196 if (isMapping) {
2197 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
2198 } else if (isPair) {
2199 _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
2200 } else {
2201 _result.push(keyNode);
2202 }
2203
2204 skipSeparationSpace(state, true, nodeIndent);
2205
2206 ch = state.input.charCodeAt(state.position);
2207
2208 if (ch === 0x2C/* , */) {
2209 readNext = true;
2210 ch = state.input.charCodeAt(++state.position);
2211 } else {
2212 readNext = false;
2213 }
2214 }
2215
2216 throwError(state, 'unexpected end of the stream within a flow collection');
2217}
2218
2219function readBlockScalar(state, nodeIndent) {
2220 var captureStart,
2221 folding,
2222 chomping = CHOMPING_CLIP,
2223 didReadContent = false,
2224 detectedIndent = false,
2225 textIndent = nodeIndent,
2226 emptyLines = 0,
2227 atMoreIndented = false,
2228 tmp,
2229 ch;
2230
2231 ch = state.input.charCodeAt(state.position);
2232
2233 if (ch === 0x7C/* | */) {
2234 folding = false;
2235 } else if (ch === 0x3E/* > */) {
2236 folding = true;
2237 } else {
2238 return false;
2239 }
2240
2241 state.kind = 'scalar';
2242 state.result = '';
2243
2244 while (ch !== 0) {
2245 ch = state.input.charCodeAt(++state.position);
2246
2247 if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
2248 if (CHOMPING_CLIP === chomping) {
2249 chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
2250 } else {
2251 throwError(state, 'repeat of a chomping mode identifier');
2252 }
2253
2254 } else if ((tmp = fromDecimalCode(ch)) >= 0) {
2255 if (tmp === 0) {
2256 throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
2257 } else if (!detectedIndent) {
2258 textIndent = nodeIndent + tmp - 1;
2259 detectedIndent = true;
2260 } else {
2261 throwError(state, 'repeat of an indentation width identifier');
2262 }
2263
2264 } else {
2265 break;
2266 }
2267 }
2268
2269 if (is_WHITE_SPACE(ch)) {
2270 do { ch = state.input.charCodeAt(++state.position); }
2271 while (is_WHITE_SPACE(ch));
2272
2273 if (ch === 0x23/* # */) {
2274 do { ch = state.input.charCodeAt(++state.position); }
2275 while (!is_EOL(ch) && (ch !== 0));
2276 }
2277 }
2278
2279 while (ch !== 0) {
2280 readLineBreak(state);
2281 state.lineIndent = 0;
2282
2283 ch = state.input.charCodeAt(state.position);
2284
2285 while ((!detectedIndent || state.lineIndent < textIndent) &&
2286 (ch === 0x20/* Space */)) {
2287 state.lineIndent++;
2288 ch = state.input.charCodeAt(++state.position);
2289 }
2290
2291 if (!detectedIndent && state.lineIndent > textIndent) {
2292 textIndent = state.lineIndent;
2293 }
2294
2295 if (is_EOL(ch)) {
2296 emptyLines++;
2297 continue;
2298 }
2299
2300 // End of the scalar.
2301 if (state.lineIndent < textIndent) {
2302
2303 // Perform the chomping.
2304 if (chomping === CHOMPING_KEEP) {
2305 state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2306 } else if (chomping === CHOMPING_CLIP) {
2307 if (didReadContent) { // i.e. only if the scalar is not empty.
2308 state.result += '\n';
2309 }
2310 }
2311
2312 // Break this `while` cycle and go to the funciton's epilogue.
2313 break;
2314 }
2315
2316 // Folded style: use fancy rules to handle line breaks.
2317 if (folding) {
2318
2319 // Lines starting with white space characters (more-indented lines) are not folded.
2320 if (is_WHITE_SPACE(ch)) {
2321 atMoreIndented = true;
2322 // except for the first content line (cf. Example 8.1)
2323 state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2324
2325 // End of more-indented block.
2326 } else if (atMoreIndented) {
2327 atMoreIndented = false;
2328 state.result += common$1.repeat('\n', emptyLines + 1);
2329
2330 // Just one line break - perceive as the same line.
2331 } else if (emptyLines === 0) {
2332 if (didReadContent) { // i.e. only if we have already read some scalar content.
2333 state.result += ' ';
2334 }
2335
2336 // Several line breaks - perceive as different lines.
2337 } else {
2338 state.result += common$1.repeat('\n', emptyLines);
2339 }
2340
2341 // Literal style: just add exact number of line breaks between content lines.
2342 } else {
2343 // Keep all line breaks except the header line break.
2344 state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2345 }
2346
2347 didReadContent = true;
2348 detectedIndent = true;
2349 emptyLines = 0;
2350 captureStart = state.position;
2351
2352 while (!is_EOL(ch) && (ch !== 0)) {
2353 ch = state.input.charCodeAt(++state.position);
2354 }
2355
2356 captureSegment(state, captureStart, state.position, false);
2357 }
2358
2359 return true;
2360}
2361
2362function readBlockSequence(state, nodeIndent) {
2363 var _line,
2364 _tag = state.tag,
2365 _anchor = state.anchor,
2366 _result = [],
2367 following,
2368 detected = false,
2369 ch;
2370
2371 if (state.anchor !== null) {
2372 state.anchorMap[state.anchor] = _result;
2373 }
2374
2375 ch = state.input.charCodeAt(state.position);
2376
2377 while (ch !== 0) {
2378
2379 if (ch !== 0x2D/* - */) {
2380 break;
2381 }
2382
2383 following = state.input.charCodeAt(state.position + 1);
2384
2385 if (!is_WS_OR_EOL(following)) {
2386 break;
2387 }
2388
2389 detected = true;
2390 state.position++;
2391
2392 if (skipSeparationSpace(state, true, -1)) {
2393 if (state.lineIndent <= nodeIndent) {
2394 _result.push(null);
2395 ch = state.input.charCodeAt(state.position);
2396 continue;
2397 }
2398 }
2399
2400 _line = state.line;
2401 composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
2402 _result.push(state.result);
2403 skipSeparationSpace(state, true, -1);
2404
2405 ch = state.input.charCodeAt(state.position);
2406
2407 if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
2408 throwError(state, 'bad indentation of a sequence entry');
2409 } else if (state.lineIndent < nodeIndent) {
2410 break;
2411 }
2412 }
2413
2414 if (detected) {
2415 state.tag = _tag;
2416 state.anchor = _anchor;
2417 state.kind = 'sequence';
2418 state.result = _result;
2419 return true;
2420 }
2421 return false;
2422}
2423
2424function readBlockMapping(state, nodeIndent, flowIndent) {
2425 var following,
2426 allowCompact,
2427 _line,
2428 _pos,
2429 _tag = state.tag,
2430 _anchor = state.anchor,
2431 _result = {},
2432 overridableKeys = {},
2433 keyTag = null,
2434 keyNode = null,
2435 valueNode = null,
2436 atExplicitKey = false,
2437 detected = false,
2438 ch;
2439
2440 if (state.anchor !== null) {
2441 state.anchorMap[state.anchor] = _result;
2442 }
2443
2444 ch = state.input.charCodeAt(state.position);
2445
2446 while (ch !== 0) {
2447 following = state.input.charCodeAt(state.position + 1);
2448 _line = state.line; // Save the current line.
2449 _pos = state.position;
2450
2451 //
2452 // Explicit notation case. There are two separate blocks:
2453 // first for the key (denoted by "?") and second for the value (denoted by ":")
2454 //
2455 if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
2456
2457 if (ch === 0x3F/* ? */) {
2458 if (atExplicitKey) {
2459 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2460 keyTag = keyNode = valueNode = null;
2461 }
2462
2463 detected = true;
2464 atExplicitKey = true;
2465 allowCompact = true;
2466
2467 } else if (atExplicitKey) {
2468 // i.e. 0x3A/* : */ === character after the explicit key.
2469 atExplicitKey = false;
2470 allowCompact = true;
2471
2472 } else {
2473 throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
2474 }
2475
2476 state.position += 1;
2477 ch = following;
2478
2479 //
2480 // Implicit notation case. Flow-style node as the key first, then ":", and the value.
2481 //
2482 } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
2483
2484 if (state.line === _line) {
2485 ch = state.input.charCodeAt(state.position);
2486
2487 while (is_WHITE_SPACE(ch)) {
2488 ch = state.input.charCodeAt(++state.position);
2489 }
2490
2491 if (ch === 0x3A/* : */) {
2492 ch = state.input.charCodeAt(++state.position);
2493
2494 if (!is_WS_OR_EOL(ch)) {
2495 throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
2496 }
2497
2498 if (atExplicitKey) {
2499 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2500 keyTag = keyNode = valueNode = null;
2501 }
2502
2503 detected = true;
2504 atExplicitKey = false;
2505 allowCompact = false;
2506 keyTag = state.tag;
2507 keyNode = state.result;
2508
2509 } else if (detected) {
2510 throwError(state, 'can not read an implicit mapping pair; a colon is missed');
2511
2512 } else {
2513 state.tag = _tag;
2514 state.anchor = _anchor;
2515 return true; // Keep the result of `composeNode`.
2516 }
2517
2518 } else if (detected) {
2519 throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
2520
2521 } else {
2522 state.tag = _tag;
2523 state.anchor = _anchor;
2524 return true; // Keep the result of `composeNode`.
2525 }
2526
2527 } else {
2528 break; // Reading is done. Go to the epilogue.
2529 }
2530
2531 //
2532 // Common reading code for both explicit and implicit notations.
2533 //
2534 if (state.line === _line || state.lineIndent > nodeIndent) {
2535 if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
2536 if (atExplicitKey) {
2537 keyNode = state.result;
2538 } else {
2539 valueNode = state.result;
2540 }
2541 }
2542
2543 if (!atExplicitKey) {
2544 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
2545 keyTag = keyNode = valueNode = null;
2546 }
2547
2548 skipSeparationSpace(state, true, -1);
2549 ch = state.input.charCodeAt(state.position);
2550 }
2551
2552 if (state.lineIndent > nodeIndent && (ch !== 0)) {
2553 throwError(state, 'bad indentation of a mapping entry');
2554 } else if (state.lineIndent < nodeIndent) {
2555 break;
2556 }
2557 }
2558
2559 //
2560 // Epilogue.
2561 //
2562
2563 // Special case: last mapping's node contains only the key in explicit notation.
2564 if (atExplicitKey) {
2565 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2566 }
2567
2568 // Expose the resulting mapping.
2569 if (detected) {
2570 state.tag = _tag;
2571 state.anchor = _anchor;
2572 state.kind = 'mapping';
2573 state.result = _result;
2574 }
2575
2576 return detected;
2577}
2578
2579function readTagProperty(state) {
2580 var _position,
2581 isVerbatim = false,
2582 isNamed = false,
2583 tagHandle,
2584 tagName,
2585 ch;
2586
2587 ch = state.input.charCodeAt(state.position);
2588
2589 if (ch !== 0x21/* ! */) return false;
2590
2591 if (state.tag !== null) {
2592 throwError(state, 'duplication of a tag property');
2593 }
2594
2595 ch = state.input.charCodeAt(++state.position);
2596
2597 if (ch === 0x3C/* < */) {
2598 isVerbatim = true;
2599 ch = state.input.charCodeAt(++state.position);
2600
2601 } else if (ch === 0x21/* ! */) {
2602 isNamed = true;
2603 tagHandle = '!!';
2604 ch = state.input.charCodeAt(++state.position);
2605
2606 } else {
2607 tagHandle = '!';
2608 }
2609
2610 _position = state.position;
2611
2612 if (isVerbatim) {
2613 do { ch = state.input.charCodeAt(++state.position); }
2614 while (ch !== 0 && ch !== 0x3E/* > */);
2615
2616 if (state.position < state.length) {
2617 tagName = state.input.slice(_position, state.position);
2618 ch = state.input.charCodeAt(++state.position);
2619 } else {
2620 throwError(state, 'unexpected end of the stream within a verbatim tag');
2621 }
2622 } else {
2623 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2624
2625 if (ch === 0x21/* ! */) {
2626 if (!isNamed) {
2627 tagHandle = state.input.slice(_position - 1, state.position + 1);
2628
2629 if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
2630 throwError(state, 'named tag handle cannot contain such characters');
2631 }
2632
2633 isNamed = true;
2634 _position = state.position + 1;
2635 } else {
2636 throwError(state, 'tag suffix cannot contain exclamation marks');
2637 }
2638 }
2639
2640 ch = state.input.charCodeAt(++state.position);
2641 }
2642
2643 tagName = state.input.slice(_position, state.position);
2644
2645 if (PATTERN_FLOW_INDICATORS.test(tagName)) {
2646 throwError(state, 'tag suffix cannot contain flow indicator characters');
2647 }
2648 }
2649
2650 if (tagName && !PATTERN_TAG_URI.test(tagName)) {
2651 throwError(state, 'tag name cannot contain such characters: ' + tagName);
2652 }
2653
2654 if (isVerbatim) {
2655 state.tag = tagName;
2656
2657 } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
2658 state.tag = state.tagMap[tagHandle] + tagName;
2659
2660 } else if (tagHandle === '!') {
2661 state.tag = '!' + tagName;
2662
2663 } else if (tagHandle === '!!') {
2664 state.tag = 'tag:yaml.org,2002:' + tagName;
2665
2666 } else {
2667 throwError(state, 'undeclared tag handle "' + tagHandle + '"');
2668 }
2669
2670 return true;
2671}
2672
2673function readAnchorProperty(state) {
2674 var _position,
2675 ch;
2676
2677 ch = state.input.charCodeAt(state.position);
2678
2679 if (ch !== 0x26/* & */) return false;
2680
2681 if (state.anchor !== null) {
2682 throwError(state, 'duplication of an anchor property');
2683 }
2684
2685 ch = state.input.charCodeAt(++state.position);
2686 _position = state.position;
2687
2688 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2689 ch = state.input.charCodeAt(++state.position);
2690 }
2691
2692 if (state.position === _position) {
2693 throwError(state, 'name of an anchor node must contain at least one character');
2694 }
2695
2696 state.anchor = state.input.slice(_position, state.position);
2697 return true;
2698}
2699
2700function readAlias(state) {
2701 var _position, alias,
2702 ch;
2703
2704 ch = state.input.charCodeAt(state.position);
2705
2706 if (ch !== 0x2A/* * */) return false;
2707
2708 ch = state.input.charCodeAt(++state.position);
2709 _position = state.position;
2710
2711 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2712 ch = state.input.charCodeAt(++state.position);
2713 }
2714
2715 if (state.position === _position) {
2716 throwError(state, 'name of an alias node must contain at least one character');
2717 }
2718
2719 alias = state.input.slice(_position, state.position);
2720
2721 if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
2722 throwError(state, 'unidentified alias "' + alias + '"');
2723 }
2724
2725 state.result = state.anchorMap[alias];
2726 skipSeparationSpace(state, true, -1);
2727 return true;
2728}
2729
2730function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
2731 var allowBlockStyles,
2732 allowBlockScalars,
2733 allowBlockCollections,
2734 indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
2735 atNewLine = false,
2736 hasContent = false,
2737 typeIndex,
2738 typeQuantity,
2739 type,
2740 flowIndent,
2741 blockIndent;
2742
2743 if (state.listener !== null) {
2744 state.listener('open', state);
2745 }
2746
2747 state.tag = null;
2748 state.anchor = null;
2749 state.kind = null;
2750 state.result = null;
2751
2752 allowBlockStyles = allowBlockScalars = allowBlockCollections =
2753 CONTEXT_BLOCK_OUT === nodeContext ||
2754 CONTEXT_BLOCK_IN === nodeContext;
2755
2756 if (allowToSeek) {
2757 if (skipSeparationSpace(state, true, -1)) {
2758 atNewLine = true;
2759
2760 if (state.lineIndent > parentIndent) {
2761 indentStatus = 1;
2762 } else if (state.lineIndent === parentIndent) {
2763 indentStatus = 0;
2764 } else if (state.lineIndent < parentIndent) {
2765 indentStatus = -1;
2766 }
2767 }
2768 }
2769
2770 if (indentStatus === 1) {
2771 while (readTagProperty(state) || readAnchorProperty(state)) {
2772 if (skipSeparationSpace(state, true, -1)) {
2773 atNewLine = true;
2774 allowBlockCollections = allowBlockStyles;
2775
2776 if (state.lineIndent > parentIndent) {
2777 indentStatus = 1;
2778 } else if (state.lineIndent === parentIndent) {
2779 indentStatus = 0;
2780 } else if (state.lineIndent < parentIndent) {
2781 indentStatus = -1;
2782 }
2783 } else {
2784 allowBlockCollections = false;
2785 }
2786 }
2787 }
2788
2789 if (allowBlockCollections) {
2790 allowBlockCollections = atNewLine || allowCompact;
2791 }
2792
2793 if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
2794 if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
2795 flowIndent = parentIndent;
2796 } else {
2797 flowIndent = parentIndent + 1;
2798 }
2799
2800 blockIndent = state.position - state.lineStart;
2801
2802 if (indentStatus === 1) {
2803 if (allowBlockCollections &&
2804 (readBlockSequence(state, blockIndent) ||
2805 readBlockMapping(state, blockIndent, flowIndent)) ||
2806 readFlowCollection(state, flowIndent)) {
2807 hasContent = true;
2808 } else {
2809 if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
2810 readSingleQuotedScalar(state, flowIndent) ||
2811 readDoubleQuotedScalar(state, flowIndent)) {
2812 hasContent = true;
2813
2814 } else if (readAlias(state)) {
2815 hasContent = true;
2816
2817 if (state.tag !== null || state.anchor !== null) {
2818 throwError(state, 'alias node should not have any properties');
2819 }
2820
2821 } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
2822 hasContent = true;
2823
2824 if (state.tag === null) {
2825 state.tag = '?';
2826 }
2827 }
2828
2829 if (state.anchor !== null) {
2830 state.anchorMap[state.anchor] = state.result;
2831 }
2832 }
2833 } else if (indentStatus === 0) {
2834 // Special case: block sequences are allowed to have same indentation level as the parent.
2835 // http://www.yaml.org/spec/1.2/spec.html#id2799784
2836 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
2837 }
2838 }
2839
2840 if (state.tag !== null && state.tag !== '!') {
2841 if (state.tag === '?') {
2842 // Implicit resolving is not allowed for non-scalar types, and '?'
2843 // non-specific tag is only automatically assigned to plain scalars.
2844 //
2845 // We only need to check kind conformity in case user explicitly assigns '?'
2846 // tag, for example like this: "!<?> [0]"
2847 //
2848 if (state.result !== null && state.kind !== 'scalar') {
2849 throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
2850 }
2851
2852 for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
2853 type = state.implicitTypes[typeIndex];
2854
2855 if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
2856 state.result = type.construct(state.result);
2857 state.tag = type.tag;
2858 if (state.anchor !== null) {
2859 state.anchorMap[state.anchor] = state.result;
2860 }
2861 break;
2862 }
2863 }
2864 } else if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
2865 type = state.typeMap[state.kind || 'fallback'][state.tag];
2866
2867 if (state.result !== null && type.kind !== state.kind) {
2868 throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
2869 }
2870
2871 if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
2872 throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
2873 } else {
2874 state.result = type.construct(state.result);
2875 if (state.anchor !== null) {
2876 state.anchorMap[state.anchor] = state.result;
2877 }
2878 }
2879 } else {
2880 throwError(state, 'unknown tag !<' + state.tag + '>');
2881 }
2882 }
2883
2884 if (state.listener !== null) {
2885 state.listener('close', state);
2886 }
2887 return state.tag !== null || state.anchor !== null || hasContent;
2888}
2889
2890function readDocument(state) {
2891 var documentStart = state.position,
2892 _position,
2893 directiveName,
2894 directiveArgs,
2895 hasDirectives = false,
2896 ch;
2897
2898 state.version = null;
2899 state.checkLineBreaks = state.legacy;
2900 state.tagMap = {};
2901 state.anchorMap = {};
2902
2903 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2904 skipSeparationSpace(state, true, -1);
2905
2906 ch = state.input.charCodeAt(state.position);
2907
2908 if (state.lineIndent > 0 || ch !== 0x25/* % */) {
2909 break;
2910 }
2911
2912 hasDirectives = true;
2913 ch = state.input.charCodeAt(++state.position);
2914 _position = state.position;
2915
2916 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2917 ch = state.input.charCodeAt(++state.position);
2918 }
2919
2920 directiveName = state.input.slice(_position, state.position);
2921 directiveArgs = [];
2922
2923 if (directiveName.length < 1) {
2924 throwError(state, 'directive name must not be less than one character in length');
2925 }
2926
2927 while (ch !== 0) {
2928 while (is_WHITE_SPACE(ch)) {
2929 ch = state.input.charCodeAt(++state.position);
2930 }
2931
2932 if (ch === 0x23/* # */) {
2933 do { ch = state.input.charCodeAt(++state.position); }
2934 while (ch !== 0 && !is_EOL(ch));
2935 break;
2936 }
2937
2938 if (is_EOL(ch)) break;
2939
2940 _position = state.position;
2941
2942 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2943 ch = state.input.charCodeAt(++state.position);
2944 }
2945
2946 directiveArgs.push(state.input.slice(_position, state.position));
2947 }
2948
2949 if (ch !== 0) readLineBreak(state);
2950
2951 if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
2952 directiveHandlers[directiveName](state, directiveName, directiveArgs);
2953 } else {
2954 throwWarning(state, 'unknown document directive "' + directiveName + '"');
2955 }
2956 }
2957
2958 skipSeparationSpace(state, true, -1);
2959
2960 if (state.lineIndent === 0 &&
2961 state.input.charCodeAt(state.position) === 0x2D/* - */ &&
2962 state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
2963 state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
2964 state.position += 3;
2965 skipSeparationSpace(state, true, -1);
2966
2967 } else if (hasDirectives) {
2968 throwError(state, 'directives end mark is expected');
2969 }
2970
2971 composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
2972 skipSeparationSpace(state, true, -1);
2973
2974 if (state.checkLineBreaks &&
2975 PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
2976 throwWarning(state, 'non-ASCII line breaks are interpreted as content');
2977 }
2978
2979 state.documents.push(state.result);
2980
2981 if (state.position === state.lineStart && testDocumentSeparator(state)) {
2982
2983 if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
2984 state.position += 3;
2985 skipSeparationSpace(state, true, -1);
2986 }
2987 return;
2988 }
2989
2990 if (state.position < (state.length - 1)) {
2991 throwError(state, 'end of the stream or a document separator is expected');
2992 } else {
2993 return;
2994 }
2995}
2996
2997
2998function loadDocuments(input, options) {
2999 input = String(input);
3000 options = options || {};
3001
3002 if (input.length !== 0) {
3003
3004 // Add tailing `\n` if not exists
3005 if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
3006 input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
3007 input += '\n';
3008 }
3009
3010 // Strip BOM
3011 if (input.charCodeAt(0) === 0xFEFF) {
3012 input = input.slice(1);
3013 }
3014 }
3015
3016 var state = new State$1(input, options);
3017
3018 var nullpos = input.indexOf('\0');
3019
3020 if (nullpos !== -1) {
3021 state.position = nullpos;
3022 throwError(state, 'null byte is not allowed in input');
3023 }
3024
3025 // Use 0 as string terminator. That significantly simplifies bounds check.
3026 state.input += '\0';
3027
3028 while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
3029 state.lineIndent += 1;
3030 state.position += 1;
3031 }
3032
3033 while (state.position < (state.length - 1)) {
3034 readDocument(state);
3035 }
3036
3037 return state.documents;
3038}
3039
3040
3041function loadAll(input, iterator, options) {
3042 if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
3043 options = iterator;
3044 iterator = null;
3045 }
3046
3047 var documents = loadDocuments(input, options);
3048
3049 if (typeof iterator !== 'function') {
3050 return documents;
3051 }
3052
3053 for (var index = 0, length = documents.length; index < length; index += 1) {
3054 iterator(documents[index]);
3055 }
3056}
3057
3058
3059function load(input, options) {
3060 var documents = loadDocuments(input, options);
3061
3062 if (documents.length === 0) {
3063 /*eslint-disable no-undefined*/
3064 return undefined;
3065 } else if (documents.length === 1) {
3066 return documents[0];
3067 }
3068 throw new YAMLException$1('expected a single document in the stream, but found more');
3069}
3070
3071
3072function safeLoadAll(input, iterator, options) {
3073 if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {
3074 options = iterator;
3075 iterator = null;
3076 }
3077
3078 return loadAll(input, iterator, common$1.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options));
3079}
3080
3081
3082function safeLoad(input, options) {
3083 return load(input, common$1.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options));
3084}
3085
3086
3087loader$1.loadAll = loadAll;
3088loader$1.load = load;
3089loader$1.safeLoadAll = safeLoadAll;
3090loader$1.safeLoad = safeLoad;
3091
3092var dumper$1 = {};
3093
3094/*eslint-disable no-use-before-define*/
3095
3096var common = common$6;
3097var YAMLException = exception;
3098var DEFAULT_FULL_SCHEMA = default_full;
3099var DEFAULT_SAFE_SCHEMA = default_safe;
3100
3101var _toString = Object.prototype.toString;
3102var _hasOwnProperty = Object.prototype.hasOwnProperty;
3103
3104var CHAR_TAB = 0x09; /* Tab */
3105var CHAR_LINE_FEED = 0x0A; /* LF */
3106var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
3107var CHAR_SPACE = 0x20; /* Space */
3108var CHAR_EXCLAMATION = 0x21; /* ! */
3109var CHAR_DOUBLE_QUOTE = 0x22; /* " */
3110var CHAR_SHARP = 0x23; /* # */
3111var CHAR_PERCENT = 0x25; /* % */
3112var CHAR_AMPERSAND = 0x26; /* & */
3113var CHAR_SINGLE_QUOTE = 0x27; /* ' */
3114var CHAR_ASTERISK = 0x2A; /* * */
3115var CHAR_COMMA = 0x2C; /* , */
3116var CHAR_MINUS = 0x2D; /* - */
3117var CHAR_COLON = 0x3A; /* : */
3118var CHAR_EQUALS = 0x3D; /* = */
3119var CHAR_GREATER_THAN = 0x3E; /* > */
3120var CHAR_QUESTION = 0x3F; /* ? */
3121var CHAR_COMMERCIAL_AT = 0x40; /* @ */
3122var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
3123var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
3124var CHAR_GRAVE_ACCENT = 0x60; /* ` */
3125var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
3126var CHAR_VERTICAL_LINE = 0x7C; /* | */
3127var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
3128
3129var ESCAPE_SEQUENCES = {};
3130
3131ESCAPE_SEQUENCES[0x00] = '\\0';
3132ESCAPE_SEQUENCES[0x07] = '\\a';
3133ESCAPE_SEQUENCES[0x08] = '\\b';
3134ESCAPE_SEQUENCES[0x09] = '\\t';
3135ESCAPE_SEQUENCES[0x0A] = '\\n';
3136ESCAPE_SEQUENCES[0x0B] = '\\v';
3137ESCAPE_SEQUENCES[0x0C] = '\\f';
3138ESCAPE_SEQUENCES[0x0D] = '\\r';
3139ESCAPE_SEQUENCES[0x1B] = '\\e';
3140ESCAPE_SEQUENCES[0x22] = '\\"';
3141ESCAPE_SEQUENCES[0x5C] = '\\\\';
3142ESCAPE_SEQUENCES[0x85] = '\\N';
3143ESCAPE_SEQUENCES[0xA0] = '\\_';
3144ESCAPE_SEQUENCES[0x2028] = '\\L';
3145ESCAPE_SEQUENCES[0x2029] = '\\P';
3146
3147var DEPRECATED_BOOLEANS_SYNTAX = [
3148 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
3149 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
3150];
3151
3152function compileStyleMap(schema, map) {
3153 var result, keys, index, length, tag, style, type;
3154
3155 if (map === null) return {};
3156
3157 result = {};
3158 keys = Object.keys(map);
3159
3160 for (index = 0, length = keys.length; index < length; index += 1) {
3161 tag = keys[index];
3162 style = String(map[tag]);
3163
3164 if (tag.slice(0, 2) === '!!') {
3165 tag = 'tag:yaml.org,2002:' + tag.slice(2);
3166 }
3167 type = schema.compiledTypeMap['fallback'][tag];
3168
3169 if (type && _hasOwnProperty.call(type.styleAliases, style)) {
3170 style = type.styleAliases[style];
3171 }
3172
3173 result[tag] = style;
3174 }
3175
3176 return result;
3177}
3178
3179function encodeHex(character) {
3180 var string, handle, length;
3181
3182 string = character.toString(16).toUpperCase();
3183
3184 if (character <= 0xFF) {
3185 handle = 'x';
3186 length = 2;
3187 } else if (character <= 0xFFFF) {
3188 handle = 'u';
3189 length = 4;
3190 } else if (character <= 0xFFFFFFFF) {
3191 handle = 'U';
3192 length = 8;
3193 } else {
3194 throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
3195 }
3196
3197 return '\\' + handle + common.repeat('0', length - string.length) + string;
3198}
3199
3200function State(options) {
3201 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
3202 this.indent = Math.max(1, (options['indent'] || 2));
3203 this.noArrayIndent = options['noArrayIndent'] || false;
3204 this.skipInvalid = options['skipInvalid'] || false;
3205 this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
3206 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
3207 this.sortKeys = options['sortKeys'] || false;
3208 this.lineWidth = options['lineWidth'] || 80;
3209 this.noRefs = options['noRefs'] || false;
3210 this.noCompatMode = options['noCompatMode'] || false;
3211 this.condenseFlow = options['condenseFlow'] || false;
3212
3213 this.implicitTypes = this.schema.compiledImplicit;
3214 this.explicitTypes = this.schema.compiledExplicit;
3215
3216 this.tag = null;
3217 this.result = '';
3218
3219 this.duplicates = [];
3220 this.usedDuplicates = null;
3221}
3222
3223// Indents every line in a string. Empty lines (\n only) are not indented.
3224function indentString(string, spaces) {
3225 var ind = common.repeat(' ', spaces),
3226 position = 0,
3227 next = -1,
3228 result = '',
3229 line,
3230 length = string.length;
3231
3232 while (position < length) {
3233 next = string.indexOf('\n', position);
3234 if (next === -1) {
3235 line = string.slice(position);
3236 position = length;
3237 } else {
3238 line = string.slice(position, next + 1);
3239 position = next + 1;
3240 }
3241
3242 if (line.length && line !== '\n') result += ind;
3243
3244 result += line;
3245 }
3246
3247 return result;
3248}
3249
3250function generateNextLine(state, level) {
3251 return '\n' + common.repeat(' ', state.indent * level);
3252}
3253
3254function testImplicitResolving(state, str) {
3255 var index, length, type;
3256
3257 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
3258 type = state.implicitTypes[index];
3259
3260 if (type.resolve(str)) {
3261 return true;
3262 }
3263 }
3264
3265 return false;
3266}
3267
3268// [33] s-white ::= s-space | s-tab
3269function isWhitespace(c) {
3270 return c === CHAR_SPACE || c === CHAR_TAB;
3271}
3272
3273// Returns true if the character can be printed without escaping.
3274// From YAML 1.2: "any allowed characters known to be non-printable
3275// should also be escaped. [However,] This isn’t mandatory"
3276// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
3277function isPrintable(c) {
3278 return (0x00020 <= c && c <= 0x00007E)
3279 || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
3280 || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
3281 || (0x10000 <= c && c <= 0x10FFFF);
3282}
3283
3284// [34] ns-char ::= nb-char - s-white
3285// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
3286// [26] b-char ::= b-line-feed | b-carriage-return
3287// [24] b-line-feed ::= #xA /* LF */
3288// [25] b-carriage-return ::= #xD /* CR */
3289// [3] c-byte-order-mark ::= #xFEFF
3290function isNsChar(c) {
3291 return isPrintable(c) && !isWhitespace(c)
3292 // byte-order-mark
3293 && c !== 0xFEFF
3294 // b-char
3295 && c !== CHAR_CARRIAGE_RETURN
3296 && c !== CHAR_LINE_FEED;
3297}
3298
3299// Simplified test for values allowed after the first character in plain style.
3300function isPlainSafe(c, prev) {
3301 // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
3302 // where nb-char ::= c-printable - b-char - c-byte-order-mark.
3303 return isPrintable(c) && c !== 0xFEFF
3304 // - c-flow-indicator
3305 && c !== CHAR_COMMA
3306 && c !== CHAR_LEFT_SQUARE_BRACKET
3307 && c !== CHAR_RIGHT_SQUARE_BRACKET
3308 && c !== CHAR_LEFT_CURLY_BRACKET
3309 && c !== CHAR_RIGHT_CURLY_BRACKET
3310 // - ":" - "#"
3311 // /* An ns-char preceding */ "#"
3312 && c !== CHAR_COLON
3313 && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));
3314}
3315
3316// Simplified test for values allowed as the first character in plain style.
3317function isPlainSafeFirst(c) {
3318 // Uses a subset of ns-char - c-indicator
3319 // where ns-char = nb-char - s-white.
3320 return isPrintable(c) && c !== 0xFEFF
3321 && !isWhitespace(c) // - s-white
3322 // - (c-indicator ::=
3323 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
3324 && c !== CHAR_MINUS
3325 && c !== CHAR_QUESTION
3326 && c !== CHAR_COLON
3327 && c !== CHAR_COMMA
3328 && c !== CHAR_LEFT_SQUARE_BRACKET
3329 && c !== CHAR_RIGHT_SQUARE_BRACKET
3330 && c !== CHAR_LEFT_CURLY_BRACKET
3331 && c !== CHAR_RIGHT_CURLY_BRACKET
3332 // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
3333 && c !== CHAR_SHARP
3334 && c !== CHAR_AMPERSAND
3335 && c !== CHAR_ASTERISK
3336 && c !== CHAR_EXCLAMATION
3337 && c !== CHAR_VERTICAL_LINE
3338 && c !== CHAR_EQUALS
3339 && c !== CHAR_GREATER_THAN
3340 && c !== CHAR_SINGLE_QUOTE
3341 && c !== CHAR_DOUBLE_QUOTE
3342 // | “%” | “@” | “`”)
3343 && c !== CHAR_PERCENT
3344 && c !== CHAR_COMMERCIAL_AT
3345 && c !== CHAR_GRAVE_ACCENT;
3346}
3347
3348// Determines whether block indentation indicator is required.
3349function needIndentIndicator(string) {
3350 var leadingSpaceRe = /^\n* /;
3351 return leadingSpaceRe.test(string);
3352}
3353
3354var STYLE_PLAIN = 1,
3355 STYLE_SINGLE = 2,
3356 STYLE_LITERAL = 3,
3357 STYLE_FOLDED = 4,
3358 STYLE_DOUBLE = 5;
3359
3360// Determines which scalar styles are possible and returns the preferred style.
3361// lineWidth = -1 => no limit.
3362// Pre-conditions: str.length > 0.
3363// Post-conditions:
3364// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
3365// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
3366// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
3367function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
3368 var i;
3369 var char, prev_char;
3370 var hasLineBreak = false;
3371 var hasFoldableLine = false; // only checked if shouldTrackWidth
3372 var shouldTrackWidth = lineWidth !== -1;
3373 var previousLineBreak = -1; // count the first line correctly
3374 var plain = isPlainSafeFirst(string.charCodeAt(0))
3375 && !isWhitespace(string.charCodeAt(string.length - 1));
3376
3377 if (singleLineOnly) {
3378 // Case: no block styles.
3379 // Check for disallowed characters to rule out plain and single.
3380 for (i = 0; i < string.length; i++) {
3381 char = string.charCodeAt(i);
3382 if (!isPrintable(char)) {
3383 return STYLE_DOUBLE;
3384 }
3385 prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
3386 plain = plain && isPlainSafe(char, prev_char);
3387 }
3388 } else {
3389 // Case: block styles permitted.
3390 for (i = 0; i < string.length; i++) {
3391 char = string.charCodeAt(i);
3392 if (char === CHAR_LINE_FEED) {
3393 hasLineBreak = true;
3394 // Check if any line can be folded.
3395 if (shouldTrackWidth) {
3396 hasFoldableLine = hasFoldableLine ||
3397 // Foldable line = too long, and not more-indented.
3398 (i - previousLineBreak - 1 > lineWidth &&
3399 string[previousLineBreak + 1] !== ' ');
3400 previousLineBreak = i;
3401 }
3402 } else if (!isPrintable(char)) {
3403 return STYLE_DOUBLE;
3404 }
3405 prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
3406 plain = plain && isPlainSafe(char, prev_char);
3407 }
3408 // in case the end is missing a \n
3409 hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
3410 (i - previousLineBreak - 1 > lineWidth &&
3411 string[previousLineBreak + 1] !== ' '));
3412 }
3413 // Although every style can represent \n without escaping, prefer block styles
3414 // for multiline, since they're more readable and they don't add empty lines.
3415 // Also prefer folding a super-long line.
3416 if (!hasLineBreak && !hasFoldableLine) {
3417 // Strings interpretable as another type have to be quoted;
3418 // e.g. the string 'true' vs. the boolean true.
3419 return plain && !testAmbiguousType(string)
3420 ? STYLE_PLAIN : STYLE_SINGLE;
3421 }
3422 // Edge case: block indentation indicator can only have one digit.
3423 if (indentPerLevel > 9 && needIndentIndicator(string)) {
3424 return STYLE_DOUBLE;
3425 }
3426 // At this point we know block styles are valid.
3427 // Prefer literal style unless we want to fold.
3428 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
3429}
3430
3431// Note: line breaking/folding is implemented for only the folded style.
3432// NB. We drop the last trailing newline (if any) of a returned block scalar
3433// since the dumper adds its own newline. This always works:
3434// • No ending newline => unaffected; already using strip "-" chomping.
3435// • Ending newline => removed then restored.
3436// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
3437function writeScalar(state, string, level, iskey) {
3438 state.dump = (function () {
3439 if (string.length === 0) {
3440 return "''";
3441 }
3442 if (!state.noCompatMode &&
3443 DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
3444 return "'" + string + "'";
3445 }
3446
3447 var indent = state.indent * Math.max(1, level); // no 0-indent scalars
3448 // As indentation gets deeper, let the width decrease monotonically
3449 // to the lower bound min(state.lineWidth, 40).
3450 // Note that this implies
3451 // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
3452 // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
3453 // This behaves better than a constant minimum width which disallows narrower options,
3454 // or an indent threshold which causes the width to suddenly increase.
3455 var lineWidth = state.lineWidth === -1
3456 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
3457
3458 // Without knowing if keys are implicit/explicit, assume implicit for safety.
3459 var singleLineOnly = iskey
3460 // No block styles in flow mode.
3461 || (state.flowLevel > -1 && level >= state.flowLevel);
3462 function testAmbiguity(string) {
3463 return testImplicitResolving(state, string);
3464 }
3465
3466 switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
3467 case STYLE_PLAIN:
3468 return string;
3469 case STYLE_SINGLE:
3470 return "'" + string.replace(/'/g, "''") + "'";
3471 case STYLE_LITERAL:
3472 return '|' + blockHeader(string, state.indent)
3473 + dropEndingNewline(indentString(string, indent));
3474 case STYLE_FOLDED:
3475 return '>' + blockHeader(string, state.indent)
3476 + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
3477 case STYLE_DOUBLE:
3478 return '"' + escapeString(string) + '"';
3479 default:
3480 throw new YAMLException('impossible error: invalid scalar style');
3481 }
3482 }());
3483}
3484
3485// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
3486function blockHeader(string, indentPerLevel) {
3487 var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
3488
3489 // note the special case: the string '\n' counts as a "trailing" empty line.
3490 var clip = string[string.length - 1] === '\n';
3491 var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
3492 var chomp = keep ? '+' : (clip ? '' : '-');
3493
3494 return indentIndicator + chomp + '\n';
3495}
3496
3497// (See the note for writeScalar.)
3498function dropEndingNewline(string) {
3499 return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
3500}
3501
3502// Note: a long line without a suitable break point will exceed the width limit.
3503// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
3504function foldString(string, width) {
3505 // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
3506 // unless they're before or after a more-indented line, or at the very
3507 // beginning or end, in which case $k$ maps to $k$.
3508 // Therefore, parse each chunk as newline(s) followed by a content line.
3509 var lineRe = /(\n+)([^\n]*)/g;
3510
3511 // first line (possibly an empty line)
3512 var result = (function () {
3513 var nextLF = string.indexOf('\n');
3514 nextLF = nextLF !== -1 ? nextLF : string.length;
3515 lineRe.lastIndex = nextLF;
3516 return foldLine(string.slice(0, nextLF), width);
3517 }());
3518 // If we haven't reached the first content line yet, don't add an extra \n.
3519 var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
3520 var moreIndented;
3521
3522 // rest of the lines
3523 var match;
3524 while ((match = lineRe.exec(string))) {
3525 var prefix = match[1], line = match[2];
3526 moreIndented = (line[0] === ' ');
3527 result += prefix
3528 + (!prevMoreIndented && !moreIndented && line !== ''
3529 ? '\n' : '')
3530 + foldLine(line, width);
3531 prevMoreIndented = moreIndented;
3532 }
3533
3534 return result;
3535}
3536
3537// Greedy line breaking.
3538// Picks the longest line under the limit each time,
3539// otherwise settles for the shortest line over the limit.
3540// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
3541function foldLine(line, width) {
3542 if (line === '' || line[0] === ' ') return line;
3543
3544 // Since a more-indented line adds a \n, breaks can't be followed by a space.
3545 var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
3546 var match;
3547 // start is an inclusive index. end, curr, and next are exclusive.
3548 var start = 0, end, curr = 0, next = 0;
3549 var result = '';
3550
3551 // Invariants: 0 <= start <= length-1.
3552 // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
3553 // Inside the loop:
3554 // A match implies length >= 2, so curr and next are <= length-2.
3555 while ((match = breakRe.exec(line))) {
3556 next = match.index;
3557 // maintain invariant: curr - start <= width
3558 if (next - start > width) {
3559 end = (curr > start) ? curr : next; // derive end <= length-2
3560 result += '\n' + line.slice(start, end);
3561 // skip the space that was output as \n
3562 start = end + 1; // derive start <= length-1
3563 }
3564 curr = next;
3565 }
3566
3567 // By the invariants, start <= length-1, so there is something left over.
3568 // It is either the whole string or a part starting from non-whitespace.
3569 result += '\n';
3570 // Insert a break if the remainder is too long and there is a break available.
3571 if (line.length - start > width && curr > start) {
3572 result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
3573 } else {
3574 result += line.slice(start);
3575 }
3576
3577 return result.slice(1); // drop extra \n joiner
3578}
3579
3580// Escapes a double-quoted string.
3581function escapeString(string) {
3582 var result = '';
3583 var char, nextChar;
3584 var escapeSeq;
3585
3586 for (var i = 0; i < string.length; i++) {
3587 char = string.charCodeAt(i);
3588 // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
3589 if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
3590 nextChar = string.charCodeAt(i + 1);
3591 if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
3592 // Combine the surrogate pair and store it escaped.
3593 result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
3594 // Advance index one extra since we already used that char here.
3595 i++; continue;
3596 }
3597 }
3598 escapeSeq = ESCAPE_SEQUENCES[char];
3599 result += !escapeSeq && isPrintable(char)
3600 ? string[i]
3601 : escapeSeq || encodeHex(char);
3602 }
3603
3604 return result;
3605}
3606
3607function writeFlowSequence(state, level, object) {
3608 var _result = '',
3609 _tag = state.tag,
3610 index,
3611 length;
3612
3613 for (index = 0, length = object.length; index < length; index += 1) {
3614 // Write only valid elements.
3615 if (writeNode(state, level, object[index], false, false)) {
3616 if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
3617 _result += state.dump;
3618 }
3619 }
3620
3621 state.tag = _tag;
3622 state.dump = '[' + _result + ']';
3623}
3624
3625function writeBlockSequence(state, level, object, compact) {
3626 var _result = '',
3627 _tag = state.tag,
3628 index,
3629 length;
3630
3631 for (index = 0, length = object.length; index < length; index += 1) {
3632 // Write only valid elements.
3633 if (writeNode(state, level + 1, object[index], true, true)) {
3634 if (!compact || index !== 0) {
3635 _result += generateNextLine(state, level);
3636 }
3637
3638 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3639 _result += '-';
3640 } else {
3641 _result += '- ';
3642 }
3643
3644 _result += state.dump;
3645 }
3646 }
3647
3648 state.tag = _tag;
3649 state.dump = _result || '[]'; // Empty sequence if no valid values.
3650}
3651
3652function writeFlowMapping(state, level, object) {
3653 var _result = '',
3654 _tag = state.tag,
3655 objectKeyList = Object.keys(object),
3656 index,
3657 length,
3658 objectKey,
3659 objectValue,
3660 pairBuffer;
3661
3662 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3663
3664 pairBuffer = '';
3665 if (index !== 0) pairBuffer += ', ';
3666
3667 if (state.condenseFlow) pairBuffer += '"';
3668
3669 objectKey = objectKeyList[index];
3670 objectValue = object[objectKey];
3671
3672 if (!writeNode(state, level, objectKey, false, false)) {
3673 continue; // Skip this pair because of invalid key;
3674 }
3675
3676 if (state.dump.length > 1024) pairBuffer += '? ';
3677
3678 pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
3679
3680 if (!writeNode(state, level, objectValue, false, false)) {
3681 continue; // Skip this pair because of invalid value.
3682 }
3683
3684 pairBuffer += state.dump;
3685
3686 // Both key and value are valid.
3687 _result += pairBuffer;
3688 }
3689
3690 state.tag = _tag;
3691 state.dump = '{' + _result + '}';
3692}
3693
3694function writeBlockMapping(state, level, object, compact) {
3695 var _result = '',
3696 _tag = state.tag,
3697 objectKeyList = Object.keys(object),
3698 index,
3699 length,
3700 objectKey,
3701 objectValue,
3702 explicitPair,
3703 pairBuffer;
3704
3705 // Allow sorting keys so that the output file is deterministic
3706 if (state.sortKeys === true) {
3707 // Default sorting
3708 objectKeyList.sort();
3709 } else if (typeof state.sortKeys === 'function') {
3710 // Custom sort function
3711 objectKeyList.sort(state.sortKeys);
3712 } else if (state.sortKeys) {
3713 // Something is wrong
3714 throw new YAMLException('sortKeys must be a boolean or a function');
3715 }
3716
3717 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3718 pairBuffer = '';
3719
3720 if (!compact || index !== 0) {
3721 pairBuffer += generateNextLine(state, level);
3722 }
3723
3724 objectKey = objectKeyList[index];
3725 objectValue = object[objectKey];
3726
3727 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
3728 continue; // Skip this pair because of invalid key.
3729 }
3730
3731 explicitPair = (state.tag !== null && state.tag !== '?') ||
3732 (state.dump && state.dump.length > 1024);
3733
3734 if (explicitPair) {
3735 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3736 pairBuffer += '?';
3737 } else {
3738 pairBuffer += '? ';
3739 }
3740 }
3741
3742 pairBuffer += state.dump;
3743
3744 if (explicitPair) {
3745 pairBuffer += generateNextLine(state, level);
3746 }
3747
3748 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
3749 continue; // Skip this pair because of invalid value.
3750 }
3751
3752 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3753 pairBuffer += ':';
3754 } else {
3755 pairBuffer += ': ';
3756 }
3757
3758 pairBuffer += state.dump;
3759
3760 // Both key and value are valid.
3761 _result += pairBuffer;
3762 }
3763
3764 state.tag = _tag;
3765 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
3766}
3767
3768function detectType(state, object, explicit) {
3769 var _result, typeList, index, length, type, style;
3770
3771 typeList = explicit ? state.explicitTypes : state.implicitTypes;
3772
3773 for (index = 0, length = typeList.length; index < length; index += 1) {
3774 type = typeList[index];
3775
3776 if ((type.instanceOf || type.predicate) &&
3777 (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
3778 (!type.predicate || type.predicate(object))) {
3779
3780 state.tag = explicit ? type.tag : '?';
3781
3782 if (type.represent) {
3783 style = state.styleMap[type.tag] || type.defaultStyle;
3784
3785 if (_toString.call(type.represent) === '[object Function]') {
3786 _result = type.represent(object, style);
3787 } else if (_hasOwnProperty.call(type.represent, style)) {
3788 _result = type.represent[style](object, style);
3789 } else {
3790 throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
3791 }
3792
3793 state.dump = _result;
3794 }
3795
3796 return true;
3797 }
3798 }
3799
3800 return false;
3801}
3802
3803// Serializes `object` and writes it to global `result`.
3804// Returns true on success, or false on invalid object.
3805//
3806function writeNode(state, level, object, block, compact, iskey) {
3807 state.tag = null;
3808 state.dump = object;
3809
3810 if (!detectType(state, object, false)) {
3811 detectType(state, object, true);
3812 }
3813
3814 var type = _toString.call(state.dump);
3815
3816 if (block) {
3817 block = (state.flowLevel < 0 || state.flowLevel > level);
3818 }
3819
3820 var objectOrArray = type === '[object Object]' || type === '[object Array]',
3821 duplicateIndex,
3822 duplicate;
3823
3824 if (objectOrArray) {
3825 duplicateIndex = state.duplicates.indexOf(object);
3826 duplicate = duplicateIndex !== -1;
3827 }
3828
3829 if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
3830 compact = false;
3831 }
3832
3833 if (duplicate && state.usedDuplicates[duplicateIndex]) {
3834 state.dump = '*ref_' + duplicateIndex;
3835 } else {
3836 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
3837 state.usedDuplicates[duplicateIndex] = true;
3838 }
3839 if (type === '[object Object]') {
3840 if (block && (Object.keys(state.dump).length !== 0)) {
3841 writeBlockMapping(state, level, state.dump, compact);
3842 if (duplicate) {
3843 state.dump = '&ref_' + duplicateIndex + state.dump;
3844 }
3845 } else {
3846 writeFlowMapping(state, level, state.dump);
3847 if (duplicate) {
3848 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
3849 }
3850 }
3851 } else if (type === '[object Array]') {
3852 var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
3853 if (block && (state.dump.length !== 0)) {
3854 writeBlockSequence(state, arrayLevel, state.dump, compact);
3855 if (duplicate) {
3856 state.dump = '&ref_' + duplicateIndex + state.dump;
3857 }
3858 } else {
3859 writeFlowSequence(state, arrayLevel, state.dump);
3860 if (duplicate) {
3861 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
3862 }
3863 }
3864 } else if (type === '[object String]') {
3865 if (state.tag !== '?') {
3866 writeScalar(state, state.dump, level, iskey);
3867 }
3868 } else {
3869 if (state.skipInvalid) return false;
3870 throw new YAMLException('unacceptable kind of an object to dump ' + type);
3871 }
3872
3873 if (state.tag !== null && state.tag !== '?') {
3874 state.dump = '!<' + state.tag + '> ' + state.dump;
3875 }
3876 }
3877
3878 return true;
3879}
3880
3881function getDuplicateReferences(object, state) {
3882 var objects = [],
3883 duplicatesIndexes = [],
3884 index,
3885 length;
3886
3887 inspectNode(object, objects, duplicatesIndexes);
3888
3889 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
3890 state.duplicates.push(objects[duplicatesIndexes[index]]);
3891 }
3892 state.usedDuplicates = new Array(length);
3893}
3894
3895function inspectNode(object, objects, duplicatesIndexes) {
3896 var objectKeyList,
3897 index,
3898 length;
3899
3900 if (object !== null && typeof object === 'object') {
3901 index = objects.indexOf(object);
3902 if (index !== -1) {
3903 if (duplicatesIndexes.indexOf(index) === -1) {
3904 duplicatesIndexes.push(index);
3905 }
3906 } else {
3907 objects.push(object);
3908
3909 if (Array.isArray(object)) {
3910 for (index = 0, length = object.length; index < length; index += 1) {
3911 inspectNode(object[index], objects, duplicatesIndexes);
3912 }
3913 } else {
3914 objectKeyList = Object.keys(object);
3915
3916 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3917 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
3918 }
3919 }
3920 }
3921 }
3922}
3923
3924function dump(input, options) {
3925 options = options || {};
3926
3927 var state = new State(options);
3928
3929 if (!state.noRefs) getDuplicateReferences(input, state);
3930
3931 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
3932
3933 return '';
3934}
3935
3936function safeDump(input, options) {
3937 return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
3938}
3939
3940dumper$1.dump = dump;
3941dumper$1.safeDump = safeDump;
3942
3943var loader = loader$1;
3944var dumper = dumper$1;
3945
3946
3947function deprecated(name) {
3948 return function () {
3949 throw new Error('Function ' + name + ' is deprecated and cannot be used.');
3950 };
3951}
3952
3953
3954jsYaml$1.Type = type;
3955jsYaml$1.Schema = schema;
3956jsYaml$1.FAILSAFE_SCHEMA = failsafe;
3957jsYaml$1.JSON_SCHEMA = json;
3958jsYaml$1.CORE_SCHEMA = core;
3959jsYaml$1.DEFAULT_SAFE_SCHEMA = default_safe;
3960jsYaml$1.DEFAULT_FULL_SCHEMA = default_full;
3961jsYaml$1.load = loader.load;
3962jsYaml$1.loadAll = loader.loadAll;
3963jsYaml$1.safeLoad = loader.safeLoad;
3964jsYaml$1.safeLoadAll = loader.safeLoadAll;
3965jsYaml$1.dump = dumper.dump;
3966jsYaml$1.safeDump = dumper.safeDump;
3967jsYaml$1.YAMLException = exception;
3968
3969// Deprecated schema names from JS-YAML 2.0.x
3970jsYaml$1.MINIMAL_SCHEMA = failsafe;
3971jsYaml$1.SAFE_SCHEMA = default_safe;
3972jsYaml$1.DEFAULT_SCHEMA = default_full;
3973
3974// Deprecated functions from JS-YAML 1.x.x
3975jsYaml$1.scan = deprecated('scan');
3976jsYaml$1.parse = deprecated('parse');
3977jsYaml$1.compose = deprecated('compose');
3978jsYaml$1.addConstructor = deprecated('addConstructor');
3979
3980var yaml$1 = jsYaml$1;
3981
3982
3983var jsYaml = yaml$1;
3984
3985var callsites$1 = () => {
3986 const _ = Error.prepareStackTrace;
3987 Error.prepareStackTrace = (_, stack) => stack;
3988 const stack = new Error().stack.slice(1);
3989 Error.prepareStackTrace = _;
3990 return stack;
3991};
3992
3993const callsites = callsites$1;
3994
3995var callerCallsite$1 = () => {
3996 const c = callsites();
3997 let caller;
3998
3999 for (let i = 0; i < c.length; i++) {
4000 const hasReceiver = c[i].getTypeName() !== null;
4001
4002 if (hasReceiver) {
4003 caller = i;
4004 break;
4005 }
4006 }
4007
4008 return c[caller];
4009};
4010
4011const callerCallsite = callerCallsite$1;
4012
4013var callerPath$1 = () => callerCallsite().getFileName();
4014
4015const path$3 = path__default['default'];
4016const resolveFrom = require$$1__default['default'];
4017const callerPath = callerPath$1;
4018
4019var importFresh$1 = moduleId => {
4020 if (typeof moduleId !== 'string') {
4021 throw new TypeError('Expected a string');
4022 }
4023
4024 const filePath = resolveFrom(path$3.dirname(callerPath()), moduleId);
4025
4026 // Delete itself from module parent
4027 if (require.cache[filePath] && require.cache[filePath].parent) {
4028 let i = require.cache[filePath].parent.children.length;
4029
4030 while (i--) {
4031 if (require.cache[filePath].parent.children[i].id === filePath) {
4032 require.cache[filePath].parent.children.splice(i, 1);
4033 }
4034 }
4035 }
4036
4037 // Delete module from cache
4038 delete require.cache[filePath];
4039
4040 // Return fresh module
4041 return commonjsRequire(filePath);
4042};
4043
4044const parseJson = require$$0__default['default'];
4045const yaml = jsYaml;
4046const importFresh = importFresh$1;
4047
4048function loadJs(filepath ) {
4049 const result = importFresh(filepath);
4050 return result;
4051}
4052
4053function loadJson(filepath , content ) {
4054 try {
4055 return parseJson(content);
4056 } catch (err) {
4057 err.message = `JSON Error in ${filepath}:\n${err.message}`;
4058 throw err;
4059 }
4060}
4061
4062function loadYaml(filepath , content ) {
4063 return yaml.safeLoad(content, { filename: filepath });
4064}
4065
4066var loaders$2 = {
4067 loadJs,
4068 loadJson,
4069 loadYaml,
4070};
4071
4072const fs$2 = require$$0__default$1['default'];
4073
4074
4075
4076
4077
4078function readFile$1(filepath , options ) {
4079 options = options || {};
4080 const throwNotFound = options.throwNotFound || false;
4081
4082 return new Promise((resolve, reject) => {
4083 fs$2.readFile(filepath, 'utf8', (err, content) => {
4084 if (err && err.code === 'ENOENT' && !throwNotFound) {
4085 return resolve(null);
4086 }
4087 if (err) return reject(err);
4088 resolve(content);
4089 });
4090 });
4091}
4092
4093readFile$1.sync = function readFileSync(
4094 filepath ,
4095 options
4096) {
4097 options = options || {};
4098 const throwNotFound = options.throwNotFound || false;
4099
4100 try {
4101 return fs$2.readFileSync(filepath, 'utf8');
4102 } catch (err) {
4103 if (err.code === 'ENOENT' && !throwNotFound) {
4104 return null;
4105 }
4106 throw err;
4107 }
4108};
4109
4110var readFile_1 = readFile$1;
4111
4112function cacheWrapper$1 (cache , key , fn ) {
4113 if (!cache) {
4114 return fn();
4115 }
4116
4117 const cached = cache.get(key);
4118 if (cached !== undefined) {
4119 return cached;
4120 }
4121
4122 const result = fn();
4123 cache.set(key, result);
4124 return result;
4125}
4126
4127var cacheWrapper_1 = cacheWrapper$1;
4128
4129/*!
4130 * is-directory <https://github.com/jonschlinkert/is-directory>
4131 *
4132 * Copyright (c) 2014-2015, Jon Schlinkert.
4133 * Licensed under the MIT License.
4134 */
4135
4136var fs$1 = require$$0__default$1['default'];
4137
4138/**
4139 * async
4140 */
4141
4142function isDirectory$1(filepath, cb) {
4143 if (typeof cb !== 'function') {
4144 throw new Error('expected a callback function');
4145 }
4146
4147 if (typeof filepath !== 'string') {
4148 cb(new Error('expected filepath to be a string'));
4149 return;
4150 }
4151
4152 fs$1.stat(filepath, function(err, stats) {
4153 if (err) {
4154 if (err.code === 'ENOENT') {
4155 cb(null, false);
4156 return;
4157 }
4158 cb(err);
4159 return;
4160 }
4161 cb(null, stats.isDirectory());
4162 });
4163}
4164
4165/**
4166 * sync
4167 */
4168
4169isDirectory$1.sync = function isDirectorySync(filepath) {
4170 if (typeof filepath !== 'string') {
4171 throw new Error('expected filepath to be a string');
4172 }
4173
4174 try {
4175 var stat = fs$1.statSync(filepath);
4176 return stat.isDirectory();
4177 } catch (err) {
4178 if (err.code === 'ENOENT') {
4179 return false;
4180 } else {
4181 throw err;
4182 }
4183 }
4184 return false;
4185};
4186
4187/**
4188 * Expose `isDirectory`
4189 */
4190
4191var isDirectory_1 = isDirectory$1;
4192
4193const path$2 = path__default['default'];
4194const isDirectory = isDirectory_1;
4195
4196function getDirectory$1(filepath ) {
4197 return new Promise((resolve, reject) => {
4198 return isDirectory(filepath, (err, filepathIsDirectory) => {
4199 if (err) {
4200 return reject(err);
4201 }
4202 return resolve(filepathIsDirectory ? filepath : path$2.dirname(filepath));
4203 });
4204 });
4205}
4206
4207getDirectory$1.sync = function getDirectorySync(filepath ) {
4208 return isDirectory.sync(filepath) ? filepath : path$2.dirname(filepath);
4209};
4210
4211var getDirectory_1 = getDirectory$1;
4212
4213// Resolves property names or property paths defined with period-delimited
4214// strings or arrays of strings. Property names that are found on the source
4215// object are used directly (even if they include a period).
4216// Nested property names that include periods, within a path, are only
4217// understood in array paths.
4218function getPropertyByPath$1(source , path ) {
4219 if (typeof path === 'string' && source.hasOwnProperty(path)) {
4220 return source[path];
4221 }
4222
4223 const parsedPath = typeof path === 'string' ? path.split('.') : path;
4224 return parsedPath.reduce((previous, key) => {
4225 if (previous === undefined) {
4226 return previous;
4227 }
4228 return previous[key];
4229 }, source);
4230}
4231
4232var getPropertyByPath_1 = getPropertyByPath$1;
4233
4234const path$1 = path__default['default'];
4235const loaders$1 = loaders$2;
4236const readFile = readFile_1;
4237const cacheWrapper = cacheWrapper_1;
4238const getDirectory = getDirectory_1;
4239const getPropertyByPath = getPropertyByPath_1;
4240
4241const MODE_SYNC = 'sync';
4242
4243// An object value represents a config object.
4244// null represents that the loader did not find anything relevant.
4245// undefined represents that the loader found something relevant
4246// but it was empty.
4247
4248
4249class Explorer {
4250
4251
4252
4253
4254
4255
4256 constructor(options ) {
4257 this.loadCache = options.cache ? new Map() : null;
4258 this.loadSyncCache = options.cache ? new Map() : null;
4259 this.searchCache = options.cache ? new Map() : null;
4260 this.searchSyncCache = options.cache ? new Map() : null;
4261 this.config = options;
4262 this.validateConfig();
4263 }
4264
4265 clearLoadCache() {
4266 if (this.loadCache) {
4267 this.loadCache.clear();
4268 }
4269 if (this.loadSyncCache) {
4270 this.loadSyncCache.clear();
4271 }
4272 }
4273
4274 clearSearchCache() {
4275 if (this.searchCache) {
4276 this.searchCache.clear();
4277 }
4278 if (this.searchSyncCache) {
4279 this.searchSyncCache.clear();
4280 }
4281 }
4282
4283 clearCaches() {
4284 this.clearLoadCache();
4285 this.clearSearchCache();
4286 }
4287
4288 validateConfig() {
4289 const config = this.config;
4290
4291 config.searchPlaces.forEach(place => {
4292 const loaderKey = path$1.extname(place) || 'noExt';
4293 const loader = config.loaders[loaderKey];
4294 if (!loader) {
4295 throw new Error(
4296 `No loader specified for ${getExtensionDescription(
4297 place
4298 )}, so searchPlaces item "${place}" is invalid`
4299 );
4300 }
4301 });
4302 }
4303
4304 search(searchFrom ) {
4305 searchFrom = searchFrom || process.cwd();
4306 return getDirectory(searchFrom).then(dir => {
4307 return this.searchFromDirectory(dir);
4308 });
4309 }
4310
4311 searchFromDirectory(dir ) {
4312 const absoluteDir = path$1.resolve(process.cwd(), dir);
4313 const run = () => {
4314 return this.searchDirectory(absoluteDir).then(result => {
4315 const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
4316 if (nextDir) {
4317 return this.searchFromDirectory(nextDir);
4318 }
4319 return this.config.transform(result);
4320 });
4321 };
4322
4323 if (this.searchCache) {
4324 return cacheWrapper(this.searchCache, absoluteDir, run);
4325 }
4326 return run();
4327 }
4328
4329 searchSync(searchFrom ) {
4330 searchFrom = searchFrom || process.cwd();
4331 const dir = getDirectory.sync(searchFrom);
4332 return this.searchFromDirectorySync(dir);
4333 }
4334
4335 searchFromDirectorySync(dir ) {
4336 const absoluteDir = path$1.resolve(process.cwd(), dir);
4337 const run = () => {
4338 const result = this.searchDirectorySync(absoluteDir);
4339 const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
4340 if (nextDir) {
4341 return this.searchFromDirectorySync(nextDir);
4342 }
4343 return this.config.transform(result);
4344 };
4345
4346 if (this.searchSyncCache) {
4347 return cacheWrapper(this.searchSyncCache, absoluteDir, run);
4348 }
4349 return run();
4350 }
4351
4352 searchDirectory(dir ) {
4353 return this.config.searchPlaces.reduce((prevResultPromise, place) => {
4354 return prevResultPromise.then(prevResult => {
4355 if (this.shouldSearchStopWithResult(prevResult)) {
4356 return prevResult;
4357 }
4358 return this.loadSearchPlace(dir, place);
4359 });
4360 }, Promise.resolve(null));
4361 }
4362
4363 searchDirectorySync(dir ) {
4364 let result = null;
4365 for (const place of this.config.searchPlaces) {
4366 result = this.loadSearchPlaceSync(dir, place);
4367 if (this.shouldSearchStopWithResult(result)) break;
4368 }
4369 return result;
4370 }
4371
4372 shouldSearchStopWithResult(result ) {
4373 if (result === null) return false;
4374 if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
4375 return true;
4376 }
4377
4378 loadSearchPlace(dir , place ) {
4379 const filepath = path$1.join(dir, place);
4380 return readFile(filepath).then(content => {
4381 return this.createCosmiconfigResult(filepath, content);
4382 });
4383 }
4384
4385 loadSearchPlaceSync(dir , place ) {
4386 const filepath = path$1.join(dir, place);
4387 const content = readFile.sync(filepath);
4388 return this.createCosmiconfigResultSync(filepath, content);
4389 }
4390
4391 nextDirectoryToSearch(
4392 currentDir ,
4393 currentResult
4394 ) {
4395 if (this.shouldSearchStopWithResult(currentResult)) {
4396 return null;
4397 }
4398 const nextDir = nextDirUp(currentDir);
4399 if (nextDir === currentDir || currentDir === this.config.stopDir) {
4400 return null;
4401 }
4402 return nextDir;
4403 }
4404
4405 loadPackageProp(filepath , content ) {
4406 const parsedContent = loaders$1.loadJson(filepath, content);
4407 const packagePropValue = getPropertyByPath(
4408 parsedContent,
4409 this.config.packageProp
4410 );
4411 return packagePropValue || null;
4412 }
4413
4414 getLoaderEntryForFile(filepath ) {
4415 if (path$1.basename(filepath) === 'package.json') {
4416 const loader = this.loadPackageProp.bind(this);
4417 return { sync: loader, async: loader };
4418 }
4419
4420 const loaderKey = path$1.extname(filepath) || 'noExt';
4421 return this.config.loaders[loaderKey] || {};
4422 }
4423
4424 getSyncLoaderForFile(filepath ) {
4425 const entry = this.getLoaderEntryForFile(filepath);
4426 if (!entry.sync) {
4427 throw new Error(
4428 `No sync loader specified for ${getExtensionDescription(filepath)}`
4429 );
4430 }
4431 return entry.sync;
4432 }
4433
4434 getAsyncLoaderForFile(filepath ) {
4435 const entry = this.getLoaderEntryForFile(filepath);
4436 const loader = entry.async || entry.sync;
4437 if (!loader) {
4438 throw new Error(
4439 `No async loader specified for ${getExtensionDescription(filepath)}`
4440 );
4441 }
4442 return loader;
4443 }
4444
4445 loadFileContent(
4446 mode ,
4447 filepath ,
4448 content
4449 ) {
4450 if (content === null) {
4451 return null;
4452 }
4453 if (content.trim() === '') {
4454 return undefined;
4455 }
4456 const loader =
4457 mode === MODE_SYNC
4458 ? this.getSyncLoaderForFile(filepath)
4459 : this.getAsyncLoaderForFile(filepath);
4460 return loader(filepath, content);
4461 }
4462
4463 loadedContentToCosmiconfigResult(
4464 filepath ,
4465 loadedContent
4466 ) {
4467 if (loadedContent === null) {
4468 return null;
4469 }
4470 if (loadedContent === undefined) {
4471 return { filepath, config: undefined, isEmpty: true };
4472 }
4473 return { config: loadedContent, filepath };
4474 }
4475
4476 createCosmiconfigResult(
4477 filepath ,
4478 content
4479 ) {
4480 return Promise.resolve()
4481 .then(() => {
4482 return this.loadFileContent('async', filepath, content);
4483 })
4484 .then(loaderResult => {
4485 return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
4486 });
4487 }
4488
4489 createCosmiconfigResultSync(
4490 filepath ,
4491 content
4492 ) {
4493 const loaderResult = this.loadFileContent('sync', filepath, content);
4494 return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
4495 }
4496
4497 validateFilePath(filepath ) {
4498 if (!filepath) {
4499 throw new Error('load and loadSync must pass a non-empty string');
4500 }
4501 }
4502
4503 load(filepath ) {
4504 return Promise.resolve().then(() => {
4505 this.validateFilePath(filepath);
4506 const absoluteFilePath = path$1.resolve(process.cwd(), filepath);
4507 return cacheWrapper(this.loadCache, absoluteFilePath, () => {
4508 return readFile(absoluteFilePath, { throwNotFound: true })
4509 .then(content => {
4510 return this.createCosmiconfigResult(absoluteFilePath, content);
4511 })
4512 .then(this.config.transform);
4513 });
4514 });
4515 }
4516
4517 loadSync(filepath ) {
4518 this.validateFilePath(filepath);
4519 const absoluteFilePath = path$1.resolve(process.cwd(), filepath);
4520 return cacheWrapper(this.loadSyncCache, absoluteFilePath, () => {
4521 const content = readFile.sync(absoluteFilePath, { throwNotFound: true });
4522 const result = this.createCosmiconfigResultSync(
4523 absoluteFilePath,
4524 content
4525 );
4526 return this.config.transform(result);
4527 });
4528 }
4529}
4530
4531var createExplorer$1 = function createExplorer(options ) {
4532 const explorer = new Explorer(options);
4533
4534 return {
4535 search: explorer.search.bind(explorer),
4536 searchSync: explorer.searchSync.bind(explorer),
4537 load: explorer.load.bind(explorer),
4538 loadSync: explorer.loadSync.bind(explorer),
4539 clearLoadCache: explorer.clearLoadCache.bind(explorer),
4540 clearSearchCache: explorer.clearSearchCache.bind(explorer),
4541 clearCaches: explorer.clearCaches.bind(explorer),
4542 };
4543};
4544
4545function nextDirUp(dir ) {
4546 return path$1.dirname(dir);
4547}
4548
4549function getExtensionDescription(filepath ) {
4550 const ext = path$1.extname(filepath);
4551 return ext ? `extension "${ext}"` : 'files without extensions';
4552}
4553
4554const os = require$$0__default$2['default'];
4555const createExplorer = createExplorer$1;
4556const loaders = loaders$2;
4557
4558var dist = cosmiconfig;
4559
4560function cosmiconfig(
4561 moduleName ,
4562 options
4563
4564
4565
4566
4567
4568
4569
4570
4571) {
4572 options = options || {};
4573 const defaults = {
4574 packageProp: moduleName,
4575 searchPlaces: [
4576 'package.json',
4577 `.${moduleName}rc`,
4578 `.${moduleName}rc.json`,
4579 `.${moduleName}rc.yaml`,
4580 `.${moduleName}rc.yml`,
4581 `.${moduleName}rc.js`,
4582 `${moduleName}.config.js`,
4583 ],
4584 ignoreEmptySearchPlaces: true,
4585 stopDir: os.homedir(),
4586 cache: true,
4587 transform: identity,
4588 };
4589 const normalizedOptions = Object.assign(
4590 {},
4591 defaults,
4592 options,
4593 {
4594 loaders: normalizeLoaders(options.loaders),
4595 }
4596 );
4597
4598 return createExplorer(normalizedOptions);
4599}
4600
4601cosmiconfig.loadJs = loaders.loadJs;
4602cosmiconfig.loadJson = loaders.loadJson;
4603cosmiconfig.loadYaml = loaders.loadYaml;
4604
4605function normalizeLoaders(rawLoaders ) {
4606 const defaults = {
4607 '.js': { sync: loaders.loadJs, async: loaders.loadJs },
4608 '.json': { sync: loaders.loadJson, async: loaders.loadJson },
4609 '.yaml': { sync: loaders.loadYaml, async: loaders.loadYaml },
4610 '.yml': { sync: loaders.loadYaml, async: loaders.loadYaml },
4611 noExt: { sync: loaders.loadYaml, async: loaders.loadYaml },
4612 };
4613
4614 if (!rawLoaders) {
4615 return defaults;
4616 }
4617
4618 return Object.keys(rawLoaders).reduce((result, ext) => {
4619 const entry = rawLoaders && rawLoaders[ext];
4620 if (typeof entry === 'function') {
4621 result[ext] = { sync: entry, async: entry };
4622 } else {
4623 result[ext] = entry;
4624 }
4625 return result;
4626 }, defaults);
4627}
4628
4629function identity(x) {
4630 return x;
4631}
4632
4633/* eslint-disable complexity */
4634
4635const testExpression = /(^|\/|\\)(?:((?:u[0-9a-f]{4,6},?)+)-)(.+)\.svg$/i;
4636
4637function fileSorter(fileA, fileB) {
4638 const hasUnicodeA = testExpression.test(fileA);
4639 const hasUnicodeB = testExpression.test(fileB);
4640
4641 if (hasUnicodeA == hasUnicodeB) {
4642 // just compare alphabetically
4643 const fileA_ = fileA.substr(0, fileA.lastIndexOf('.'));
4644 const fileB_ = fileB.substr(0, fileB.lastIndexOf('.'));
4645 return fileA_ < fileB_ ? -1 : 1;
4646 } else {
4647 // map true to 0, because we want it to be first
4648 return (hasUnicodeA ? 0 : 1) - (hasUnicodeB ? 0 : 1);
4649 }
4650}
4651
4652var filesorter = fileSorter;
4653
4654var callBind$6 = {exports: {}};
4655
4656/* eslint no-invalid-this: 1 */
4657
4658var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
4659var slice$1 = Array.prototype.slice;
4660var toStr$7 = Object.prototype.toString;
4661var funcType = '[object Function]';
4662
4663var implementation$8 = function bind(that) {
4664 var target = this;
4665 if (typeof target !== 'function' || toStr$7.call(target) !== funcType) {
4666 throw new TypeError(ERROR_MESSAGE + target);
4667 }
4668 var args = slice$1.call(arguments, 1);
4669
4670 var bound;
4671 var binder = function () {
4672 if (this instanceof bound) {
4673 var result = target.apply(
4674 this,
4675 args.concat(slice$1.call(arguments))
4676 );
4677 if (Object(result) === result) {
4678 return result;
4679 }
4680 return this;
4681 } else {
4682 return target.apply(
4683 that,
4684 args.concat(slice$1.call(arguments))
4685 );
4686 }
4687 };
4688
4689 var boundLength = Math.max(0, target.length - args.length);
4690 var boundArgs = [];
4691 for (var i = 0; i < boundLength; i++) {
4692 boundArgs.push('$' + i);
4693 }
4694
4695 bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
4696
4697 if (target.prototype) {
4698 var Empty = function Empty() {};
4699 Empty.prototype = target.prototype;
4700 bound.prototype = new Empty();
4701 Empty.prototype = null;
4702 }
4703
4704 return bound;
4705};
4706
4707var implementation$7 = implementation$8;
4708
4709var functionBind = Function.prototype.bind || implementation$7;
4710
4711/* eslint complexity: [2, 18], max-statements: [2, 33] */
4712var shams = function hasSymbols() {
4713 if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
4714 if (typeof Symbol.iterator === 'symbol') { return true; }
4715
4716 var obj = {};
4717 var sym = Symbol('test');
4718 var symObj = Object(sym);
4719 if (typeof sym === 'string') { return false; }
4720
4721 if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
4722 if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
4723
4724 // temp disabled per https://github.com/ljharb/object.assign/issues/17
4725 // if (sym instanceof Symbol) { return false; }
4726 // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
4727 // if (!(symObj instanceof Symbol)) { return false; }
4728
4729 // if (typeof Symbol.prototype.toString !== 'function') { return false; }
4730 // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
4731
4732 var symVal = 42;
4733 obj[sym] = symVal;
4734 for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
4735 if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
4736
4737 if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
4738
4739 var syms = Object.getOwnPropertySymbols(obj);
4740 if (syms.length !== 1 || syms[0] !== sym) { return false; }
4741
4742 if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
4743
4744 if (typeof Object.getOwnPropertyDescriptor === 'function') {
4745 var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
4746 if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
4747 }
4748
4749 return true;
4750};
4751
4752var origSymbol = typeof Symbol !== 'undefined' && Symbol;
4753var hasSymbolSham = shams;
4754
4755var hasSymbols$4 = function hasNativeSymbols() {
4756 if (typeof origSymbol !== 'function') { return false; }
4757 if (typeof Symbol !== 'function') { return false; }
4758 if (typeof origSymbol('foo') !== 'symbol') { return false; }
4759 if (typeof Symbol('bar') !== 'symbol') { return false; }
4760
4761 return hasSymbolSham();
4762};
4763
4764var bind$1 = functionBind;
4765
4766var src = bind$1.call(Function.call, Object.prototype.hasOwnProperty);
4767
4768var undefined$1;
4769
4770var $SyntaxError = SyntaxError;
4771var $Function = Function;
4772var $TypeError$3 = TypeError;
4773
4774// eslint-disable-next-line consistent-return
4775var getEvalledConstructor = function (expressionSyntax) {
4776 try {
4777 return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
4778 } catch (e) {}
4779};
4780
4781var $gOPD = Object.getOwnPropertyDescriptor;
4782if ($gOPD) {
4783 try {
4784 $gOPD({}, '');
4785 } catch (e) {
4786 $gOPD = null; // this is IE 8, which has a broken gOPD
4787 }
4788}
4789
4790var throwTypeError = function () {
4791 throw new $TypeError$3();
4792};
4793var ThrowTypeError = $gOPD
4794 ? (function () {
4795 try {
4796 // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
4797 arguments.callee; // IE 8 does not throw here
4798 return throwTypeError;
4799 } catch (calleeThrows) {
4800 try {
4801 // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
4802 return $gOPD(arguments, 'callee').get;
4803 } catch (gOPDthrows) {
4804 return throwTypeError;
4805 }
4806 }
4807 }())
4808 : throwTypeError;
4809
4810var hasSymbols$3 = hasSymbols$4();
4811
4812var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
4813
4814var needsEval = {};
4815
4816var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
4817
4818var INTRINSICS = {
4819 '%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
4820 '%Array%': Array,
4821 '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
4822 '%ArrayIteratorPrototype%': hasSymbols$3 ? getProto([][Symbol.iterator]()) : undefined$1,
4823 '%AsyncFromSyncIteratorPrototype%': undefined$1,
4824 '%AsyncFunction%': needsEval,
4825 '%AsyncGenerator%': needsEval,
4826 '%AsyncGeneratorFunction%': needsEval,
4827 '%AsyncIteratorPrototype%': needsEval,
4828 '%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
4829 '%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
4830 '%Boolean%': Boolean,
4831 '%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
4832 '%Date%': Date,
4833 '%decodeURI%': decodeURI,
4834 '%decodeURIComponent%': decodeURIComponent,
4835 '%encodeURI%': encodeURI,
4836 '%encodeURIComponent%': encodeURIComponent,
4837 '%Error%': Error,
4838 '%eval%': eval, // eslint-disable-line no-eval
4839 '%EvalError%': EvalError,
4840 '%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
4841 '%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
4842 '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
4843 '%Function%': $Function,
4844 '%GeneratorFunction%': needsEval,
4845 '%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
4846 '%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
4847 '%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
4848 '%isFinite%': isFinite,
4849 '%isNaN%': isNaN,
4850 '%IteratorPrototype%': hasSymbols$3 ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
4851 '%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
4852 '%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
4853 '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols$3 ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
4854 '%Math%': Math,
4855 '%Number%': Number,
4856 '%Object%': Object,
4857 '%parseFloat%': parseFloat,
4858 '%parseInt%': parseInt,
4859 '%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
4860 '%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
4861 '%RangeError%': RangeError,
4862 '%ReferenceError%': ReferenceError,
4863 '%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
4864 '%RegExp%': RegExp,
4865 '%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
4866 '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols$3 ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
4867 '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
4868 '%String%': String,
4869 '%StringIteratorPrototype%': hasSymbols$3 ? getProto(''[Symbol.iterator]()) : undefined$1,
4870 '%Symbol%': hasSymbols$3 ? Symbol : undefined$1,
4871 '%SyntaxError%': $SyntaxError,
4872 '%ThrowTypeError%': ThrowTypeError,
4873 '%TypedArray%': TypedArray,
4874 '%TypeError%': $TypeError$3,
4875 '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
4876 '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
4877 '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
4878 '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
4879 '%URIError%': URIError,
4880 '%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
4881 '%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
4882 '%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet
4883};
4884
4885var doEval = function doEval(name) {
4886 var value;
4887 if (name === '%AsyncFunction%') {
4888 value = getEvalledConstructor('async function () {}');
4889 } else if (name === '%GeneratorFunction%') {
4890 value = getEvalledConstructor('function* () {}');
4891 } else if (name === '%AsyncGeneratorFunction%') {
4892 value = getEvalledConstructor('async function* () {}');
4893 } else if (name === '%AsyncGenerator%') {
4894 var fn = doEval('%AsyncGeneratorFunction%');
4895 if (fn) {
4896 value = fn.prototype;
4897 }
4898 } else if (name === '%AsyncIteratorPrototype%') {
4899 var gen = doEval('%AsyncGenerator%');
4900 if (gen) {
4901 value = getProto(gen.prototype);
4902 }
4903 }
4904
4905 INTRINSICS[name] = value;
4906
4907 return value;
4908};
4909
4910var LEGACY_ALIASES = {
4911 '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
4912 '%ArrayPrototype%': ['Array', 'prototype'],
4913 '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
4914 '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
4915 '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
4916 '%ArrayProto_values%': ['Array', 'prototype', 'values'],
4917 '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
4918 '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
4919 '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
4920 '%BooleanPrototype%': ['Boolean', 'prototype'],
4921 '%DataViewPrototype%': ['DataView', 'prototype'],
4922 '%DatePrototype%': ['Date', 'prototype'],
4923 '%ErrorPrototype%': ['Error', 'prototype'],
4924 '%EvalErrorPrototype%': ['EvalError', 'prototype'],
4925 '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
4926 '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
4927 '%FunctionPrototype%': ['Function', 'prototype'],
4928 '%Generator%': ['GeneratorFunction', 'prototype'],
4929 '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
4930 '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
4931 '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
4932 '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
4933 '%JSONParse%': ['JSON', 'parse'],
4934 '%JSONStringify%': ['JSON', 'stringify'],
4935 '%MapPrototype%': ['Map', 'prototype'],
4936 '%NumberPrototype%': ['Number', 'prototype'],
4937 '%ObjectPrototype%': ['Object', 'prototype'],
4938 '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
4939 '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
4940 '%PromisePrototype%': ['Promise', 'prototype'],
4941 '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
4942 '%Promise_all%': ['Promise', 'all'],
4943 '%Promise_reject%': ['Promise', 'reject'],
4944 '%Promise_resolve%': ['Promise', 'resolve'],
4945 '%RangeErrorPrototype%': ['RangeError', 'prototype'],
4946 '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
4947 '%RegExpPrototype%': ['RegExp', 'prototype'],
4948 '%SetPrototype%': ['Set', 'prototype'],
4949 '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
4950 '%StringPrototype%': ['String', 'prototype'],
4951 '%SymbolPrototype%': ['Symbol', 'prototype'],
4952 '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
4953 '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
4954 '%TypeErrorPrototype%': ['TypeError', 'prototype'],
4955 '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
4956 '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
4957 '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
4958 '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
4959 '%URIErrorPrototype%': ['URIError', 'prototype'],
4960 '%WeakMapPrototype%': ['WeakMap', 'prototype'],
4961 '%WeakSetPrototype%': ['WeakSet', 'prototype']
4962};
4963
4964var bind = functionBind;
4965var hasOwn = src;
4966var $concat = bind.call(Function.call, Array.prototype.concat);
4967var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
4968var $replace$1 = bind.call(Function.call, String.prototype.replace);
4969var $strSlice$1 = bind.call(Function.call, String.prototype.slice);
4970
4971/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
4972var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
4973var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
4974var stringToPath = function stringToPath(string) {
4975 var first = $strSlice$1(string, 0, 1);
4976 var last = $strSlice$1(string, -1);
4977 if (first === '%' && last !== '%') {
4978 throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
4979 } else if (last === '%' && first !== '%') {
4980 throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
4981 }
4982 var result = [];
4983 $replace$1(string, rePropName, function (match, number, quote, subString) {
4984 result[result.length] = quote ? $replace$1(subString, reEscapeChar, '$1') : number || match;
4985 });
4986 return result;
4987};
4988/* end adaptation */
4989
4990var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
4991 var intrinsicName = name;
4992 var alias;
4993 if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
4994 alias = LEGACY_ALIASES[intrinsicName];
4995 intrinsicName = '%' + alias[0] + '%';
4996 }
4997
4998 if (hasOwn(INTRINSICS, intrinsicName)) {
4999 var value = INTRINSICS[intrinsicName];
5000 if (value === needsEval) {
5001 value = doEval(intrinsicName);
5002 }
5003 if (typeof value === 'undefined' && !allowMissing) {
5004 throw new $TypeError$3('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
5005 }
5006
5007 return {
5008 alias: alias,
5009 name: intrinsicName,
5010 value: value
5011 };
5012 }
5013
5014 throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
5015};
5016
5017var getIntrinsic = function GetIntrinsic(name, allowMissing) {
5018 if (typeof name !== 'string' || name.length === 0) {
5019 throw new $TypeError$3('intrinsic name must be a non-empty string');
5020 }
5021 if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
5022 throw new $TypeError$3('"allowMissing" argument must be a boolean');
5023 }
5024
5025 var parts = stringToPath(name);
5026 var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
5027
5028 var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
5029 var intrinsicRealName = intrinsic.name;
5030 var value = intrinsic.value;
5031 var skipFurtherCaching = false;
5032
5033 var alias = intrinsic.alias;
5034 if (alias) {
5035 intrinsicBaseName = alias[0];
5036 $spliceApply(parts, $concat([0, 1], alias));
5037 }
5038
5039 for (var i = 1, isOwn = true; i < parts.length; i += 1) {
5040 var part = parts[i];
5041 var first = $strSlice$1(part, 0, 1);
5042 var last = $strSlice$1(part, -1);
5043 if (
5044 (
5045 (first === '"' || first === "'" || first === '`')
5046 || (last === '"' || last === "'" || last === '`')
5047 )
5048 && first !== last
5049 ) {
5050 throw new $SyntaxError('property names with quotes must have matching quotes');
5051 }
5052 if (part === 'constructor' || !isOwn) {
5053 skipFurtherCaching = true;
5054 }
5055
5056 intrinsicBaseName += '.' + part;
5057 intrinsicRealName = '%' + intrinsicBaseName + '%';
5058
5059 if (hasOwn(INTRINSICS, intrinsicRealName)) {
5060 value = INTRINSICS[intrinsicRealName];
5061 } else if (value != null) {
5062 if (!(part in value)) {
5063 if (!allowMissing) {
5064 throw new $TypeError$3('base intrinsic for ' + name + ' exists, but the property is not available.');
5065 }
5066 return void undefined$1;
5067 }
5068 if ($gOPD && (i + 1) >= parts.length) {
5069 var desc = $gOPD(value, part);
5070 isOwn = !!desc;
5071
5072 // By convention, when a data property is converted to an accessor
5073 // property to emulate a data property that does not suffer from
5074 // the override mistake, that accessor's getter is marked with
5075 // an `originalValue` property. Here, when we detect this, we
5076 // uphold the illusion by pretending to see that original data
5077 // property, i.e., returning the value rather than the getter
5078 // itself.
5079 if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
5080 value = desc.get;
5081 } else {
5082 value = value[part];
5083 }
5084 } else {
5085 isOwn = hasOwn(value, part);
5086 value = value[part];
5087 }
5088
5089 if (isOwn && !skipFurtherCaching) {
5090 INTRINSICS[intrinsicRealName] = value;
5091 }
5092 }
5093 }
5094 return value;
5095};
5096
5097(function (module) {
5098
5099var bind = functionBind;
5100var GetIntrinsic = getIntrinsic;
5101
5102var $apply = GetIntrinsic('%Function.prototype.apply%');
5103var $call = GetIntrinsic('%Function.prototype.call%');
5104var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
5105
5106var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
5107var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
5108var $max = GetIntrinsic('%Math.max%');
5109
5110if ($defineProperty) {
5111 try {
5112 $defineProperty({}, 'a', { value: 1 });
5113 } catch (e) {
5114 // IE 8 has a broken defineProperty
5115 $defineProperty = null;
5116 }
5117}
5118
5119module.exports = function callBind(originalFunction) {
5120 var func = $reflectApply(bind, $call, arguments);
5121 if ($gOPD && $defineProperty) {
5122 var desc = $gOPD(func, 'length');
5123 if (desc.configurable) {
5124 // original length, plus the receiver, minus any additional arguments (after the receiver)
5125 $defineProperty(
5126 func,
5127 'length',
5128 { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
5129 );
5130 }
5131 }
5132 return func;
5133};
5134
5135var applyBind = function applyBind() {
5136 return $reflectApply(bind, $apply, arguments);
5137};
5138
5139if ($defineProperty) {
5140 $defineProperty(module.exports, 'apply', { value: applyBind });
5141} else {
5142 module.exports.apply = applyBind;
5143}
5144}(callBind$6));
5145
5146// TODO; semver-major: remove
5147
5148var callBind$5 = callBind$6.exports;
5149
5150var toStr$6 = Object.prototype.toString;
5151
5152var isArguments = function isArguments(value) {
5153 var str = toStr$6.call(value);
5154 var isArgs = str === '[object Arguments]';
5155 if (!isArgs) {
5156 isArgs = str !== '[object Array]' &&
5157 value !== null &&
5158 typeof value === 'object' &&
5159 typeof value.length === 'number' &&
5160 value.length >= 0 &&
5161 toStr$6.call(value.callee) === '[object Function]';
5162 }
5163 return isArgs;
5164};
5165
5166var keysShim$1;
5167if (!Object.keys) {
5168 // modified from https://github.com/es-shims/es5-shim
5169 var has = Object.prototype.hasOwnProperty;
5170 var toStr$5 = Object.prototype.toString;
5171 var isArgs$1 = isArguments; // eslint-disable-line global-require
5172 var isEnumerable = Object.prototype.propertyIsEnumerable;
5173 var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
5174 var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
5175 var dontEnums = [
5176 'toString',
5177 'toLocaleString',
5178 'valueOf',
5179 'hasOwnProperty',
5180 'isPrototypeOf',
5181 'propertyIsEnumerable',
5182 'constructor'
5183 ];
5184 var equalsConstructorPrototype = function (o) {
5185 var ctor = o.constructor;
5186 return ctor && ctor.prototype === o;
5187 };
5188 var excludedKeys = {
5189 $applicationCache: true,
5190 $console: true,
5191 $external: true,
5192 $frame: true,
5193 $frameElement: true,
5194 $frames: true,
5195 $innerHeight: true,
5196 $innerWidth: true,
5197 $onmozfullscreenchange: true,
5198 $onmozfullscreenerror: true,
5199 $outerHeight: true,
5200 $outerWidth: true,
5201 $pageXOffset: true,
5202 $pageYOffset: true,
5203 $parent: true,
5204 $scrollLeft: true,
5205 $scrollTop: true,
5206 $scrollX: true,
5207 $scrollY: true,
5208 $self: true,
5209 $webkitIndexedDB: true,
5210 $webkitStorageInfo: true,
5211 $window: true
5212 };
5213 var hasAutomationEqualityBug = (function () {
5214 /* global window */
5215 if (typeof window === 'undefined') { return false; }
5216 for (var k in window) {
5217 try {
5218 if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
5219 try {
5220 equalsConstructorPrototype(window[k]);
5221 } catch (e) {
5222 return true;
5223 }
5224 }
5225 } catch (e) {
5226 return true;
5227 }
5228 }
5229 return false;
5230 }());
5231 var equalsConstructorPrototypeIfNotBuggy = function (o) {
5232 /* global window */
5233 if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
5234 return equalsConstructorPrototype(o);
5235 }
5236 try {
5237 return equalsConstructorPrototype(o);
5238 } catch (e) {
5239 return false;
5240 }
5241 };
5242
5243 keysShim$1 = function keys(object) {
5244 var isObject = object !== null && typeof object === 'object';
5245 var isFunction = toStr$5.call(object) === '[object Function]';
5246 var isArguments = isArgs$1(object);
5247 var isString = isObject && toStr$5.call(object) === '[object String]';
5248 var theKeys = [];
5249
5250 if (!isObject && !isFunction && !isArguments) {
5251 throw new TypeError('Object.keys called on a non-object');
5252 }
5253
5254 var skipProto = hasProtoEnumBug && isFunction;
5255 if (isString && object.length > 0 && !has.call(object, 0)) {
5256 for (var i = 0; i < object.length; ++i) {
5257 theKeys.push(String(i));
5258 }
5259 }
5260
5261 if (isArguments && object.length > 0) {
5262 for (var j = 0; j < object.length; ++j) {
5263 theKeys.push(String(j));
5264 }
5265 } else {
5266 for (var name in object) {
5267 if (!(skipProto && name === 'prototype') && has.call(object, name)) {
5268 theKeys.push(String(name));
5269 }
5270 }
5271 }
5272
5273 if (hasDontEnumBug) {
5274 var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
5275
5276 for (var k = 0; k < dontEnums.length; ++k) {
5277 if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
5278 theKeys.push(dontEnums[k]);
5279 }
5280 }
5281 }
5282 return theKeys;
5283 };
5284}
5285var implementation$6 = keysShim$1;
5286
5287var slice = Array.prototype.slice;
5288var isArgs = isArguments;
5289
5290var origKeys = Object.keys;
5291var keysShim = origKeys ? function keys(o) { return origKeys(o); } : implementation$6;
5292
5293var originalKeys = Object.keys;
5294
5295keysShim.shim = function shimObjectKeys() {
5296 if (Object.keys) {
5297 var keysWorksWithArguments = (function () {
5298 // Safari 5.0 bug
5299 var args = Object.keys(arguments);
5300 return args && args.length === arguments.length;
5301 }(1, 2));
5302 if (!keysWorksWithArguments) {
5303 Object.keys = function keys(object) { // eslint-disable-line func-name-matching
5304 if (isArgs(object)) {
5305 return originalKeys(slice.call(object));
5306 }
5307 return originalKeys(object);
5308 };
5309 }
5310 } else {
5311 Object.keys = keysShim;
5312 }
5313 return Object.keys || keysShim;
5314};
5315
5316var objectKeys = keysShim;
5317
5318var keys = objectKeys;
5319var hasSymbols$2 = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
5320
5321var toStr$4 = Object.prototype.toString;
5322var concat = Array.prototype.concat;
5323var origDefineProperty = Object.defineProperty;
5324
5325var isFunction = function (fn) {
5326 return typeof fn === 'function' && toStr$4.call(fn) === '[object Function]';
5327};
5328
5329var arePropertyDescriptorsSupported = function () {
5330 var obj = {};
5331 try {
5332 origDefineProperty(obj, 'x', { enumerable: false, value: obj });
5333 // eslint-disable-next-line no-unused-vars, no-restricted-syntax
5334 for (var _ in obj) { // jscs:ignore disallowUnusedVariables
5335 return false;
5336 }
5337 return obj.x === obj;
5338 } catch (e) { /* this is IE 8. */
5339 return false;
5340 }
5341};
5342var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
5343
5344var defineProperty = function (object, name, value, predicate) {
5345 if (name in object && (!isFunction(predicate) || !predicate())) {
5346 return;
5347 }
5348 if (supportsDescriptors) {
5349 origDefineProperty(object, name, {
5350 configurable: true,
5351 enumerable: false,
5352 value: value,
5353 writable: true
5354 });
5355 } else {
5356 object[name] = value;
5357 }
5358};
5359
5360var defineProperties = function (object, map) {
5361 var predicates = arguments.length > 2 ? arguments[2] : {};
5362 var props = keys(map);
5363 if (hasSymbols$2) {
5364 props = concat.call(props, Object.getOwnPropertySymbols(map));
5365 }
5366 for (var i = 0; i < props.length; i += 1) {
5367 defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
5368 }
5369};
5370
5371defineProperties.supportsDescriptors = !!supportsDescriptors;
5372
5373var defineProperties_1 = defineProperties;
5374
5375var GetIntrinsic$6 = getIntrinsic;
5376
5377var callBind$4 = callBind$6.exports;
5378
5379var $indexOf = callBind$4(GetIntrinsic$6('String.prototype.indexOf'));
5380
5381var callBound$4 = function callBoundIntrinsic(name, allowMissing) {
5382 var intrinsic = GetIntrinsic$6(name, !!allowMissing);
5383 if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
5384 return callBind$4(intrinsic);
5385 }
5386 return intrinsic;
5387};
5388
5389var GetIntrinsic$5 = getIntrinsic;
5390
5391var $test = GetIntrinsic$5('RegExp.prototype.test');
5392
5393var callBind$3 = callBind$6.exports;
5394
5395var regexTester$1 = function regexTester(regex) {
5396 return callBind$3($test, regex);
5397};
5398
5399var isPrimitive$4 = function isPrimitive(value) {
5400 return value === null || (typeof value !== 'function' && typeof value !== 'object');
5401};
5402
5403var isPrimitive$3 = function isPrimitive(value) {
5404 return value === null || (typeof value !== 'function' && typeof value !== 'object');
5405};
5406
5407var fnToStr = Function.prototype.toString;
5408var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
5409var badArrayLike;
5410var isCallableMarker;
5411if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
5412 try {
5413 badArrayLike = Object.defineProperty({}, 'length', {
5414 get: function () {
5415 throw isCallableMarker;
5416 }
5417 });
5418 isCallableMarker = {};
5419 // eslint-disable-next-line no-throw-literal
5420 reflectApply(function () { throw 42; }, null, badArrayLike);
5421 } catch (_) {
5422 if (_ !== isCallableMarker) {
5423 reflectApply = null;
5424 }
5425 }
5426} else {
5427 reflectApply = null;
5428}
5429
5430var constructorRegex = /^\s*class\b/;
5431var isES6ClassFn = function isES6ClassFunction(value) {
5432 try {
5433 var fnStr = fnToStr.call(value);
5434 return constructorRegex.test(fnStr);
5435 } catch (e) {
5436 return false; // not a function
5437 }
5438};
5439
5440var tryFunctionObject = function tryFunctionToStr(value) {
5441 try {
5442 if (isES6ClassFn(value)) { return false; }
5443 fnToStr.call(value);
5444 return true;
5445 } catch (e) {
5446 return false;
5447 }
5448};
5449var toStr$3 = Object.prototype.toString;
5450var fnClass = '[object Function]';
5451var genClass = '[object GeneratorFunction]';
5452var hasToStringTag$1 = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
5453/* globals document: false */
5454var documentDotAll = typeof document === 'object' && typeof document.all === 'undefined' && document.all !== undefined ? document.all : {};
5455
5456var isCallable$2 = reflectApply
5457 ? function isCallable(value) {
5458 if (value === documentDotAll) { return true; }
5459 if (!value) { return false; }
5460 if (typeof value !== 'function' && typeof value !== 'object') { return false; }
5461 if (typeof value === 'function' && !value.prototype) { return true; }
5462 try {
5463 reflectApply(value, null, badArrayLike);
5464 } catch (e) {
5465 if (e !== isCallableMarker) { return false; }
5466 }
5467 return !isES6ClassFn(value);
5468 }
5469 : function isCallable(value) {
5470 if (value === documentDotAll) { return true; }
5471 if (!value) { return false; }
5472 if (typeof value !== 'function' && typeof value !== 'object') { return false; }
5473 if (typeof value === 'function' && !value.prototype) { return true; }
5474 if (hasToStringTag$1) { return tryFunctionObject(value); }
5475 if (isES6ClassFn(value)) { return false; }
5476 var strClass = toStr$3.call(value);
5477 return strClass === fnClass || strClass === genClass;
5478 };
5479
5480var getDay = Date.prototype.getDay;
5481var tryDateObject = function tryDateGetDayCall(value) {
5482 try {
5483 getDay.call(value);
5484 return true;
5485 } catch (e) {
5486 return false;
5487 }
5488};
5489
5490var toStr$2 = Object.prototype.toString;
5491var dateClass = '[object Date]';
5492var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag;
5493
5494var isDateObject = function isDateObject(value) {
5495 if (typeof value !== 'object' || value === null) {
5496 return false;
5497 }
5498 return hasToStringTag ? tryDateObject(value) : toStr$2.call(value) === dateClass;
5499};
5500
5501var isSymbol$1 = {exports: {}};
5502
5503var toStr$1 = Object.prototype.toString;
5504var hasSymbols$1 = hasSymbols$4();
5505
5506if (hasSymbols$1) {
5507 var symToStr = Symbol.prototype.toString;
5508 var symStringRegex = /^Symbol\(.*\)$/;
5509 var isSymbolObject = function isRealSymbolObject(value) {
5510 if (typeof value.valueOf() !== 'symbol') {
5511 return false;
5512 }
5513 return symStringRegex.test(symToStr.call(value));
5514 };
5515
5516 isSymbol$1.exports = function isSymbol(value) {
5517 if (typeof value === 'symbol') {
5518 return true;
5519 }
5520 if (toStr$1.call(value) !== '[object Symbol]') {
5521 return false;
5522 }
5523 try {
5524 return isSymbolObject(value);
5525 } catch (e) {
5526 return false;
5527 }
5528 };
5529} else {
5530
5531 isSymbol$1.exports = function isSymbol(value) {
5532 // this environment does not support Symbols.
5533 return false ;
5534 };
5535}
5536
5537var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
5538
5539var isPrimitive$2 = isPrimitive$3;
5540var isCallable$1 = isCallable$2;
5541var isDate = isDateObject;
5542var isSymbol = isSymbol$1.exports;
5543
5544var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) {
5545 if (typeof O === 'undefined' || O === null) {
5546 throw new TypeError('Cannot call method on ' + O);
5547 }
5548 if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) {
5549 throw new TypeError('hint must be "string" or "number"');
5550 }
5551 var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
5552 var method, result, i;
5553 for (i = 0; i < methodNames.length; ++i) {
5554 method = O[methodNames[i]];
5555 if (isCallable$1(method)) {
5556 result = method.call(O);
5557 if (isPrimitive$2(result)) {
5558 return result;
5559 }
5560 }
5561 }
5562 throw new TypeError('No default value');
5563};
5564
5565var GetMethod = function GetMethod(O, P) {
5566 var func = O[P];
5567 if (func !== null && typeof func !== 'undefined') {
5568 if (!isCallable$1(func)) {
5569 throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function');
5570 }
5571 return func;
5572 }
5573 return void 0;
5574};
5575
5576// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
5577var es2015 = function ToPrimitive(input) {
5578 if (isPrimitive$2(input)) {
5579 return input;
5580 }
5581 var hint = 'default';
5582 if (arguments.length > 1) {
5583 if (arguments[1] === String) {
5584 hint = 'string';
5585 } else if (arguments[1] === Number) {
5586 hint = 'number';
5587 }
5588 }
5589
5590 var exoticToPrim;
5591 if (hasSymbols) {
5592 if (Symbol.toPrimitive) {
5593 exoticToPrim = GetMethod(input, Symbol.toPrimitive);
5594 } else if (isSymbol(input)) {
5595 exoticToPrim = Symbol.prototype.valueOf;
5596 }
5597 }
5598 if (typeof exoticToPrim !== 'undefined') {
5599 var result = exoticToPrim.call(input, hint);
5600 if (isPrimitive$2(result)) {
5601 return result;
5602 }
5603 throw new TypeError('unable to convert exotic object to primitive');
5604 }
5605 if (hint === 'default' && (isDate(input) || isSymbol(input))) {
5606 hint = 'string';
5607 }
5608 return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
5609};
5610
5611var toPrimitive = es2015;
5612
5613// https://ecma-international.org/ecma-262/6.0/#sec-toprimitive
5614
5615var ToPrimitive$3 = function ToPrimitive(input) {
5616 if (arguments.length > 1) {
5617 return toPrimitive(input, arguments[1]);
5618 }
5619 return toPrimitive(input);
5620};
5621
5622var GetIntrinsic$4 = getIntrinsic;
5623
5624var $TypeError$2 = GetIntrinsic$4('%TypeError%');
5625var $Number = GetIntrinsic$4('%Number%');
5626var $RegExp = GetIntrinsic$4('%RegExp%');
5627var $parseInteger = GetIntrinsic$4('%parseInt%');
5628
5629var callBound$3 = callBound$4;
5630var regexTester = regexTester$1;
5631var isPrimitive$1 = isPrimitive$4;
5632
5633var $strSlice = callBound$3('String.prototype.slice');
5634var isBinary = regexTester(/^0b[01]+$/i);
5635var isOctal = regexTester(/^0o[0-7]+$/i);
5636var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
5637var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
5638var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
5639var hasNonWS = regexTester(nonWSregex);
5640
5641// whitespace from: https://es5.github.io/#x15.5.4.20
5642// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
5643var ws = [
5644 '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
5645 '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
5646 '\u2029\uFEFF'
5647].join('');
5648var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
5649var $replace = callBound$3('String.prototype.replace');
5650var $trim = function (value) {
5651 return $replace(value, trimRegex, '');
5652};
5653
5654var ToPrimitive$2 = ToPrimitive$3;
5655
5656// https://ecma-international.org/ecma-262/6.0/#sec-tonumber
5657
5658var ToNumber$4 = function ToNumber(argument) {
5659 var value = isPrimitive$1(argument) ? argument : ToPrimitive$2(argument, $Number);
5660 if (typeof value === 'symbol') {
5661 throw new $TypeError$2('Cannot convert a Symbol value to a number');
5662 }
5663 if (typeof value === 'string') {
5664 if (isBinary(value)) {
5665 return ToNumber($parseInteger($strSlice(value, 2), 2));
5666 } else if (isOctal(value)) {
5667 return ToNumber($parseInteger($strSlice(value, 2), 8));
5668 } else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
5669 return NaN;
5670 } else {
5671 var trimmed = $trim(value);
5672 if (trimmed !== value) {
5673 return ToNumber(trimmed);
5674 }
5675 }
5676 }
5677 return $Number(value);
5678};
5679
5680var GetIntrinsic$3 = getIntrinsic;
5681
5682var $abs$1 = GetIntrinsic$3('%Math.abs%');
5683
5684// http://262.ecma-international.org/5.1/#sec-5.2
5685
5686var abs$3 = function abs(x) {
5687 return $abs$1(x);
5688};
5689
5690// var modulo = require('./modulo');
5691var $floor$1 = Math.floor;
5692
5693// http://262.ecma-international.org/5.1/#sec-5.2
5694
5695var floor$3 = function floor(x) {
5696 // return x - modulo(x, 1);
5697 return $floor$1(x);
5698};
5699
5700var _isNaN = Number.isNaN || function isNaN(a) {
5701 return a !== a;
5702};
5703
5704var $isNaN$2 = Number.isNaN || function (a) { return a !== a; };
5705
5706var _isFinite = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN$2(x) && x !== Infinity && x !== -Infinity; };
5707
5708var abs$2 = abs$3;
5709var floor$2 = floor$3;
5710
5711var $isNaN$1 = _isNaN;
5712var $isFinite$1 = _isFinite;
5713
5714// https://ecma-international.org/ecma-262/6.0/#sec-isinteger
5715
5716var IsInteger$1 = function IsInteger(argument) {
5717 if (typeof argument !== 'number' || $isNaN$1(argument) || !$isFinite$1(argument)) {
5718 return false;
5719 }
5720 var absValue = abs$2(argument);
5721 return floor$2(absValue) === absValue;
5722};
5723
5724// TODO; semver-major: remove
5725
5726var callBound$2 = callBound$4;
5727
5728/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5729
5730var ToNumber$3 = ToNumber$4;
5731var IsInteger = IsInteger$1;
5732var callBound$1 = callBound$2;
5733var callBind$2 = callBind$5;
5734
5735var ArrayPush = callBound$1('Array.prototype.push');
5736var StringFromCharCodeSpread = callBind$2.apply(String.fromCharCode, null);
5737
5738var implementation$5 = function fromCodePoint(_ /* fromCodePoint.length is 1 */) {
5739 var MAX_SIZE = 0x4000;
5740 var codeUnits = [];
5741 var highSurrogate;
5742 var lowSurrogate;
5743 var index = -1;
5744 var length = arguments.length;
5745 if (!length) {
5746 return '';
5747 }
5748 var result = '';
5749 while (++index < length) {
5750 var codePoint = ToNumber$3(arguments[index]);
5751 if (
5752 !IsInteger(codePoint) ||
5753 codePoint < 0 || codePoint > 0x10FFFF // not a valid Unicode code point
5754 ) {
5755 throw RangeError('Invalid code point: ' + codePoint);
5756 }
5757 if (codePoint <= 0xFFFF) { // BMP code point
5758 ArrayPush(codeUnits, codePoint);
5759 } else { // Astral code point; split in surrogate halves
5760 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
5761 codePoint -= 0x10000;
5762 highSurrogate = (codePoint >> 10) + 0xD800;
5763 lowSurrogate = (codePoint % 0x400) + 0xDC00;
5764 ArrayPush(codeUnits, highSurrogate, lowSurrogate);
5765 }
5766 if (index + 1 == length || codeUnits.length > MAX_SIZE) {
5767 result += StringFromCharCodeSpread(codeUnits);
5768 codeUnits.length = 0;
5769 }
5770 }
5771 return result;
5772};
5773
5774/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5775
5776var implementation$4 = implementation$5;
5777
5778var polyfill$1 = function getPolyfill() {
5779 return String.fromCodePoint || implementation$4;
5780};
5781
5782/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5783
5784var define$3 = defineProperties_1;
5785
5786var getPolyfill$3 = polyfill$1;
5787
5788var shim$3 = function shimFromCodePoint() {
5789 var polyfill = getPolyfill$3();
5790
5791 if (String.fromCodePoint !== polyfill) {
5792 define$3(String, { fromCodePoint: polyfill });
5793 }
5794
5795 return polyfill;
5796};
5797
5798/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5799
5800var callBind$1 = callBind$5;
5801var define$2 = defineProperties_1;
5802
5803var implementation$3 = implementation$5;
5804var getPolyfill$2 = polyfill$1;
5805var shim$2 = shim$3;
5806
5807var boundFromCodePoint = callBind$1(getPolyfill$2(), String);
5808
5809define$2(boundFromCodePoint, {
5810 getPolyfill: getPolyfill$2,
5811 implementation: implementation$3,
5812 shim: shim$2
5813});
5814
5815var GetIntrinsic$2 = getIntrinsic;
5816
5817var $TypeError$1 = GetIntrinsic$2('%TypeError%');
5818
5819// http://262.ecma-international.org/5.1/#sec-9.10
5820
5821var CheckObjectCoercible = function CheckObjectCoercible(value, optMessage) {
5822 if (value == null) {
5823 throw new $TypeError$1(optMessage || ('Cannot call method on ' + value));
5824 }
5825 return value;
5826};
5827
5828var RequireObjectCoercible$1 = CheckObjectCoercible;
5829
5830var GetIntrinsic$1 = getIntrinsic;
5831
5832var $String = GetIntrinsic$1('%String%');
5833var $TypeError = GetIntrinsic$1('%TypeError%');
5834
5835// https://ecma-international.org/ecma-262/6.0/#sec-tostring
5836
5837var ToString$1 = function ToString(argument) {
5838 if (typeof argument === 'symbol') {
5839 throw new $TypeError('Cannot convert a Symbol value to a string');
5840 }
5841 return $String(argument);
5842};
5843
5844var GetIntrinsic = getIntrinsic;
5845
5846var $abs = GetIntrinsic('%Math.abs%');
5847
5848// http://262.ecma-international.org/5.1/#sec-5.2
5849
5850var abs$1 = function abs(x) {
5851 return $abs(x);
5852};
5853
5854// var modulo = require('./modulo');
5855var $floor = Math.floor;
5856
5857// http://262.ecma-international.org/5.1/#sec-5.2
5858
5859var floor$1 = function floor(x) {
5860 // return x - modulo(x, 1);
5861 return $floor(x);
5862};
5863
5864var toStr = Object.prototype.toString;
5865
5866var isPrimitive = isPrimitive$3;
5867
5868var isCallable = isCallable$2;
5869
5870// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
5871var ES5internalSlots = {
5872 '[[DefaultValue]]': function (O) {
5873 var actualHint;
5874 if (arguments.length > 1) {
5875 actualHint = arguments[1];
5876 } else {
5877 actualHint = toStr.call(O) === '[object Date]' ? String : Number;
5878 }
5879
5880 if (actualHint === String || actualHint === Number) {
5881 var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
5882 var value, i;
5883 for (i = 0; i < methods.length; ++i) {
5884 if (isCallable(O[methods[i]])) {
5885 value = O[methods[i]]();
5886 if (isPrimitive(value)) {
5887 return value;
5888 }
5889 }
5890 }
5891 throw new TypeError('No default value');
5892 }
5893 throw new TypeError('invalid [[DefaultValue]] hint supplied');
5894 }
5895};
5896
5897// http://ecma-international.org/ecma-262/5.1/#sec-9.1
5898var es5 = function ToPrimitive(input) {
5899 if (isPrimitive(input)) {
5900 return input;
5901 }
5902 if (arguments.length > 1) {
5903 return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
5904 }
5905 return ES5internalSlots['[[DefaultValue]]'](input);
5906};
5907
5908// http://262.ecma-international.org/5.1/#sec-9.1
5909
5910var ToPrimitive$1 = es5;
5911
5912var ToPrimitive = ToPrimitive$1;
5913
5914// http://262.ecma-international.org/5.1/#sec-9.3
5915
5916var ToNumber$2 = function ToNumber(value) {
5917 var prim = ToPrimitive(value, Number);
5918 if (typeof prim !== 'string') {
5919 return +prim; // eslint-disable-line no-implicit-coercion
5920 }
5921
5922 // eslint-disable-next-line no-control-regex
5923 var trimmed = prim.replace(/^[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+|[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+$/g, '');
5924 if ((/^0[ob]|^[+-]0x/).test(trimmed)) {
5925 return NaN;
5926 }
5927
5928 return +trimmed; // eslint-disable-line no-implicit-coercion
5929};
5930
5931var sign = function sign(number) {
5932 return number >= 0 ? 1 : -1;
5933};
5934
5935var abs = abs$1;
5936var floor = floor$1;
5937var ToNumber$1 = ToNumber$2;
5938
5939var $isNaN = _isNaN;
5940var $isFinite = _isFinite;
5941var $sign = sign;
5942
5943// http://262.ecma-international.org/5.1/#sec-9.4
5944
5945var ToInteger$2 = function ToInteger(value) {
5946 var number = ToNumber$1(value);
5947 if ($isNaN(number)) { return 0; }
5948 if (number === 0 || !$isFinite(number)) { return number; }
5949 return $sign(number) * floor(abs(number));
5950};
5951
5952var ES5ToInteger = ToInteger$2;
5953
5954var ToNumber = ToNumber$4;
5955
5956// https://ecma-international.org/ecma-262/6.0/#sec-tointeger
5957
5958var ToInteger$1 = function ToInteger(value) {
5959 var number = ToNumber(value);
5960 return ES5ToInteger(number);
5961};
5962
5963/*! https://mths.be/codepointat v1.0.0 by @mathias */
5964
5965var callBound = callBound$2;
5966var RequireObjectCoercible = RequireObjectCoercible$1;
5967var ToString = ToString$1;
5968var ToInteger = ToInteger$1;
5969var StringCharCodeAt = callBound('String.prototype.charCodeAt');
5970
5971var implementation$2 = function codePointAt(position) {
5972 var O = RequireObjectCoercible(this);
5973 var string = ToString(O);
5974 var size = string.length;
5975 var index = ToInteger(position);
5976 // Account for out-of-bounds indices:
5977 if (index < 0 || index >= size) {
5978 return undefined;
5979 }
5980 // Get the first code unit
5981 var first = StringCharCodeAt(string, index);
5982 var second;
5983 if ( // check if it’s the start of a surrogate pair
5984 first >= 0xD800 && first <= 0xDBFF && // high surrogate
5985 size > index + 1 // there is a next code unit
5986 ) {
5987 second = StringCharCodeAt(string, index + 1);
5988 if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
5989 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
5990 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
5991 }
5992 }
5993 return first;
5994};
5995
5996/*! https://mths.be/codepointat v1.0.0 by @mathias */
5997
5998var implementation$1 = implementation$2;
5999
6000var polyfill = function getPolyfill() {
6001 return String.prototype.codePointAt || implementation$1;
6002};
6003
6004/*! https://mths.be/codepointat v1.0.0 by @mathias */
6005
6006var define$1 = defineProperties_1;
6007
6008var getPolyfill$1 = polyfill;
6009
6010var shim$1 = function shimCodePointAt() {
6011 var polyfill = getPolyfill$1();
6012
6013 if (String.prototype.codePointAt !== polyfill) {
6014 define$1(String.prototype, { codePointAt: polyfill });
6015 }
6016
6017 return polyfill;
6018};
6019
6020/*! https://mths.be/codepointat v1.0.0 by @mathias */
6021
6022var callBind = callBind$5;
6023var define = defineProperties_1;
6024
6025var implementation = implementation$2;
6026var getPolyfill = polyfill;
6027var shim = shim$1;
6028
6029var boundCodePointAt = callBind(getPolyfill());
6030
6031define(boundCodePointAt, {
6032 getPolyfill: getPolyfill,
6033 implementation: implementation,
6034 shim: shim
6035});
6036
6037/* eslint-disable prefer-template,newline-per-chained-call,complexity */
6038
6039const path = path__default['default'];
6040const fs = require$$0__default$1['default'];
6041
6042
6043
6044
6045function getMetadataService(options = {}) {
6046 let usedUnicodes = [];
6047
6048 // Default options
6049 options.prependUnicode = !!options.prependUnicode;
6050 options.startUnicode =
6051 'number' === typeof options.startUnicode ? options.startUnicode : 0xea01;
6052 options.log = options.log || console.log; // eslint-disable-line
6053 options.err = options.err || console.err; // eslint-disable-line
6054
6055 // Throw on old options usage
6056 if ('undefined' !== typeof options.appendUnicode) {
6057 throw new Error(
6058 'The "appendUnicode" option was renamed "prependUnicode".' +
6059 ' See https://github.com/nfroidure/gulp-svgicons2svgfont/issues/33'
6060 );
6061 }
6062
6063 return function getMetadataFromFile(file, cb) {
6064 const basename = path.basename(file);
6065 const metadata = {
6066 path: file,
6067 name: '',
6068 unicode: [],
6069 renamed: false,
6070 };
6071 const matches = basename.match(/^(?:((?:u[0-9a-f]{4,6},?)+)-)?(.+)\.svg$/i);
6072
6073 metadata.name =
6074 matches && matches[2] ? matches[2] : 'icon' + options.startUnicode;
6075 if (matches && matches[1]) {
6076 metadata.unicode = matches[1].split(',').map((match) => {
6077 match = match.substr(1);
6078 return match
6079 .split('u')
6080 .map((code) => String.fromCodePoint(parseInt(code, 16)))
6081 .join('');
6082 });
6083 if (-1 !== usedUnicodes.indexOf(metadata.unicode[0])) {
6084 cb(
6085 new Error(
6086 'The unicode codepoint of the glyph ' +
6087 metadata.name +
6088 ' seems to be already used by another glyph.'
6089 )
6090 );
6091 return;
6092 }
6093 usedUnicodes.push(...metadata.unicode);
6094 } else {
6095 do {
6096 metadata.unicode[0] = String.fromCodePoint(options.startUnicode++);
6097 } while (usedUnicodes.includes(metadata.unicode[0]));
6098 usedUnicodes.push(metadata.unicode[0]);
6099 if (options.prependUnicode) {
6100 metadata.renamed = true;
6101 metadata.path = path.join(
6102 path.dirname(file),
6103 'u' +
6104 metadata.unicode[0].codePointAt(0).toString(16).toUpperCase() +
6105 '-' +
6106 basename
6107 );
6108 fs.rename(file, metadata.path, (err) => {
6109 if (err) {
6110 cb(
6111 new Error(
6112 'Could not save codepoint: ' +
6113 'u' +
6114 metadata.unicode[0]
6115 .codePointAt(0)
6116 .toString(16)
6117 .toUpperCase() +
6118 ' for ' +
6119 basename
6120 )
6121 );
6122 return;
6123 }
6124 cb(null, metadata);
6125 });
6126 }
6127 }
6128 if (!metadata.renamed) {
6129 setImmediate(() => cb(null, metadata));
6130 }
6131 };
6132}
6133
6134var metadata = getMetadataService;
6135
6136var buildConfig = function (options) { return __awaiter(void 0, void 0, void 0, function () {
6137 var searchPath, configPath, configExplorer, config;
6138 return __generator(this, function (_a) {
6139 switch (_a.label) {
6140 case 0:
6141 searchPath = process.cwd();
6142 configPath = null;
6143 if (options.configFile) {
6144 searchPath = null;
6145 configPath = path__default['default'].resolve(process.cwd(), options.configFile);
6146 }
6147 configExplorer = dist("webfont");
6148 return [4 /*yield*/, configExplorer.search(searchPath)];
6149 case 1:
6150 config = _a.sent();
6151 if (!configPath) return [3 /*break*/, 3];
6152 return [4 /*yield*/, configExplorer.load(configPath)];
6153 case 2:
6154 config = _a.sent();
6155 _a.label = 3;
6156 case 3:
6157 if (!config) {
6158 return [2 /*return*/, {}];
6159 }
6160 return [2 /*return*/, config];
6161 }
6162 });
6163}); };
6164var getGlyphsData = function (files, options) {
6165 var metadataProvider = options.metadataProvider ||
6166 metadata({
6167 prependUnicode: options.prependUnicode,
6168 startUnicode: options.startUnicode
6169 });
6170 var xmlParser = new xml2js__default['default'].Parser();
6171 var throttle = pLimit__default['default'](options.maxConcurrency);
6172 return Promise.all(files.map(function (srcPath) { return throttle(function () { return new Promise(function (resolve, reject) {
6173 var glyph = require$$0__default$1['default'].createReadStream(srcPath);
6174 var glyphContents = "";
6175 // eslint-disable-next-line no-promise-executor-return
6176 return glyph.
6177 on("error", function (glyphError) { return reject(glyphError); }).
6178 on("data", function (data) {
6179 glyphContents += data.toString();
6180 }).
6181 on("end", function () {
6182 // Maybe bug in xml2js
6183 if (glyphContents.length === 0) {
6184 return reject(new Error("Empty file " + srcPath));
6185 }
6186 return xmlParser.parseString(glyphContents, function (error) {
6187 if (error) {
6188 return reject(error);
6189 }
6190 var glyphData = {
6191 contents: glyphContents,
6192 srcPath: srcPath
6193 };
6194 return resolve(glyphData);
6195 });
6196 });
6197 }); }); })).then(function (glyphsData) {
6198 var sortedGlyphsData = glyphsData;
6199 if (options.sort) {
6200 var sortCallback = function (fileA, fileB) { return filesorter(fileA.srcPath, fileB.srcPath); };
6201 sortedGlyphsData = glyphsData.sort(sortCallback);
6202 }
6203 return Promise.all(sortedGlyphsData.map(function (glyphData) { return new Promise(function (resolve, reject) {
6204 metadataProvider(glyphData.srcPath, function (error, metadata) {
6205 if (error) {
6206 return reject(error);
6207 }
6208 metadata.unicode.push(metadata.name.replace(/-/gu, "_"));
6209 glyphData.metadata = metadata;
6210 return resolve(glyphData);
6211 });
6212 }); }));
6213 });
6214};
6215var toSvg = function (glyphsData, options) {
6216 var result = "";
6217 return new Promise(function (resolve, reject) {
6218 var log = function () {
6219 Function.prototype();
6220 };
6221 if (options.verbose) {
6222 // eslint-disable-next-line no-console
6223 log = console.log.bind(console);
6224 }
6225 var fontStream = new SVGIcons2SVGFontStream__default['default']({
6226 ascent: options.ascent,
6227 centerHorizontally: options.centerHorizontally,
6228 descent: options.descent,
6229 fixedWidth: options.fixedWidth,
6230 fontHeight: options.fontHeight,
6231 fontId: options.fontId,
6232 fontName: options.fontName,
6233 fontStyle: options.fontStyle,
6234 fontWeight: options.fontWeight,
6235 log: log,
6236 metadata: options.metadata,
6237 normalize: options.normalize,
6238 round: options.round
6239 }).
6240 on("finish", function () { return resolve(result); }).
6241 on("data", function (data) {
6242 result += data;
6243 }).
6244 on("error", function (error) { return reject(error); });
6245 glyphsData.forEach(function (glyphData) {
6246 var glyphStream = new stream.Readable();
6247 glyphStream.push(glyphData.contents);
6248 glyphStream.push(null);
6249 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
6250 // @ts-ignore
6251 glyphStream.metadata = glyphData.metadata;
6252 fontStream.write(glyphStream);
6253 });
6254 fontStream.end();
6255 });
6256};
6257var toTtf = function (buffer, options) { return Buffer.from(svg2ttf__default['default'](buffer, options).buffer); };
6258var toEot = function (buffer) { return Buffer.from(ttf2eot__default['default'](buffer).buffer); };
6259var toWoff = function (buffer, options) { return Buffer.from(ttf2woff__default['default'](buffer, options).buffer); };
6260var toWoff2 = function (buffer) { return wawoff2__default['default'].compress(buffer); };
6261var webfont = function (initialOptions) { return __awaiter(void 0, void 0, void 0, function () {
6262 var options, config, foundFiles, filteredFiles, glyphsData, ttfOptions, svg, ttf, result, _a, builtInTemplates, templateFilePath, builtInPath, resolvedTemplateFilePath, hashOption, nunjucksOptions;
6263 return __generator(this, function (_b) {
6264 switch (_b.label) {
6265 case 0:
6266 if (!initialOptions || !initialOptions.files) {
6267 throw new Error("You must pass webfont a `files` glob");
6268 }
6269 options = __assign({ centerHorizontally: false, descent: 0, fixedWidth: false, fontHeight: null, fontId: null, fontName: "webfont", fontStyle: "", fontWeight: "", formats: ["svg", "ttf", "eot", "woff", "woff2"], formatsOptions: {
6270 ttf: {
6271 copyright: null,
6272 ts: null,
6273 version: null
6274 }
6275 }, glyphTransformFn: null,
6276 /*
6277 * Maybe allow setup from CLI
6278 * This is usually less than file read maximums while staying performance
6279 */
6280 maxConcurrency: 100, metadata: null, metadataProvider: null, normalize: false, prependUnicode: false, round: 10e12, sort: true, startUnicode: 0xea01, template: null, templateCacheString: null, templateClassName: null, templateFontName: null, templateFontPath: "./", verbose: false }, initialOptions);
6281 return [4 /*yield*/, buildConfig({
6282 configFile: options.configFile
6283 })];
6284 case 1:
6285 config = _b.sent();
6286 if (Object.keys(config).length > 0) {
6287 // eslint-disable-next-line require-atomic-updates
6288 options = deepmerge__default['default'](options, config.config, {
6289 arrayMerge: function (_destinationArray, sourceArray) { return sourceArray; }
6290 });
6291 // eslint-disable-next-line require-atomic-updates
6292 options.filePath = config.filepath;
6293 }
6294 return [4 /*yield*/, globby__default['default']([].concat(options.files))];
6295 case 2:
6296 foundFiles = _b.sent();
6297 filteredFiles = foundFiles.filter(function (foundFile) { return path__default['default'].extname(foundFile) === ".svg"; });
6298 if (filteredFiles.length === 0) {
6299 throw new Error("Files glob patterns specified did not match any files");
6300 }
6301 return [4 /*yield*/, getGlyphsData(filteredFiles, options)];
6302 case 3:
6303 glyphsData = _b.sent();
6304 ttfOptions = {};
6305 if (options.formatsOptions && options.formatsOptions.ttf) {
6306 ttfOptions = options.formatsOptions.ttf;
6307 }
6308 return [4 /*yield*/, toSvg(glyphsData, options)];
6309 case 4:
6310 svg = _b.sent();
6311 ttf = toTtf(svg, ttfOptions);
6312 result = {
6313 glyphsData: glyphsData,
6314 hash: crypto__default['default'].createHash("md5").update(svg).
6315 digest("hex"),
6316 svg: svg,
6317 ttf: ttf
6318 };
6319 if (options.formats.includes("eot")) {
6320 result.eot = toEot(ttf);
6321 }
6322 if (options.formats.includes("woff")) {
6323 result.woff = toWoff(ttf, { metadata: options.metadata });
6324 }
6325 if (!options.formats.includes("woff2")) return [3 /*break*/, 6];
6326 _a = result;
6327 return [4 /*yield*/, toWoff2(ttf)];
6328 case 5:
6329 _a.woff2 = _b.sent();
6330 _b.label = 6;
6331 case 6:
6332 if (options.template) {
6333 builtInTemplates = getBuiltInTemplates();
6334 templateFilePath = void 0;
6335 if (Object.keys(builtInTemplates).includes(options.template)) {
6336 result.usedBuildInTemplate = true;
6337 builtInPath = path__default['default'].resolve(__dirname, "../..");
6338 nunjucks__default['default'].configure(builtInPath);
6339 templateFilePath = getTemplateFilePath(options.template);
6340 }
6341 else {
6342 resolvedTemplateFilePath = path__default['default'].resolve(options.template);
6343 nunjucks__default['default'].configure(path__default['default'].dirname(resolvedTemplateFilePath));
6344 templateFilePath = path__default['default'].resolve(resolvedTemplateFilePath);
6345 }
6346 hashOption = {};
6347 if (options.addHashInFontUrl) {
6348 hashOption = { hash: result.hash };
6349 }
6350 nunjucksOptions = deepmerge__default['default'].all([
6351 {
6352 glyphs: result.glyphsData.map(function (glyphData) {
6353 if (typeof options.glyphTransformFn === "function") {
6354 glyphData.metadata = options.glyphTransformFn(glyphData.metadata);
6355 }
6356 return glyphData.metadata;
6357 })
6358 },
6359 options,
6360 {
6361 cacheString: options.templateCacheString || Date.now(),
6362 className: options.templateClassName || options.fontName,
6363 fontName: options.templateFontName || options.fontName,
6364 fontPath: options.templateFontPath.replace(/\/?$/u, "/")
6365 },
6366 hashOption,
6367 {
6368 fonts: Object.fromEntries(new Map(options.formats.map(function (format) { return [
6369 format,
6370 function () {
6371 if (format === "woff2") {
6372 return Buffer.from(result.woff2).toString("base64");
6373 }
6374 return result[format].toString("base64");
6375 },
6376 ]; })))
6377 },
6378 ]);
6379 result.template = nunjucks__default['default'].render(templateFilePath, nunjucksOptions);
6380 }
6381 if (!options.formats.includes("svg")) {
6382 delete result.svg;
6383 }
6384 if (!options.formats.includes("ttf")) {
6385 delete result.ttf;
6386 }
6387 result.config = options;
6388 return [2 /*return*/, result];
6389 }
6390 });
6391}); };
6392
6393exports.default = webfont;
6394exports.webfont = webfont;